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
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)
class Checkout: def __init__(self): self.total = 0 self.number_of_a = 0 self.number_of_b = 0 self.receipt = Receipt() def scan(self, sku): if sku == 'A': self.total += 50 self.receipt.scanned_a() elif sku == 'B': self.total += 30 self.receipt.scanned_b() elif sku == "C": self.total += 20 self.receipt.scanned_c() elif sku == "D": self.total += 15 self.receipt.scanned_d() if sku == 'A': self.number_of_a += 1 if self.number_of_a % 3 == 0: self.total -= 20 elif sku == "B": self.number_of_b += 1 if self.number_of_b % 2 == 0: self.total -= 15 def receipt_text(self): return self.receipt.get_text()
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_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])
def read_input(file_name): receipt = Receipt() print "INPUT" with open(file_name) as file: print "Input: %s" % file_name for line in file: print line.strip() quantity, description, price = parse_line(line.strip()) receipt.add(quantity, description, price) print "OUTPUT" print receipt
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
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())
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
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)
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 setUp(self): self.input1_a = Receipt(1, 'book', '12.49') self.input1_b = Receipt(1, 'music CD', '14.99') self.input1_c = Receipt(1, 'chocolate bar', '0.85') self.input2_a = Receipt(1, 'imported box of chocolates', '10.00') self.input2_b = Receipt(1, 'imported bottle of perfume', '47.50') self.input3_a = Receipt(1, 'imported bottle of perfume', '27.99') self.input3_b = Receipt(1, 'bottle of perfume', '18.99') self.input3_c = Receipt(1, 'packet of headache pills', '9.75') self.input3_d = Receipt(1, 'box of imported chocolates', '11.25')
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)
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
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")
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'
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_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'
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 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) }
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
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_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'
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
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()
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))
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('/')
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'
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'
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()
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)
def get(self): user = users.get_current_user() if user != None: user_name = user.nickname() access_link = users.create_logout_url('/') # Get receipt id idReceipt = self.request.get('idReceipt', '') if idReceipt == '': self.redirect('/error?error=El ticket no existe :(') return else: # Get query from database receipt = ndb.Key(urlsafe=idReceipt).get() if receipt == None: self.redirect('/error?error=El ticket no existe :(') return else: # Delete id receipt.key.delete() time.sleep(1) # Get query from database receipts = Receipt.query( Receipt.user == user.user_id()).order(-Receipt.date) 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('/')
def get(self): user = users.get_current_user() if user != None: user_name = user.nickname() access_link = users.create_logout_url('/') # Get receipt id idReceipt = self.request.get('idReceipt', '') if idReceipt == '': self.redirect('/error?error=El ticket no existe :(') return else: # Get query from database receipt = ndb.Key(urlsafe = idReceipt).get() if receipt == None: self.redirect('/error?error=El ticket no existe :(') return else: # Delete id receipt.key.delete() time.sleep(1) # Get query from database receipts = Receipt.query(Receipt.user == user.user_id()).order(-Receipt.date) 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('/')
class TestReceipt(unittest.TestCase): def setUp(self): self.input1_a = Receipt(1, 'book', '12.49') self.input1_b = Receipt(1, 'music CD', '14.99') self.input1_c = Receipt(1, 'chocolate bar', '0.85') self.input2_a = Receipt(1, 'imported box of chocolates', '10.00') self.input2_b = Receipt(1, 'imported bottle of perfume', '47.50') self.input3_a = Receipt(1, 'imported bottle of perfume', '27.99') self.input3_b = Receipt(1, 'bottle of perfume', '18.99') self.input3_c = Receipt(1, 'packet of headache pills', '9.75') self.input3_d = Receipt(1, 'box of imported chocolates', '11.25') def tearDown(self): db = shelve.open('shelve.db') db.clear() db.close() def test_tax_exempt_products(self): self.assertTrue(self.input1_a.product_tax_exempt()) self.assertFalse(self.input1_b.product_tax_exempt()) self.assertTrue(self.input1_c.product_tax_exempt()) self.assertTrue(self.input2_a.product_tax_exempt()) def test_imported_products(self): self.assertTrue(self.input2_a.product_imported()) self.assertFalse(self.input3_b.product_imported()) def test_product_price(self): self.assertEqual(self.input1_a.product_price(), 12.49) self.assertEqual(self.input1_b.product_price(), 16.49) self.assertEqual(self.input2_a.product_price(), 10.50) self.assertEqual(self.input2_b.product_price(), 54.65) self.assertEqual(self.input3_a.product_price(), 32.19) self.assertEqual(self.input3_b.product_price(), 20.89) self.assertEqual(self.input3_c.product_price(), 9.75) self.assertEqual(self.input3_d.product_price(), 11.8) def test_save_receipt_item(self): data = self.input1_a.receipt_save_item('input1') self.assertEqual(len(data['items']), 1) self.assertEqual(data['items'][0]['name'], 'book') def test_save_multiple_items(self): data = self.input1_a.receipt_save_item('input1') self.assertEqual(len(data['items']), 1) data = self.input1_b.receipt_save_item('input1') self.assertEqual(len(data['items']), 2) data = self.input1_c.receipt_save_item('input1') self.assertEqual(len(data['items']), 3) self.assertEqual(data['total'], 29.83) self.assertEqual(data['items'][0]['name'], 'book') def test_retrieve_receipt(self): self.input2_a.receipt_save_item('input2') self.input2_b.receipt_save_item('input2') receipt = self.input2_a.receipt_checkout('input2') self.assertEqual(receipt['total'], 65.15) def test_retrieve_non_existent_receipt(self): self.assertIsNone(self.input3_d.receipt_checkout('input2'))
def populate_provinces_tbl(session): canada = Country("CAN", "Canada") ontario = Province('Ontario','ON', 13) quebec = Province('Quebec','QC', 14.975) canada.provinces = [Province('Alberta','AB', 5), Province('British Columbia','BC', 12), Province('Manitoba','MB', 13), Province('New Brunswick','NB', 13), Province('Newfoundland and Labrador','NL', 13), Province('Northwest Territories','NT', 5), Province('Nova Scotia','NS', 15), Province('Nunavut','NU', 5), ontario, Province('Prince Edward Island','PE', 14), quebec, Province('Saskatchewan','SK', 10), Province('Yukon','YT', 5) ] session.add(canada) #Create test user jhooey = User("Jacob", "Hooey", "jhooey", "password") #Create test Stores loblaws = Store("Loblaws", "Rideau and Nelson", ontario) Maxi = Store("Maxi", "Hull St. Joseph", quebec) herbspice = Store("Herb and Spice Shop", "375 Bank Street", ontario) #Create test Receipts loblaws_receipt1 = Receipt(loblaws) loblaws_receipt2 = Receipt(loblaws, datetime.date.fromordinal(datetime.date.today().toordinal()-1)) loblaws_receipt3 = Receipt(loblaws, datetime.date.fromordinal(datetime.date.today().toordinal()-4)) #Create Test Items bananas = Item('Bananas', 'yellow fruit', False) napkins = Item('Napkins', 'paper napkins', True) #Add items to receipts loblaws_receipt1.add_item(session, bananas, 2, 0.79) loblaws_receipt1.add_item(session, napkins, 1, 2.99) loblaws_receipt2.add_item(session, bananas, 1.54, 0.79) loblaws_receipt3.add_item(session, bananas, 10.2, 0.59) loblaws_receipt3.add_item(session, napkins, 3, 1.99) #Add Receipts to test user jhooey.add_receipt(loblaws_receipt1) jhooey.add_receipt(loblaws_receipt2) jhooey.add_receipt(loblaws_receipt3) session.add_all([ loblaws, Maxi, herbspice, jhooey, bananas, napkins, Category('Food', 'Stuff you eat'), Category('Household Supplies', "Stuff you don't eat") ], ) session.commit()
class TestReceiptMethods(unittest.TestCase): def setUp(self): self.receipt = Receipt() def test_round(self): self.assertAlmostEqual(self.receipt._round(3.81, 0.05), 3.85) self.assertAlmostEqual(self.receipt._round(3.85, 0.05), 3.85) self.assertAlmostEqual(self.receipt._round(3.86, 0.05), 3.90) self.assertAlmostEqual(self.receipt._round(3.9, 0.05), 3.90) def test_imported_food(self): self.receipt.add(1, "imported box of chocolates", 11.25) self.assertAlmostEqual(self.receipt.tax[0], 0.05) self.assertAlmostEqual(self.receipt.calculate_final_price(0), 11.85) def test_local_food(self): self.receipt.add(1, "chocolate bar", 0.85) self.assertAlmostEqual(self.receipt.tax[0], 0.0) self.assertAlmostEqual(self.receipt.calculate_final_price(0), 0.85) def test_imported_general_product(self): self.receipt.add(1, "imported bottle of perfume", 47.5) self.assertAlmostEqual(self.receipt.tax[0], 0.15) self.assertAlmostEqual(self.receipt.calculate_final_price(0), 54.65) def test_general_product(self): self.receipt.add(1, "music CD", 14.99) self.assertAlmostEqual(self.receipt.tax[0], 0.10) self.assertAlmostEqual(self.receipt.calculate_final_price(0), 16.49)
def setUp(self): self.receipt = Receipt()