Example #1
0
            def write_order_row(index, order=None):
                row_format_center = workbook.add_format({
                    'font_size': TEXT_FONT_SIZE,
                    'left': 2,
                    'right': 2,
                    'bottom': 1,
                    'align': 'center',
                })
                row_format_right = workbook.add_format({
                    'font_size': TEXT_FONT_SIZE,
                    'left': 2,
                    'right': 2,
                    'bottom': 1,
                    'align': 'right',
                })
                name, quantity, unit_price = None, 0, 0
                if order:
                    name = order.product.name
                    quantity = order.amount
                    unit_price = order.price
                    if self.withoutIva.get() == 'Sí':
                        unit_price *= (1 - IVA)

                total_order = unit_price * quantity
                if self.currency.get() == 'Bolívares':
                    total_order *= string_to_float(self.rate_entry.get())
                    unit_price *= string_to_float(self.rate_entry.get())
                if total_order == 0:
                    total_order = '-'
                    unit_price = '-'
                worksheet.write(f'A{index}', quantity, row_format_center)
                worksheet.write(f'B{index}', name, row_format_center)
                worksheet.write(f'C{index}', unit_price, row_format_right)
                worksheet.write(f'D{index}', total_order, row_format_right)
Example #2
0
 def calculate_total_sale(self, index, is_detail=False):
     payment = self.payments_tree.item(index)
     sale_type = payment['values'][3]
     amount = payment['values'][4]
     currency = payment['values'][5]
     rate = string_to_float(payment['values'][7])
     if currency == 'Dólares':
         if sale_type == 'Pago':
             self.total_payments += string_to_float(amount)
             self.dollars_payments += string_to_float(amount)
         else:
             self.total_payments -= string_to_float(amount)
             self.dollars_payments -= string_to_float(amount)
         self.total_payments_dollars_label['text'] = number_to_str(
             self.dollars_payments) + "$"
     else:
         if sale_type == 'Pago':
             self.total_payments += (string_to_float(amount) / rate)
             self.bs_payments += string_to_float(amount)
         else:
             self.total_payments -= (string_to_float(amount) / rate)
             self.bs_payments -= string_to_float(amount)
         if is_detail:
             self.total_payments_dollars_label['text'] = number_to_str(
                 self.total_payments) + "$"
         self.total_payments_bs_label['text'] = number_to_str(
             self.bs_payments) + "bs"
Example #3
0
 def create_payments(sale):
     for payment_index in self.payment_handler.payments_tree.get_children():
         payment_values = self.payment_handler.payments_tree.item(payment_index)['values']
         Payment.create(
             sale=sale,
             date=datetime.strptime(payment_values[2], DATE_FORMAT),
             type=Payment.TYPES[payment_values[3]],
             amount=string_to_float(payment_values[4]),
             currency=Payment.CURRENCIES[payment_values[5]],
             method=Payment.METHODS[payment_values[6]],
             rate= string_to_float(payment_values[7]),
             account=Payment.ACCOUNTS[payment_values[8]]
         )
Example #4
0
    def _insert_into_product_tree(self):
        self.product_tree.delete(*self.product_tree.get_children())
        products = Product.select()

        if self.name_entry.get() != '':
            for word in self.name_entry.get().split(" "):
                products = products.select().where(Product.name.contains(word))

        if self.reference_entry.get() != '':
            products = products.select().where(
                Product.reference.contains(self.reference_entry.get()))

        if self.code_entry.get() != '':
            products = products.select().where(
                Product.code.contains(self.code_entry.get()))

        if self.brand_entry.get() != '':
            products = products.select().where(
                Product.brand.contains(self.brand_entry.get()))

        rate = string_to_float(self.rate_entry.get())
        for product in products:
            self.product_tree.insert(
                "",
                index='end',
                values=(product.id, product.brand,
                        product.name, product.reference, product.code,
                        str(product.price) + "$" + " ({}bs)".format(
                            number_to_str(float(product.price) * rate))))
Example #5
0
 def add_payment_to_tree():
     try:
         if not (amount_entry.get()) or (amount_entry.get() == '0'):
             raise Exception("Debes agregar el monto.")
         if currency.get() == 'Bolívares':
             amount_currency = number_to_str(amount_entry.get()) + 'bs'
             if not (rate_entry.get()) or (string_to_float(
                     rate_entry.get()) == 0):
                 raise Exception("Debes especificar la tasa.")
         else:
             amount_currency = number_to_str(amount_entry.get()) + '$'
         type = 'Pago'
         if is_return:
             type = 'Vuelto'
         index = self.payments_tree.insert(
             "",
             index='end',
             value=(None, None, new_payment_date_entry.get(), type,
                    amount_currency, currency.get(), method.get(),
                    rate_entry.get(), account.get()))
         self.calculate_total_sale(index, is_detail)
         self.row_indexes.append(index)
         new_payment_window.destroy()
         if callbacks:
             for callback in callbacks:
                 callback()
     except Exception as err:
         messagebox.showerror("Error", err, parent=new_payment_window)
Example #6
0
 def insert_into_orders_tree(self, product_id, product_name, price, amount, discount, rate):
     amount = float(amount)
     discount = int(discount)
     product_id = product_id
     product_name = product_name
     
     # Getting price.
     product_price = string_to_float(price)
     product_price *= 1 - (discount/100)
     price_to_print = f"{product_price}$"
     total_price = f"{ product_price * amount }$"
     if discount != 0:
         price_to_print += f" - {discount}% (Ya incluído)"
     
     # Insert to Tree.
     self.orders_tree.insert(
         "",
         index=tk.END,
         values=(
             None,
             product_id,
             product_name,
             amount,
             price_to_print,
             total_price,
             rate,
             discount
         )
     )
     for callback in self.callbacks:
         callback()
Example #7
0
 def calculate_remaining(self):
     dollars_order = float(self.order_tree.total_orders_usd)
     total_dollar_payments = self.payment_handler.total_payments
     remaining_dollars = dollars_order - total_dollar_payments
     rate =  string_to_float(self.rate_entry.get())
     remaining_bs = number_to_str(remaining_dollars * rate)
     self.remaining_sale_dollars_label['text'] = number_to_str(remaining_dollars) + "$"
     self.remaining_sale_bs_label['text'] = number_to_str(remaining_bs) + "bs"
Example #8
0
 def calculate_total(self):
     total_orders_usd = 0
     total_orders_bs = 0
     for order_index in self.orders_tree.get_children():
         order_values = self.orders_tree.item(order_index)['values']
         total_order =  get_dollars(order_values[5])
         total_orders_usd += total_order
         if not self.sale:
             rate_order =  string_to_float(order_values[6])
             total_orders_bs += (total_order * rate_order)
     self.total_orders_usd = total_orders_usd
     self.total_orders_bs = total_orders_bs
     self._update_total_labels()
Example #9
0
        def delete_payment_row(callbacks):

            if self.payments_tree.focus():
                index = self.payments_tree.focus()
                payment = self.payments_tree.item(index)
                pay_type = payment['values'][3]
                amount = payment['values'][4]
                currency = payment['values'][5]
                rate = string_to_float(str(payment['values'][7]))

                if currency == 'Dólares':
                    if pay_type == 'Pago':
                        self.total_payments -= string_to_float(amount)
                        self.dollars_payments -= string_to_float(amount)
                    else:
                        self.total_payments += string_to_float(amount)
                        self.dollars_payments += string_to_float(amount)
                    self.total_payments_dollars_label['text'] = number_to_str(
                        self.dollars_payments) + '$'
                else:
                    if pay_type == 'Pago':
                        self.total_payments -= (string_to_float(amount) / rate)
                        self.bs_payments -= string_to_float(amount)
                    else:
                        self.total_payments += (string_to_float(amount) / rate)
                        self.bs_payments += string_to_float(amount)
                    self.total_payments_bs_label['text'] = number_to_str(
                        self.bs_payments) + 'bs'
                if self.payments_tree.item(index)['values'][0] != 'None':
                    self.payments_to_delete.append(
                        self.payments_tree.item(index)['values'][0])
                self.payments_tree.delete(index)
                if sale_id:
                    self.total_payments_dollars_label['text'] = number_to_str(
                        self.total_payments) + '$'
                if callbacks:
                    for callback in callbacks:
                        callback()
Example #10
0
 def PressAnyKey(event):
     # print(event.keycode)
     if event.keycode == 65:
         ProductsWin(
             self.rate_entry.get(), 
             self.order_tree.insert_into_orders_tree,
             callbacks=[
                 self.order_tree.calculate_total,
                 self.calculate_remaining
             ],
         )
     elif event.keycode == 90:
         self.payment_handler.add_payment_window(self.query_date.get(), self.rate_entry.get(), False, callbacks=[self.calculate_remaining])
     elif event.keycode == 88:
         self.payment_handler.add_payment_window(self.query_date.get(), self.rate_entry.get(), True, callbacks=[self.calculate_remaining])
     elif event.keycode == 49:
         FilterPaymentWin(self.query_date)
     elif event.keycode == 50:
         self.display_credit_window()
     elif event.keycode == 51:
         self.display_credit_window(True)
     elif (event.keycode == 66) or (event.keycode == 68):
         # Bolívares > 66 > "ctrl + b"
         # Dólares68 > 68 > "ctrl + d"
         total_orders = float(self.order_tree.total_orders_usd)
         total_payments = float(self.payment_handler.total_payments)
         total_result = total_orders - total_payments
         currencies = {66: "bs", 68: "usd"}
         rate = string_to_float(self.rate_entry.get())
         currency = currencies[event.keycode]
         is_return = total_result < 0
         if currency == "bs":
             total_result *= rate
         if int(total_result) != 0:
             self.payment_handler.add_payment_window(
                 self.query_date.get(), 
                 self.rate_entry.get(), 
                 total=abs(total_result), 
                 currency_option=currency,
                 is_return=is_return,
                 callbacks=[self.calculate_remaining]
             )
Example #11
0
    collection = 'historical_data_daily'

    for colunm in reader:
        if year < 2021:
            for week in calendar.monthcalendar(year, month):
                for day in week:
                    if day != 0:
                        date = utils.format_number(
                            day, 2) + '.' + utils.format_number(
                                month, 2) + '.' + str(year)
                        date = utils.string_to_date(date)
                        if server.db_select(collection, ['date'],
                                            [date]) == None:
                            server.db_insert(
                                collection, ['date', 'br_production'],
                                [date, utils.string_to_float(colunm[1])])
                        else:
                            server.db_update(collection, {"date": date}, {
                                'br_production':
                                utils.string_to_float(colunm[1])
                            })

                        if server.db_select(collection, ['date'],
                                            [date]) == None:
                            server.db_insert(
                                collection, ['date', 'br_plateau_area'],
                                [date, utils.string_to_float(colunm[2])])
                        else:
                            server.db_update(collection, {"date": date}, {
                                'br_plateau_area':
                                utils.string_to_float(colunm[2])
Example #12
0
import server as server
from datetime import timedelta
import utils

with open('../files/dolar_brl_semanal.csv', 'r') as arquivo_csv:
    reader = csv.reader(arquivo_csv, delimiter=',')
    for idx, colunm in enumerate(reader):
        if idx > 1:
            collection = 'historical_data_weekly'
            keys = [
                'date', 'dolar', 'open_dolar', 'max_dolar', 'min_dolar',
                'var_dolar'
            ]
            values = [
                utils.string_to_date(colunm[0]),
                utils.string_to_float(colunm[1]),
                utils.string_to_float(colunm[2]),
                utils.string_to_float(colunm[3]),
                utils.string_to_float(colunm[4]),
                utils.string_to_float(colunm[5])
            ]
            colunm[0] = utils.string_to_date(colunm[0]) - timedelta(days=1)
            if server.db_select(collection, [keys[0]], [values[0]]) == None:
                server.db_insert(collection, keys, values)
            else:
                for i, *_ in enumerate(colunm):
                    if i >= 1:
                        server.db_update(collection, {keys[0]: values[0]},
                                         {keys[i]: values[i]})

with open('../files/dolar_brl_historio.csv', 'r') as arquivo_csv:
Example #13
0
    def create_xlsx(self):
        if self.currency.get() == 'Bolívares' and string_to_float(
                self.rate_entry.get()) == 0:
            messagebox.showerror("Error!",
                                 'No se pudo leer la tasa',
                                 parent=self.resume_window)
        else:
            workbook = xlsxwriter.Workbook(
                f'./resumes/NOTA_DE_ENTREGA_{self.sale_id}.xlsx')
            worksheet = workbook.add_worksheet("NOTA_DE_ENTREGA")

            worksheet.set_column('A:A', 5)
            worksheet.set_column('B:B', 35)
            worksheet.set_column('C:C', 15)
            worksheet.set_column('D:D', 20)

            # TITLE
            ENTERPRISE_NAME = 'COMERCIAL GUERRA C.A.'
            SUBTITLE = 'FERRETERÍA EN GENERAL'
            ADDRESS = 'CALLE SANTA ROSA  TEL: 0293-4310577  CUMANA RIF.J-08013970-4 '

            title_format = workbook.add_format({
                'font_size': 20,
                'align': 'center',
                'bold': True,
            })
            subtitle_format = workbook.add_format({
                'font_size': 16,
                'align': 'center',
            })
            address_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'align': 'center',
            })
            worksheet.merge_range(2, 0, 2, 3, ENTERPRISE_NAME, title_format)
            worksheet.merge_range(3, 0, 3, 3, SUBTITLE, subtitle_format)
            worksheet.merge_range(4, 0, 4, 3, ADDRESS, address_format)

            # HEADER_1

            header_top_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'top': 2,
                'left': 2,
                'right': 2,
                'bold': True,
                'align': 'center',
            })
            header_bottom_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'bottom': 2,
                'left': 2,
                'right': 2,
                'align': 'center',
            })

            CLIENT_NAME_HEADER = 'NOMBRE O RAZÓN SOCIAL'
            worksheet.merge_range(6, 0, 6, 1, CLIENT_NAME_HEADER,
                                  header_top_format)
            worksheet.merge_range(7, 0, 7, 1, self.sale.client.name,
                                  header_bottom_format)

            CLIENT_RIF_HEADER = 'RIF'
            worksheet.write('C7', CLIENT_RIF_HEADER, header_top_format)
            worksheet.write('C8', self.sale.client.identity_card,
                            header_bottom_format)

            CLIENT_PAYMENT_CONDITION = 'CONDICIÓN DE PAGO'
            worksheet.write('D7', CLIENT_PAYMENT_CONDITION, header_top_format)
            worksheet.write('D8', self.option.get(), header_bottom_format)

            # HEADER 2

            CLIENT_ADDRESS_HEADER = 'DIRECCIÓN'
            worksheet.merge_range(8, 0, 8, 1, CLIENT_ADDRESS_HEADER,
                                  header_top_format)
            worksheet.merge_range(9, 0, 9, 1, 'CUMANÁ', header_bottom_format)

            SALE_DATE_HEADER = 'FECHA'
            TODAY = date.today().strftime('%d/%m/%y')
            worksheet.write('C9', SALE_DATE_HEADER, header_top_format)
            worksheet.write('C10', TODAY, header_bottom_format)

            CLIENT_PHONE_HEADER = 'TELÉFONO'
            worksheet.write('D9', CLIENT_PHONE_HEADER, header_top_format)
            worksheet.write('D10', self.sale.client.phone_number,
                            header_bottom_format)

            # # ORDER LIST

            # # Header
            header_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'border': 2,
                'align': 'center',
                'bold': True,
            })
            price_u_header_title = 'PRECIO U. $'
            order_price_header_title = 'MONTO $'
            if self.currency.get() == 'Bolívares':
                price_u_header_title = price_u_header_title.rstrip('$')
                order_price_header_title = order_price_header_title.rstrip('$')
                price_u_header_title += 'BsS'
                order_price_header_title += 'BsS'
            worksheet.write('A11', 'CAN.', header_format)
            worksheet.write('B11', 'DESCRIPCIÓN', header_format)
            worksheet.write('C11', price_u_header_title, header_format)
            worksheet.write('D11', order_price_header_title, header_format)

            def write_order_row(index, order=None):
                row_format_center = workbook.add_format({
                    'font_size': TEXT_FONT_SIZE,
                    'left': 2,
                    'right': 2,
                    'bottom': 1,
                    'align': 'center',
                })
                row_format_right = workbook.add_format({
                    'font_size': TEXT_FONT_SIZE,
                    'left': 2,
                    'right': 2,
                    'bottom': 1,
                    'align': 'right',
                })
                name, quantity, unit_price = None, 0, 0
                if order:
                    name = order.product.name
                    quantity = order.amount
                    unit_price = order.price
                    if self.withoutIva.get() == 'Sí':
                        unit_price *= (1 - IVA)

                total_order = unit_price * quantity
                if self.currency.get() == 'Bolívares':
                    total_order *= string_to_float(self.rate_entry.get())
                    unit_price *= string_to_float(self.rate_entry.get())
                if total_order == 0:
                    total_order = '-'
                    unit_price = '-'
                worksheet.write(f'A{index}', quantity, row_format_center)
                worksheet.write(f'B{index}', name, row_format_center)
                worksheet.write(f'C{index}', unit_price, row_format_right)
                worksheet.write(f'D{index}', total_order, row_format_right)

            DEFAULT_ROWS = 8
            order_row_index = 12
            for order in self.orders:
                write_order_row(order_row_index, order)
                order_row_index += 1

            if len(self.orders) < DEFAULT_ROWS:
                rows_for_fill = DEFAULT_ROWS - len(self.orders)
                for row in range(rows_for_fill):
                    write_order_row(order_row_index)
                    order_row_index += 1

            # # FOOTER

            # # RESUME ID
            RESUME_ID = f'NOTA DE ENTREGA \n NÚMERO {self.sale_id}'
            resume_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'border': 2,
                'align': 'center',
                'valign': 'top',
            })
            worksheet.merge_range(order_row_index - 1, 0, order_row_index + 1,
                                  1, RESUME_ID, resume_format)

            # # ORDERS TOTAL
            top_title_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'align': 'center',
                'top': 2,
                'right': 2,
            })
            middle_title_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'align': 'center',
                'top': 1,
                'right': 2,
            })
            bottom_title_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'align': 'center',
                'top': 2,
                'right': 2,
                'bottom': 2,
                'bold': True,
            })

            iva_title = None
            sub_total_title = 'SUB. TOTAL $'
            total_title = 'TOTAL $'
            if (self.currency.get()
                    == 'Bolívares') and (self.iva.get()
                                         == 'Sí') and (self.withoutIva.get()
                                                       == 'No'):
                iva_title = 'IVA 16%'
            if (self.currency.get() == 'Bolívares'):
                sub_total_title = sub_total_title.rstrip('$')
                sub_total_title += 'BsS'
                total_title = total_title.rstrip('$')
                total_title += 'BsS'
            worksheet.write(f'C{order_row_index}', sub_total_title,
                            top_title_format)
            worksheet.write(f'C{order_row_index + 1}', iva_title,
                            middle_title_format)
            worksheet.write(f'C{order_row_index + 2}', total_title,
                            bottom_title_format)

            top_amount_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'align': 'right',
                'top': 2,
                'right': 2,
            })
            middle_amount_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'align': 'right',
                'top': 1,
                'right': 2,
            })
            bottom_amount_format = workbook.add_format({
                'font_size': TEXT_FONT_SIZE,
                'align': 'right',
                'top': 2,
                'right': 2,
                'bottom': 2,
                'bold': True,
            })

            total = reduce(
                lambda acc, cur: acc + (cur.product.price * cur.amount),
                self.orders, 0)
            if self.withoutIva.get() == 'Sí':
                total *= (1 - IVA)

            sub_total, total_iva = total, None
            if (self.currency.get() == 'Bolívares'):
                total = total * string_to_float(self.rate_entry.get())
                sub_total = total
                if (self.iva.get() == 'Sí') and (self.withoutIva.get()
                                                 == 'No'):
                    sub_total = "%.2f" % (total * (1 - IVA))
                    total_iva = "%.2f" % (total * IVA)

            worksheet.write(f'D{order_row_index}', sub_total,
                            top_amount_format)
            worksheet.write(f'D{order_row_index + 1}', total_iva,
                            middle_amount_format)
            worksheet.write(f'D{order_row_index + 2}', total,
                            bottom_amount_format)

            workbook.close()
            messagebox.showinfo('Nota de entrega',
                                'La nota de entrega se creó exitosamente',
                                parent=self.parent)
            self.resume_window.destroy()
Example #14
0
    def modify_order(self):
        if self.orders_tree.focus():
            order_index = self.orders_tree.focus()
            order_id = self.orders_tree.item(order_index)['values'][0]
            product_name = self.orders_tree.item(order_index)['values'][2]
            amount = self.orders_tree.item(order_index)['values'][3]
            price = self.orders_tree.item(order_index)['values'][4]
            discount = self.orders_tree.item(order_index)['values'][7]
            if discount == 'None':
                discount = 0
            # New window
            modify_order_window = tk.Toplevel(
                width=700,
                height=700,
                padx=30,
                pady=30)
            modify_order_window.title('Modificar orden')
            
            # Title.
            title_label = tk.Label(
                modify_order_window,
                text='Modificar orden',
                font=('calibri', 18, 'bold'))
            title_label.grid(row=0, pady=(10,20))
            
            # Product Name
            product_name_label = tk.Label(
                modify_order_window,
                text=product_name,
                font=('calibri', 16))
            product_name_label.grid(row=1, pady=(0,5))
            
            # Amount.
            amount_label = tk.Label(
                modify_order_window,
                text="Cantidad",
                font=('calibri', 16, 'bold'))
            amount_label.grid(row=2, column=0, pady=(20,3))
            amount_entry = ttk.Entry(
                modify_order_window,
                width=15,
                font=('calibri', 14)
            )
            amount_entry.insert(0, string_to_float(amount))
            amount_entry.grid(row=3, padx=15)

            # Price.
            price_label = tk.Label(
                modify_order_window,
                text="Precio",
                font=('calibri', 16, 'bold'))
            price_label.grid(row=4, column=0, pady=(20,3))
            price_entry = ttk.Entry(
                modify_order_window,
                width=15,
                font=('calibri', 14)
            )
            price =  get_dollars(price)
            price_entry.insert(0, price)
            price_entry.grid(row=5, padx=15)

            # Discount
            discount_label = tk.Label(
                modify_order_window,
                text="Descuento",
                font=('calibri', 16, 'bold'))
            if not self.sale:
                discount_label.grid(row=6, column=0, pady=(20,3))
            discount_entry = ttk.Entry(
                modify_order_window,
                width=15,
                font=('calibri', 14)
            )
            discount_entry.insert(0, discount)
            if not self.sale:
                discount_entry.grid(row=7, padx=15)

            # Functions
            def modify_order_row():
                discount = discount_entry.get()
                total = (float(price_entry.get()) * float(amount_entry.get())) * (1 - (float(discount) / 100))
                if discount == 'None':
                    discount = 0
                self.orders_tree.item(order_index, values=(
                    self.orders_tree.item(order_index)['values'][0],
                    self.orders_tree.item(order_index)['values'][1],
                    self.orders_tree.item(order_index)['values'][2],
                    amount_entry.get(),
                    str(price_entry.get()) + "$",
                    str(total) + "$",
                    self.orders_tree.item(order_index)['values'][6],
                    discount,
                ))
                if order_id != 'None':
                    self.orders_to_update.append(order_index)
                self.calculate_total()
                modify_order_window.destroy()
                if self.callbacks:
                    for callback in self.callbacks:
                        callback()
            
            # Save Button
            modify_button = tk.Button(
                modify_order_window,
                text="Modificar",
                font=('calibri', 12),
                bd=1,
                relief=tk.RIDGE,
                bg='#54bf54',
                padx=30,
                command=modify_order_row)
            modify_button.grid(row=8, column=0, pady=(15,10))
Example #15
0
    def update_sale(self):
        # Sale Info.
        sale_date = self.sale.date.strftime(DATE_FORMAT)
        sale_desc = self.sale.description
        sale_client = self.sale.client

        try:
            if sale_date != self.sale_date_entry.get():
                self.sale.date = datetime.strptime(self.sale_date_entry.get(),
                                                   DATE_FORMAT)

            if sale_desc != self.sale_desc_text.get():
                self.sale.description = self.sale_desc_text.get()

            if sale_client != self.client_handler.client:
                self.sale.client = self.client_handler.client

            if not self.order_tree.orders_tree.get_children():
                raise Exception("No puede existir una venta sin órdenes!")

            for order_index in self.order_tree.orders_tree.get_children():
                if self.order_tree.orders_tree.item(
                        order_index)['values'][0] == 'None':
                    new_order_values = self.order_tree.orders_tree.item(
                        order_index)['values']
                    Order.create(product=new_order_values[1],
                                 sale=self.sale.id,
                                 date=datetime.strptime(TODAY, DATE_FORMAT),
                                 amount=new_order_values[3],
                                 price=get_dollars(new_order_values[5]),
                                 discount=int(new_order_values[7]))

            for payment_index in self.payments_handler.payments_tree.get_children(
            ):
                if self.payments_handler.payments_tree.item(
                        payment_index)['values'][0] == 'None':
                    payment_values = self.payments_handler.payments_tree.item(
                        payment_index)['values']
                    Payment.create(
                        sale=self.sale,
                        date=datetime.strptime(payment_values[2], DATE_FORMAT),
                        type=Payment.TYPES[payment_values[3]],
                        amount=string_to_float(payment_values[4]),
                        currency=Payment.CURRENCIES[payment_values[5]],
                        method=Payment.METHODS[payment_values[6]],
                        rate=string_to_float(payment_values[7]),
                        account=Payment.ACCOUNTS[payment_values[8]])

            for order_index in self.order_tree.orders_to_update:
                updated_order_values = self.order_tree.orders_tree.item(
                    order_index)['values']
                order_id = updated_order_values[0]
                amount = updated_order_values[3]
                # discount = int(updated_order_values[7])
                price = get_dollars(updated_order_values[5])
                order = Order.get(order_id)
                order.amount = amount
                order.price = price
                # order.discount = discount
                order.save()

            for order_id in self.order_tree.orders_to_delete:
                try:
                    order = Order.get(Order.id == order_id)
                    order.delete_instance()
                except Exception as err:
                    pass

            for payment_id in self.payments_handler.payments_to_delete:
                payment = Payment.get(Payment.id == payment_id)
                payment.delete_instance()

            total_sale = float(self.order_tree.total_orders_usd)
            total_payments = float(
                self.payments_handler.total_payments_dollars_label["text"].
                rstrip("$"))
            if es_casi_igual(total_sale, total_payments):
                self.sale.is_finished = True
                self.sale.finished_date = date.today()
            else:
                self.sale.is_finished = False

            self.sale.save()
            self.detail_sale_window.destroy()

            if self.callbacks and self.params:
                self.callbacks[0](self.params)
            elif self.callbacks:
                for callback in self.callbacks:
                    callback(self.query_date)

        except Exception as err:
            messagebox.showerror("Error!", err, parent=self.detail_sale_window)
Example #16
0
import csv
import server as server
import utils

print('\n\nImportando dados Semanais do Preço do Milho\n\n')
with open('../files/milho_br_semanal.csv', 'r') as arquivo_csv:
    reader = csv.reader(arquivo_csv, delimiter = ',')
    for idx, colunm in enumerate(reader):
        if idx > 1:
            date = colunm[0].replace(',','')
            date = date.split(' ')
            date = utils.format_number(date[1], 2) + '.' + utils.format_number(str(utils.mounth_numeric.get(date[0])), 2) + '.' + date[2]

            collection = 'historical_data_weekly'
            keys = ['date', 'corn_br', 'open_corn_br', 'max_corn_br', 'min_corn_br', 'vol_corn_br', 'var_corn_br']
            values = [utils.string_to_date(date), utils.string_to_float(colunm[1]), utils.string_to_float(colunm[2]), utils.string_to_float(colunm[3]), utils.string_to_float(colunm[4]), utils.string_to_float(colunm[5]), utils.string_to_float(colunm[6])]


            if server.db_select(collection, [keys[0]], [utils.string_to_date(date)]) == None:
                server.db_insert(collection, keys, values)
            else:
                for i, *_ in enumerate(colunm):
                    if i >= 1:
                        server.db_update(collection, {keys[0]: values[0]}, {keys[i]: values[i]})

print('\n\nImportando dados Diarios do Preço do Milho\n\n')
with open('../files/milho_br.csv', 'r') as arquivo_csv:
    reader = csv.reader(arquivo_csv, delimiter = ',')
    for idx, colunm in enumerate(reader):
        if idx > 1:
            collection = 'historical_data_daily'