Пример #1
0
    def __init__(self):
        self.receipts = []
        new_csv = False

        try:
            with open("receipts_summation.csv", "r") as csv_file:
                read_file = csv.reader(csv_file,
                                       quoting=csv.QUOTE_NONE,
                                       escapechar="\\")

                for row in list(read_file)[1:]:
                    tags = row[-1]
                    tags = tags.split(" ")
                    self.receipts.append(Receipt(row[:-2], row[-2], tags))

        except FileNotFoundError:
            self.receipts = []
            new_csv = True

        with open("receipts_summation.csv", "a") as file:
            csv_file = csv.writer(file,
                                  quoting=csv.QUOTE_NONE,
                                  escapechar="\\")
            if new_csv:
                csv_file.writerow(["day", "month", "year", "amount", "tags"])

        self.available_tags = []
        for receipt in self.receipts:
            self.available_tags = self.available_tags + receipt.tags
Пример #2
0
    def add_receipt(self):
        # ask if user wants to save receipt again (if was savd before)
        if self.saved:
            self.saved = not(tk.messagebox.askyesno("Are you sure?",
                                                    "Looks like you already did that. Save again?"))

        # save recceipt if validated
        if self.validate_year(self.year_field.get()) and\
        self.validate_day(self.day_field.get()) and not self.saved:
            date = self.day_field.get() + "." + str(self.month_field.curselection()[0]+1)
            date += "." + self.year_field.get()

            tags = self.tags_field.get().split(", ")

            self.controller.database.add_receipt(Receipt(date, self.amount, tags))
            self.update_tags()
            self.saved = True
            self.message.config(text="Receipt saved succesfully!", fg="green")

        # if not validate put feedback in appropriate field
        elif not self.validate_day(self.day_field.get()):
            self.day_field.config(fg="red")
        elif not self.validate_year(self.year_field.get()):
            self.year_field.config(fg="red")

        elif self.saved:
            pass

        # shouldn't really reach this point ever
        # but in case it does display something for the user
        else:
            messagebox.showinfo("Ooops", "Something went wrong")
Пример #3
0
def ocr_receipts(config, receipt_files):
    """
    :param config: ObjectView
        Parsed config file
    :param receipt_files: [] of str
        List of files to parse
    :return: {}
        Stats about files
    """

    stats = defaultdict(int)
    print(VERBOSE_OUTPUT_FORMAT)
    for receipt_path in receipt_files:
        with open(receipt_path) as receipt:
            receipt = Receipt(config, receipt.readlines())
            print(receipt_path, receipt.company, receipt.date, receipt.sum)

            stats["total"] += 1
            if receipt.company:
                stats["company"] += 1
            if receipt.date:
                stats["date"] += 1
            if receipt.sum:
                stats["sum"] += 1
    return stats
Пример #4
0
def test_receipt_saved():
    # 4.6.1.2 Receipt Database Storage
    receiptManager = ReceiptManager()
    new_order = Order(EXISTING_ACCOUNT, STAFF_ACCOUNT)

    new_receipt = Receipt(new_order)

    assert receiptManager.add_receipt(
        new_receipt) == True, 'Receipt has been saved'
Пример #5
0
    def testReceipt_add(self):
        receipt = Receipt()

        barcode = "ITEM000001"
        one_receipt_info = OneReceiptInfo(barcode, 2)

        receipt.add(one_receipt_info)
        self.assertEquals(receipt.receipt_infos[barcode], 2)
        receipt.add(one_receipt_info)
        self.assertEquals(receipt.receipt_infos[barcode], 4)
Пример #6
0
def main(input_csv):
    global fieldnames
    my_receipt = Receipt(fieldnames)

    for item in parse_csv_and_return_item_dict(input_csv, fieldnames):
        if item:
            my_receipt.items.append(item)
        else:
            raise ParsingError("Error parsing input file")

    return my_receipt
    def test_receipt_add_product(self):
        toothbrush = Product("toothbrush", ProductUnit.EACH)
        apples = Product("apples", ProductUnit.KILO)
        receipt_toothbrush = ReceiptItem(toothbrush, 2, 1.5, 3)

        receipt = Receipt()
        receipt.discount = []
        receipt._items = [receipt_toothbrush]
        self.assertEqual(1, len(receipt._items))

        receipt.add_product(apples, 2, 1, 2)
        self.assertEqual(2, len(receipt._items))
Пример #8
0
    def setUpClass(cls):
        cls.instances: List[Instance] = []
        for name in cls.IMAGES_NAMES:
            with open(os.path.join(cls.DATA_PATH, name,
                                   "apiResponse.json")) as f:
                receipt = Receipt(json.load(f), name=name)
            with open(os.path.join(cls.DATA_PATH, name, "result.json")) as f:
                expected = json.load(f)

            im = None if not cls.SHOW else plt.imread(
                os.path.join(cls.DATA_PATH, name, "image.jpg"))
            cls.instances.append(
                Instance(receipt=receipt, expected=expected, im=im))
    def test_receipt_add_discount(self):
        toothbrush = Product("toothbrush", ProductUnit.EACH)
        receipt_toothbrush = ReceiptItem(toothbrush, 2, 1.5, 3)

        discount = Discount(toothbrush, "test", 1.5)

        receipt = Receipt()
        receipt._items = [receipt_toothbrush]
        self.assertEqual(0, len(receipt._discounts))

        receipt.add_discount(discount)
        self.assertEqual(1, len(receipt._discounts))
        self.assertEqual(discount, receipt._discounts[0])
Пример #10
0
    def checks_out_articles_from(self, the_cart):
        receipt = Receipt()
        product_quantities = the_cart.items
        for pq in product_quantities:
            p = pq.product
            quantity = pq.quantity
            unit_price = self.catalog.unit_price(p)
            price = quantity * unit_price
            receipt.add_product(p, quantity, unit_price, price)

        the_cart.handle_offers(receipt, self.offers, self.catalog)

        return receipt
Пример #11
0
    def parse(cls, input_file=_DEFAULT_INPUT_FILE):

        f = open(input_file)

        shopping_list = json.load(f, encoding='GBK')

        receipt = Receipt()

        for each in shopping_list:
            barcode, quantity = cls.parse_line(each)
            one_receipt_info = OneReceiptInfo(barcode, quantity)
            receipt.add(one_receipt_info)
        return receipt
    def test_receipt_total_price(self):
        toothbrush = Product("toothbrush", ProductUnit.EACH)
        apples = Product("apples", ProductUnit.KILO)
        toothbrush_discount = Discount(toothbrush, "my_description", 0.2)
        receipt_toothbrush = ReceiptItem(toothbrush, 2, 1.5, 3)
        receipt_apples = ReceiptItem(apples, 3, 1, 3)

        receipt = Receipt()
        receipt.discounts = [toothbrush_discount]
        receipt.items = [receipt_toothbrush, receipt_apples]
        totalprice = receipt.total_price()

        self.assertEqual([toothbrush_discount], receipt.discounts)
        self.assertEqual(5.8, totalprice)
Пример #13
0
    def get(self):
        order1 = Order()

        form = OrderSandwich()

        #page for receipt
        o = MyOrder()  #import from library.py

        r = Receipt()

        o.addOrder(m)

        self.response.write(form.print_out())
        self.response.write(r.print_out())
Пример #14
0
 def user_receipt(self, filename, id):
     for receipt in self._receipts:
         if receipt.fromjson == filename:
             return False
     new = Receipt()
     new.createReceipt(filename)
     found = False
     for u in self._user:
         if id == u.id:
             u.addReceipt(new)
             self._receipts.append(new)
             #print("test")
             found = True
     return found
Пример #15
0
 def setUp(self):
     test_date = date(2020, 5, 1)
     self.test_receipt = Receipt(test_date, "Home Depot", 55.19, "DISC")
     price_orchid = Price(22.98, 9)
     orchid = Item("Orchid", price_orchid)
     self.test_receipt.add_item(orchid)
     price_lamp_holder = Price(3.78, 9)
     lamp_holder = Item("Lamp Holder", price_lamp_holder)
     self.test_receipt.add_item(lamp_holder)
     price_compressed_air = Price(5.98, 9)
     compressed_air = Item("Compressed Air Can", price_compressed_air)
     self.test_receipt.add_item(compressed_air)
     price_softener = Price(5.97, 9, quantity=3)
     softener_pellets = Item("Softener Pellets", price_softener)
     self.test_receipt.add_item(softener_pellets)
def parse_freeagent_expenses(expenses_string):
    receipts = set()
    for expense in json.loads(expenses_string)['expenses']:
        try:
            filename = expense['attachment']['file_name']
        except KeyError:
            filename = None

        receipts.add(
            Receipt(
                description=expense['description'],
                date=parse_iso_date(expense['dated_on']),
                amount=0 - Decimal(expense['gross_value']),
                filename=filename,
            ))
    return receipts
Пример #17
0
def test_email_has_link_to_account_creation_page():
    # 4.4.1.1 Guest Account Creation
    manager = AccountManager()
    account = Account('*****@*****.**')

    staff_account = Account('*****@*****.**')

    manager.add_account(account)
    manager.add_account(staff_account)

    new_order = Order(account, staff_account)

    order_receipt = Receipt(new_order)

    assert emailUtils.validate_receipt_content(
        order_receipt) == True, 'Redirect Link Found'
Пример #18
0
def add_cost():
    item = input('''
===>What item would you like to add?
    ''')
    cost = input('''
=======>How much you dropping?
        ''')
    freq = input('''
===========>How often are you dropping this?
            (daily, weekly, monthly, once)
            ''')
    r = Receipt()
    r.set_item(item)
    r.set_cost(cost)
    r.set_frequency(freq)
    return r
Пример #19
0
def get_receipts_in_directory(directory):
    LOG.info('Looking in: {}'.format(directory))

    def only_files(partial_filename):
        return os.path.isfile(pjoin(directory, partial_filename))

    for filename_base in filter(only_files, os.listdir(directory)):
        match = match_filename(filename_base)
        if match is not None:
            yield Receipt(filename=pjoin(directory, filename_base),
                          description=tidy_description(
                              match.group('description')),
                          date=reconstruct_date(match.groupdict()),
                          amount=Decimal(match.group('amount')))
        else:
            LOG.warning('Non-matching filename {}'.format(filename_base))
    def test_shopping_handle_offers_no_offers(self):
        catalog = FakeCatalog()
        toothbrush = Product("toothbrush", ProductUnit.EACH)
        receipt_toothbrush = ReceiptItem(toothbrush, 2, 1.5, 3)

        receipt = Receipt()
        receipt.items = [receipt_toothbrush]

        receipt_offers = {}

        cart = ShoppingCart()
        cart._items = [toothbrush]
        cart._product_quantities = {toothbrush: 2}

        cart.handle_offers(receipt, receipt_offers, catalog)
        self.assertEqual([], receipt.discounts)
Пример #21
0
    def generar_receipt(self):
        num_receipt = self.entry_num_receipt.get()
        locality = self.entry_locality_expedition.get()
        amount = self.entry_amount.get()
        date_issue = self.entry_date_expedition.get()
        maturity = self.entry_maturity.get()
        concept = self.entry_concept.get()
        payable = self.entry_payable.get()
        office = self.entry_office.get()
        account_number = self.entry_account_number.get()
        name_shipper = self.entry_name_receipt.get()
        address = self.entry_address_receipt.get()
        population = self.entry_population_receipt.get()

        Receipt(num_receipt, locality, amount, date_issue, maturity, concept,
                payable, office, account_number, address, population,
                name_shipper).generate_pdf()
Пример #22
0
def test_send_receipt_to_guest():
    # 4.4.1 Guest User Receipt
    manager = AccountManager()
    account = Account('*****@*****.**')

    staff_account = Account('*****@*****.**')

    manager.add_account(account)
    manager.add_account(staff_account)

    new_order = Order(account, staff_account)

    order_receipt = Receipt(new_order)

    assert emailUtils.account_exist(
        account) == False, 'Account does not exist'

    assert emailUtils.send_receipt(
        '*****@*****.**', order_receipt) == True, 'Email has been sent'
Пример #23
0
def test_send_receipt_to_existing_account():
    # 4.4.2 Existing User Receipt
    manager = AccountManager()
    account = Account('*****@*****.**')

    staff_account = Account('*****@*****.**')

    manager.add_account(account)
    manager.add_account(staff_account)

    assert emailUtils.account_exist(
        '*****@*****.**') == True, 'Account does exist'

    new_order = Order(account, staff_account)

    order_receipt = Receipt(new_order)

    assert emailUtils.send_receipt(
        '*****@*****.**', order_receipt) == True, 'Email has been sent'
Пример #24
0
def test_save_receipt_record():
    # 4.6 Save Receipt Record
    receiptManager = ReceiptManager()
    manager = AccountManager()
    account = Account('*****@*****.**')

    staff_account = Account('*****@*****.**')

    manager.add_account(account)
    manager.add_account(staff_account)

    assert emailUtils.account_exist(
        '*****@*****.**') == True, 'Account does exist'

    new_order = Order(account, staff_account)

    order_receipt = Receipt(new_order)
    receiptManager.add_receipt(order_receipt)

    assert receiptManager.get_receipt_information(order_receipt)
Пример #25
0
def test_account_information_in_email_content():
    # 4.5.1 Email Information for Account
    manager = AccountManager()
    account = Account('*****@*****.**')

    staff_account = Account('*****@*****.**')

    manager.add_account(account)
    manager.add_account(staff_account)

    assert emailUtils.account_exist(
        '*****@*****.**') == True, 'Account does exist'

    new_order = Order(account, staff_account)

    order_receipt = Receipt(new_order)
    order_receipt.content = 'Valid Email Content'

    assert emailUtils.validate_receipt_content(
        order_receipt.content) == True, 'Email Content is valid'
Пример #26
0
def label_for_datasets(path, datasets, force=False):
    processed = os.path.join(os.path.dirname(path),
                             ".{}.processed".format(os.path.basename(path)))

    if os.path.exists(processed) and not force:
        return

    receipt = Receipt(path)

    try:
        for dataset in datasets:
            # Stop processing if an earlier labeler requests it
            if not dataset.ingest(receipt):
                break

    except SkipInput:
        print("Skipping!")

    # touch the touchfile
    open(processed, "w").close()
Пример #27
0
def test_view_receipt_as_staff():
    # 4.9.1 Receipt View Access
    orderManager = OrderManager()
    manager = AccountManager()
    receiptManager = ReceiptManager()

    account = Account('*****@*****.**')
    staff_account = Account('*****@*****.**')

    manager.add_account(account)
    manager.add_account(staff_account)

    new_order = Order(account, staff_account)
    orderManager.add_order(new_order)

    order_receipt = Receipt(new_order)
    receiptManager.add_receipt(order_receipt)

    all_receipts = receiptManager.get_all_receipts(staff_account)

    assert all_receipts[0].received_by == staff_account, 'Receipt for Staff found'
Пример #28
0
def lambda_handler(event, context):
    bucket = "elasticbeanstalk-us-east-2-693859464061"
    document = "receipts/DSC_3607.JPG"
    document = event["path"]
    client = boto3.client('textract')

    # process using S3 object
    response = client.detect_document_text(
        Document={'S3Object': {
            'Bucket': bucket,
            'Name': document
        }})

    # Get the text blocks
    # blocks=response['Blocks']
    receipt = Receipt(response)
    receipt.analyze()

    return {
        'statusCode': 200,
        'response': json.dumps(receipt.get_json()),
        # 'body': json.dumps(response)
    }
Пример #29
0
	def post(self):
		user = users.get_current_user()

		if user != None:
			user_name = user.nickname()
			access_link = users.create_logout_url('/')

			# Get values from inputs and save into database
			concept = self.request.get('conceptReceiptAdd')
			price = float(self.request.get('priceReceiptAdd'))
			date = datetime.strptime(self.request.get('dateReceiptAdd'), '%Y-%m-%d')

			# Store data into database
			receipt = Receipt()

			receipt.user = user.user_id()
			receipt.concept = concept
			receipt.price = price
			receipt.date = date

			receipt.put()

			time.sleep(1)

			# Get query from database
			receipts = Receipt.query()

			template_values = {
				'user_name' : user_name,
				'access_link' : access_link,
				'receipts' : receipts
			}

			template = JINJA_ENVIRONMENT.get_template('showReceipt.html')
			self.response.write(template.render(template_values));
		else:
			self.redirect('/')
Пример #30
0
from item import Item
from receipt import Receipt
flag = "yes"
totalPrice = 0
rate = 0.07
r1 = Receipt(rate)
tax = 0
print("Welcome to the receipt creator")
while(flag == "yes"):
    name = input("Enter item name: ")
    price = float(input("Enter item price: "))
    taxable = input("Is the item taxable (yes/no): ")
    if(taxable == "yes"):
        __taxable = True
        
    else:
        __taxable = False
    
    i1= Item(name, price, __taxable)
    r1.addItem(i1)
    flag = input("Add another item (yes/no):")
    totalPrice = price + totalPrice
print(r1)
for i in range(0, len(r1._Receipt__purchases)):
    print(r1._Receipt__purchases[i])
for i in range(0, len(r1._Receipt__purchases)):
    if(r1._Receipt__purchases[i]._Item__taxable == True):
        tax = tax + (r1._Receipt__purchases[i]._Item__price * rate)
subTotal = tax + totalPrice

print()