Esempio n. 1
0
class EntryField(FloatLayout):
    now = datetime.now()
    which_day = now.strftime('%d')
    which_month = now.strftime('%m')
    which_year = now.strftime("%Y")
    year_path = os.path.join('storage', str(which_year))
    month_path = os.path.join(year_path, str(which_month))
    day_path = os.path.join(month_path, str(which_day))
    Path('storage').mkdir(exist_ok=True)
    Path(year_path).mkdir(exist_ok=True)
    Path(month_path).mkdir(exist_ok=True)
    wb_complete_path = f"{day_path}.xlsx"
    cols_list = [
        'Sale', 'Sale Time', 'Amount', 'Selling Price', 'Profit',
        'Buying Price', 'Description'
    ]

    if not Path(wb_complete_path).is_file():
        new_wb = opx.Workbook()
        for i, v in enumerate(cols_list, 1):
            new_wb.active.cell(row=1, column=i, value=v)

        new_wb.save(wb_complete_path)
        new_wb.close()

    load_wb = opx.load_workbook(wb_complete_path)
    ws = load_wb.active

    def __init__(self, title, grp, categories=['Alfa', 'Touch'], **kwargs):
        super().__init__(**kwargs)

        self.grp = grp
        self.categories = categories
        self.title = title
        self.label_color = '#231123'  # as same as background color

        self.title_label = Label(text=f'[b]{self.title.upper()}[/b]',
                                 pos_hint={
                                     'x': 0.5,
                                     'y': 0.94
                                 },
                                 font_size=20,
                                 markup=True,
                                 color=get_color_from_hex(self.label_color),
                                 size_hint=(0, 0))
        self.add_widget(self.title_label)

        self.tglbox1 = BoxLayout(orientation='horizontal',
                                 pos_hint={
                                     'x': 0.005,
                                     'y': 0.83
                                 },
                                 size_hint=(0.6, 0.06))

        self.tglbtn1 = CheckBox(group=self.grp, size_hint=(0.2, 1))
        self.tglbox1.add_widget(self.tglbtn1)

        self.tglbtn1_lbl = Label(text=self.categories[0],
                                 size_hint=(0.2, 1),
                                 font_size=17)
        self.tglbox1.add_widget(self.tglbtn1_lbl)
        self.add_widget(self.tglbox1)

        self.tglbox2 = BoxLayout(orientation='horizontal',
                                 pos_hint={
                                     'x': 0.005,
                                     'y': 0.74
                                 },
                                 size_hint=(0.6, 0.06))

        self.tglbtn2 = CheckBox(group=self.grp, size_hint=(0.2, 1))
        self.tglbox2.add_widget(self.tglbtn2)

        self.tglbtn2_lbl = Label(text=self.categories[1],
                                 size_hint=(0.2, 1),
                                 font_size=17)
        self.tglbox2.add_widget(self.tglbtn2_lbl)
        self.add_widget(self.tglbox2)

        self.amt_box = BoxLayout(
            orientation='vertical',
            size_hint=(1, 0.1),
            pos_hint={
                'x': 0.02,
                'y': 0.51
            },
        )

        self.amt_label = Label(text='Amount:', size_hint=(0.34, 0.25))
        self.amt_box.add_widget(self.amt_label)

        self.amt_input = ModifiedTextInput(size_hint=(0.34, 0.35),
                                           input_filter='int',
                                           text='1')
        self.amt_box.add_widget(self.amt_input)
        self.add_widget(self.amt_box)

        self.price_box = BoxLayout(orientation='vertical',
                                   size_hint=(0.9, 0.1),
                                   pos_hint={
                                       'x': 0.02,
                                       'y': 0.31
                                   })

        self.price_label = Label(text='Price:', size_hint=(0.2, 0.25))
        self.price_box.add_widget(self.price_label)

        self.price = ModifiedTextInput(hint_text='10000',
                                       size_hint=(0.55, 0.35),
                                       input_filter='int')
        self.price_box.add_widget(self.price)
        self.add_widget(self.price_box)

        self.cardtypes = ['Small', 'Big', 'Emergency', 'Start']
        self.card_choose = Spinner(
            text=self.cardtypes[0],
            values=self.cardtypes,
            pos_hint={
                'x': 0.02,
                'y': 0.58
            },
            size_hint=(0.95, 0.08),
            background_normal='',
            background_color=get_color_from_hex('#231123'),
            sync_height=True,
            text_autoupdate=True)

        self.bp_box = BoxLayout(orientation='vertical',
                                size_hint=(0.9, 0.1),
                                pos_hint={
                                    'x': 0.02,
                                    'y': 0.18
                                })

        self.bp_label = Label(text='Buying Price:', size_hint=(0.45, 0.25))
        self.bp_box.add_widget(self.bp_label)

        self.bp = ModifiedTextInput(hint_text='10000',
                                    size_hint=(0.55, 0.35),
                                    input_filter='int')
        self.bp_box.add_widget(self.bp)

        self.product_box = BoxLayout(orientation='vertical',
                                     size_hint=(0.9, 0.13),
                                     pos_hint={
                                         'x': 0.02,
                                         'y': 0.59
                                     })

        self.product_label = Label(text='Product Name:',
                                   size_hint=(0.55, 0.25))
        self.product_box.add_widget(self.product_label)

        self.product_name = ModifiedTextInput(hint_text='Samsung S9+',
                                              size_hint=(1, 0.7))
        self.product_name.font_size = 15
        self.product_name.multiline = True
        self.product_box.add_widget(self.product_name)

        self.addbtn = AddButton(pos_hint={
            'x': 0.3,
            'y': 0
        },
                                size_hint=(0.35, 0.14))
        self.add_widget(self.addbtn)
        self.addbtn.bind(on_press=self.callback)

    def callback(self, ins):
        print(ins)
        self.add_to_sheet()

    def add_to_sheet(self):
        self.background_color = get_color_from_hex('#9e2020')
        self.checked_box = ''

        if self.tglbtn1._get_active():
            self.checked_box = self.categories[0]

        elif self.tglbtn2._get_active():
            self.checked_box = self.categories[1]

        else:
            return self.error_popup(
                f'Please Choose {self.categories[0]} or {self.categories[1]}')

        if not self.price.text or not self.amt_input.text:
            return self.error_popup('Fields cannot be empty')

        if self.title.lower() == 'dollars':
            alltext = f'{self.checked_box.lower()} {self.title.lower()}'
            existing = AmountsField.existing_amounts_dict[alltext]
            company_take = AmountsField.existing_amounts_dict[
                f'{self.checked_box.lower()} dollars taken'][1]

            if (existing[0] - (int(self.amt_input.text) + company_take)) < 0:
                return self.error_popup()

            if (int(self.price.text) / int(self.amt_input.text)) < existing[1]:
                return self.error_popup(
                    'Cannot sell for less than buying price')

            existing[0] -= (float(self.amt_input.text) + company_take)
            AmountsField.labels_dict[
                alltext].text = f'{alltext.capitalize()}: {format(existing[0], ".2f")}'

            self.add_row(alltext.capitalize(), existing[1])

        elif self.title.lower() == 'days':
            ind = f'{self.checked_box.lower()} big cards'
            existing_bc = AmountsField.existing_amounts_dict[ind]
            if int(self.amt_input.text) > existing_bc[0]:
                return self.error_popup()

            days_price = AmountsField.existing_amounts_dict[
                f'{self.checked_box.lower()} {self.title.lower()}'][1]

            if (int(self.price.text) / int(self.amt_input.text)) < days_price:
                return self.error_popup(
                    'Cannot sell for less than buying price')

            existing_bc[0] -= int(self.amt_input.text)
            AmountsField.labels_dict[
                ind].text = f'{ind.capitalize()}: {int(existing_bc[0])}'

            self.add_row(f'{self.checked_box.lower()} {self.title.lower()}',
                         days_price)

        elif self.title.lower() == 'cards':
            type_of_card = f'{self.checked_box.lower()} {self.card_choose.text.lower()} {self.title.lower()}'
            existing_card = AmountsField.existing_amounts_dict[type_of_card]

            if int(self.amt_input.text) > existing_card[0]:
                return self.error_popup()

            if (int(self.price.text) /
                    int(self.amt_input.text)) < existing_card[1]:
                return self.error_popup(
                    'Cannot sell for less than buying price')

            existing_card[0] -= int(self.amt_input.text)
            AmountsField.labels_dict[
                type_of_card].text = f'{type_of_card.capitalize()}: {int(existing_card[0])}'
            self.add_row(type_of_card, existing_card[1])

        elif self.title.lower() == 'other':
            self.add_row(self.checked_box, int(self.bp.text), True)

        self.load_wb.save(self.wb_complete_path)
        with open('.storage.json', 'w') as f:
            json.dump(AmountsField.existing_amounts_dict, f)

    def error_popup(self,
                    error_text='You can\'t sell more than what you have!'):
        popup_label = Label(text=error_text, font_size=22)

        return Popup(title='Error', content=popup_label,
                     size_hint=(0.45, 0.4)).open()

    def add_row(self, name, buying_price, is_phone_acc=False):
        max_row = self.ws.max_row + 1
        self.ws['A' + str(max_row)] = name
        self.ws['B' +
                str(max_row)] = f"{datetime.now().strftime('%H: %M: %S')}"
        self.ws['C' + str(max_row)] = self.amt_input.text
        self.ws['D' + str(max_row)] = self.price.text
        total_buying_price = (buying_price * int(self.amt_input.text))
        self.ws['E' + str(max_row)] = int(self.price.text) - total_buying_price
        self.ws['F' + str(max_row)] = total_buying_price
        TotalSelledField.totals[f"{datetime.now().strftime('%d')}"][1] += int(
            self.price.text)

        with open(TotalSelledField.totals_path, 'w') as f:
            json.dump(TotalSelledField.totals, f)

        if is_phone_acc:
            self.ws['G' + str(max_row)] = self.product_name.text
            self.product_name.text = ''
            self.bp.text = ''
        self.price.text = ''
        self.amt_input.text = '1'
        self.tglbtn1._set_active(False)
        self.tglbtn2._set_active(False)
Esempio n. 2
0
class EditPopup(Popup):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.size_hint = (0.45, 0.5)
        self.title = 'Edit'
        self.title_align = 'center'
        self.title_color = get_color_from_hex('#00FF00')
        self.title_size = 19

        self.inlayout = FloatLayout(size_hint=(1, 1),
                                    pos_hint={
                                        'x': 0,
                                        'y': 0
                                    })

        self.labels = [
            txt.upper() for txt in AmountsField.existing_amounts_dict.keys()
        ]

        self.to_be_edited = Spinner(size_hint=(0.45, 0.25),
                                    pos_hint={
                                        'x': 0.05,
                                        'y': 0.6
                                    },
                                    values=self.labels,
                                    text=self.labels[0],
                                    sync_height=True)
        self.to_be_edited.bind(on_press=self.on_spinner_text)

        self.inlayout.add_widget(self.to_be_edited)
        self.add_widget(self.inlayout)

        # Plus Box.
        self.plus_box = BoxLayout(size_hint=(0.25, 0.1),
                                  orientation='horizontal',
                                  pos_hint={
                                      'x': 0.55,
                                      'y': 0.77
                                  })

        self.plus_checkbox = CheckBox(size_hint=(0.2, 1), group='plusminus')
        self.plus_box.add_widget(self.plus_checkbox)

        self.plus_label = Label(text='Plus', size_hint=(0.2, 1), font_size=19)
        self.plus_box.add_widget(self.plus_label)
        self.inlayout.add_widget(self.plus_box)

        # Minus Box.
        self.minus_box = BoxLayout(size_hint=(0.25, 0.1),
                                   orientation='horizontal',
                                   pos_hint={
                                       'x': 0.55,
                                       'y': 0.62
                                   })

        self.minus_checkbox = CheckBox(size_hint=(0.2, 1), group='plusminus')
        self.minus_box.add_widget(self.minus_checkbox)

        self.minus_label = Label(text='Minus',
                                 size_hint=(0.2, 1),
                                 font_size=19)
        self.minus_box.add_widget(self.minus_label)
        self.inlayout.add_widget(self.minus_box)

        # Price change.
        self.price_box = BoxLayout(size_hint=(0.35, 0.1),
                                   orientation='horizontal',
                                   pos_hint={
                                       'x': 0.555,
                                       'y': 0.47
                                   })

        self.price_checkbox = CheckBox(size_hint=(0.2, 1), group='plusminus')
        self.price_box.add_widget(self.price_checkbox)

        self.price_label = Label(text='Price Change',
                                 size_hint=(0.4, 1),
                                 font_size=19)
        self.price_box.add_widget(self.price_label)
        self.inlayout.add_widget(self.price_box)

        self.input_label = Label(pos_hint={
            'x': 0.16,
            'y': 0.33
        },
                                 size_hint=(0, 0),
                                 text='[b][u]Amount[/u]:[/b]',
                                 markup=True,
                                 font_size=20)
        self.inlayout.add_widget(self.input_label)

        self.input_num = ModifiedTextInput(input_filter='float',
                                           pos_hint={
                                               'x': 0.05,
                                               'y': 0.15
                                           },
                                           size_hint=(0.5, 0.12))
        self.inlayout.add_widget(self.input_num)

        self.popup_btn = Button(pos_hint={
            'x': 0.7,
            'y': 0.1
        },
                                size_hint=(0.25, 0.2),
                                text='Apply',
                                font_size=20)
        self.inlayout.add_widget(self.popup_btn)

        self.popup_btn.bind(on_press=self.on_popup_btn_press)
        self.price_checkbox.bind(on_press=self.price_cb_onpress)

    def on_spinner_text(self, spn):
        self.price_checkbox.state = 'normal'

    def price_cb_onpress(self, ins):
        self.input_num.text = str(AmountsField.existing_amounts_dict[
            self.to_be_edited.text.lower()][1])

    def on_popup_btn_press(self, btn):

        self.edited_title = self.to_be_edited.text.lower()
        self.current_value = AmountsField.existing_amounts_dict[
            self.edited_title]

        try:
            edit_number = float(self.input_num.text)
        except ValueError:
            edit_number = 1

        if self.edited_title in ['alfa days', 'touch days'
                                 ] and self.price_checkbox.state != "down":
            days_add_text = '[b]Cannot Add/Remove Days![/b]'
            return self._label_popup('Error', days_add_text)

        elif self.minus_checkbox._get_active():
            self.current_value[0] -= edit_number
            self._update_text()

        elif self.plus_checkbox._get_active():
            self.current_value[0] += edit_number
            self._update_text()

        elif self.price_checkbox._get_active():
            self.current_value[1] = float(self.input_num.text)

        else:
            empty_field_text = 'Please Choose [b]Minus[/b], [b]Plus[/b]\nor [b]Change Price[/b]'
            return self._label_popup('Error', empty_field_text)

        with open('.storage.json', 'w') as f:
            json.dump(AmountsField.existing_amounts_dict, f)

    def _update_text(self):
        what_text = self.edited_title
        if what_text in ['alfa dollars', 'touch dollars']:
            text_to_be = f'{what_text.capitalize()}: {format(self.current_value[0], ".2f")}'
        else:
            text_to_be = f'{what_text.capitalize()}: {int(self.current_value[0])}'
        AmountsField.labels_dict[self.edited_title].text = text_to_be

    def _label_popup(self, title, text):
        return Popup(title=title,
                     size_hint=(0.35, 0.35),
                     content=Label(text=text, font_size=20,
                                   markup=True)).open()