Example #1
0
    def testCreateInvoice(self):
        filtered_entries = TimeEntry.query(self.entries, 'Company1')
        invoice = Invoice(filtered_entries, None, (None, None), self.company1_jobs)
        self.assertEqual(invoice.hours_total, 3)

        filtered_entries = TimeEntry.query(self.entries, 'Company2')
        invoice = Invoice(filtered_entries, None, (None, None), self.company2_jobs)
        self.assertEqual(invoice.hours_total, 4.9)

        filtered_entry_ids = [e.id for e in filtered_entries]
        self.assertEqual(sorted(invoice.entry_ids), sorted(filtered_entry_ids))
Example #2
0
    def testInvoicePayperiod(self):
        invoice = Invoice([],
                          _dt(2019,2,18),
                          (_dt(2019,2,4), _dt(2019,2,17)), self.company1_jobs)

        self.assertEqual(invoice.payperiod_start, _dt(2019,2,4))
        self.assertEqual(invoice.payperiod_end, _dt(2019,2,17))

        invoice = Invoice([],
                          None,
                          (_dt(2019,2,1), _dt(2019,2,28)), self.company1_jobs)
        self.assertEqual(invoice.payperiod_start, _dt(2019,2,1))
        self.assertEqual(invoice.payperiod_end, _dt(2019,2,28))
Example #3
0
    def test_init(self):
        """Ensure that the invoice acquires the correct attributes from the __init__ method

        Also ensure an error is raised if an invalid ID is used"""
        invoice = Invoice(424)
        self.assertEqual(invoice.pdf_file, 'pdfs/424.pdf')
        self.assertEqual(invoice.date, datetime.date(1990, 2, 5))
        # TODO: After implementation of __eq__ in Person
        # self.assertEqual(invoice.payer, Person('test_payer'))
        # self.assertEqual(invoice.payee, Person('test_payee'))
        self.assertEqual(invoice.amount, 40.7)
        self.assertEqual(invoice.name, '0424')
        with self.assertRaises(KeyError):
            Invoice(9895)
Example #4
0
def invoice(request):

    if request.method == 'POST':
        form = DatePickerForm(request.POST)

        if form.is_valid():
            month = request.POST['month']
            year = request.POST['year']
            client = request.POST['client']

            if client:
                client = Client.objects.filter(pk=client)
            else:
                client = None

            invoice = Invoice(int(year), int(month))
            invoice.calculateInvoice(client)

            return render_to_response(
                'invoice-success.html', {
                    'listName': invoice.getListFilename(),
                    'invoiceName': invoice.getInvoiceFilename()
                },
                context_instance=RequestContext(request))
        else:
            return HttpResponse('Invalid form data.' + str(form))

    form = DatePickerForm()
    return render_to_response('invoice.html', {'form': form},
                              context_instance=RequestContext(request))
Example #5
0
 def getInvoice(self,
                rid,
                client,
                invoice_state="unpaid",
                invoice_date=None):
     client = self.client_dao.getClient(client)
     return Invoice(rid, client, invoice_state, invoice_date)
Example #6
0
def calculateSaldos(request):

    if request.method == 'POST':
        form = DatePickerForm(request.POST)

        if form.is_valid():
            month = request.POST['month']
            year = request.POST['year']

            invoice = Invoice(int(year), int(month))
            invoices = invoice.calculateSaldos()

            clientFormSet = modelformset_factory(Client)

        return render_to_response('saldos.html', {
            'invoices': invoices,
            'title': 'Saldos'
        },
                                  context_instance=RequestContext(request))
    else:
        form = DatePickerForm()
        return render_to_response('date-picker.html', {
            'form': form,
            'formAction': '/admin/newspaper/saldos/',
            'title': 'Saldos'
        },
                                  context_instance=RequestContext(request))
Example #7
0
def invoice_create():
    raw_receiver = ''
    raw_date = ''
    raw_net_price = ''
    raw_tax = ''
    raw_vat_id = ''

    try:
        raw_receiver = request.form.get('receiver')
        raw_date = request.form.get('date')
        raw_net_price = request.form.get('net')
        raw_tax = request.form.get('tax')
        raw_vat_id = request.form.get('vatid')
    except ValueError:
        return 'parameter is missing', 500
    
    check_parameter_string_empty(raw_receiver)
    check_parameter_string_empty(raw_date)
    check_parameter_string_empty(raw_net_price)
    check_parameter_string_empty(raw_tax)
    check_parameter_string_empty(raw_vat_id)

    net_price = float(raw_net_price)
    value_added_tax = float(raw_tax)
    invoice_date = raw_date
    receiver = raw_receiver
    vat_id = raw_vat_id

    invoice = Invoice(receiver, net_price, invoice_date=invoice_date, vat_id=vat_id, value_added_tax=value_added_tax)
    invoice.apply_vat_regulation()

    response = make_response(create_PDF(invoice))
    response.headers.set('Content-Disposition', 'attachment', filename='invoice' + '.pdf')
    response.headers.set('Content-Type', 'application/pdf')
    return response
Example #8
0
    def testSendInvoice(self):
        """Asserting the invoiced_dt value is weird, like what am I
           trying to prove?  So far, it's only use is being printed in
           text; of interest for future record keeping?  I don't
           really have a personal need for send(), so it's just this
           kinda-academic thing I thought an invoice should have.  And
           I think that uncertainty shows in this lame test.

        """
        
        filtered_entries = TimeEntry.query(self.entries, 'Company1')
        invoice = Invoice(filtered_entries, None, (None, None), self.company1_jobs)

        send_start = _dt.now()
        invoice.send()
        send_end = _dt.now()

        self.assertLess(send_start, invoice.invoiced_dt)
        self.assertGreater(send_end, invoice.invoiced_dt)

        for entry in invoice.entries:
            self.assertFalse(entry.can_be_invoiced())
            self.assertEqual(entry.invoiced_dt, invoice.invoiced_dt)

        self.assertTrue(invoice.sent)
Example #9
0
    def __init__(self, filename, **kwargs):
        self.filename = filename
        self.wb = load_workbook(filename)

        self.contract = Contract(self.wb.get_sheet_by_name(self.CONTRACT))
        self.invoice = Invoice(self.wb.get_sheet_by_name(self.INVOICE))
        self.details = Details(self.wb.get_sheet_by_name(self.DETAILS))
Example #10
0
 def test_initialize_default_folders_and_files_where_home_path_exist_but_not_folder_dot_invoice(
         self):
     # initialize
     dir = tempfile.mkdtemp()
     invoice = Invoice()
     # test
     result = invoice.initialize_default_folders_and_files(dir)
     # verify
     self.assertEqual(len(result), 6)
     try:
         self.assertTrue(result.index("HOME_PATH_DOES_NOT_EXIST") >= 0)
         self.fail("ValueError expected.")
     except ValueError:
         pass
     self.assertTrue(result.index("HOME_PATH_DOES_EXIST") >= 0)
     dot_invoice_folder_path = join(dir, ".invoice")
     self.assertEqual(exists(dot_invoice_folder_path), True)
     self.assertTrue(result.index("DOT_INVOICE_FOLDER_CREATED") >= 0)
     invoice_file_path = join(dot_invoice_folder_path, "invoice.txt")
     self.assertEqual(exists(invoice_file_path), True)
     self.assertTrue(result.index("INVOICE_FILE_CREATED") >= 0)
     company_file_path = join(dot_invoice_folder_path, "company.txt")
     self.assertEqual(exists(company_file_path), True)
     self.assertTrue(result.index("COMPANY_FILE_CREATED") >= 0)
     automatic_invoice_file_path = join(dot_invoice_folder_path,
                                        "automatic_invoice.txt")
     self.assertEqual(exists(automatic_invoice_file_path), True)
     self.assertTrue(result.index("AUTOMATIC_INVOICE_FILE_CREATED") >= 0)
     periodic_invoice_file_path = join(dot_invoice_folder_path,
                                       "periodic_invoice.txt")
     self.assertEqual(exists(periodic_invoice_file_path), True)
     self.assertTrue(result.index("PERIODIC_INVOICE_FILE_CREATED") >= 0)
     # cleanup
     shutil.rmtree(dir)
     return
    def test_get_mean_rounded_up(self):
        """
        It should compute the mean of the added invoices.
        Here, the raw mean is 4.8375, so `get_mean` should return 4.84.
        """
        invoices = [
            Invoice(1, 23),
            Invoice(3, 45),
            Invoice(6, 78),
            Invoice(7, 89)
        ]
        invoice_stats = InvoiceStats()
        invoice_stats.add_invoices(invoices)
        mean = invoice_stats.get_mean()

        self.assertEqual(mean, 4.84)
Example #12
0
    def test_is_invoice_released_dao_raises_value_error(self) -> None:
        mock_dao = Mock(spec=InvoiceDataAccessObject)
        mock_dao.lookup_status.side_effect = ValueError(
            'No invoice with ID 1234')

        invoice = Invoice(1234, date.today(), mock_dao)

        assert not invoice.is_invoice_released()
Example #13
0
 def get_open_invoices_of_type(self, inv_type):
     is_sales = (inv_type == 'Sales Invoice')
     invs = gui_api_wrapper(\
             Api.api.get_list,inv_type,
             filters={'status':['in',['Unpaid','Overdue']],
                      'company':self.name},
             limit_page_length=LIMIT)
     return list(map(lambda inv: Invoice(inv, is_sales), invs))
    def test_get_median_rounded_down(self):
        """
        It should compute the median of the added invoices.
        Half a cent should round down.
        Here, the raw median is 5.115, so `get_median` should return 5.11.
        """
        invoices = [
            Invoice(1, 23),
            Invoice(3, 45),
            Invoice(6, 78),
            Invoice(7, 89)
        ]
        invoice_stats = InvoiceStats()
        invoice_stats.add_invoices(invoices)
        median = invoice_stats.get_median()

        self.assertEqual(median, 5.11)
Example #15
0
 def test_delete_pdf(self):
     """Ensure that a PDF was deleted by checking the file path"""
     invoice = Invoice(424)
     invoice.pdf_file = 'tests/invoices/delete_test.pdf'
     with self.app.app_context():
         invoice.build_pdf()
     invoice.delete_pdf()
     self.assertFalse(os.path.isfile('tests/invoices/build_test.pdf'))
Example #16
0
 def test_build(self):
     """Builds a PDF and ensures it was properly created"""
     invoice = Invoice(424)
     invoice.pdf_file = 'tests/invoices/build_test.pdf'
     with self.app.app_context():
         invoice.build_pdf()
     self.assertTrue(os.path.isfile('tests/invoices/build_test.pdf'))
     invoice.delete_pdf()
Example #17
0
def main():
    i = Invoice()
    data = i.get_processed_data()
    b = Bundle()

    # Create separate files split by sender IBAN
    for send_iban in settings.SENDER_IBAN:
        content = b.generate(data, send_iban)
        b.save_to_disk(send_iban, content)
Example #18
0
    def test_is_invoice_released_status_0_yesterday(self) -> None:
        cutoff = date.today() + timedelta(days=-1)

        mock_dao = Mock(spec=InvoiceDataAccessObject)
        mock_dao.lookup_status.return_value = 0

        invoice = Invoice(1234, cutoff, mock_dao)

        assert not invoice.is_invoice_released()
Example #19
0
    def setUp(self):
        super(BaseClassIO, self).setUp()

        self.invoice = Invoice([
            TimeEntry(1, _dt(2010, 1, 1), '1st entry', 'Company1', 'job1'),
            TimeEntry(2.5, _dt(2010, 1, 2), '2nd entry', 'Company1', 'job1')
        ], _dt(2010, 1, 14), (_dt(2010, 1, 1), _dt(2010, 1, 13)),
                               CompanyJobs('Company1', {'job1': 'Job One'},
                                           20))
Example #20
0
def lambda_handler(event, context):
    invoice = Invoice(event)
    es_response = invoice.send_to_elastic()
    print(es_response.text)
    return {
        'statusCode': 200,
        'doc': invoice.es_doc,
        'es_response': es_response.text
    }
    def test_add_invoices_ok(self):
        """
        It should add each invoice to the `InvoiceStats` storage.
        """
        invoices = [Invoice(1000, 1), Invoice(10_000, 2), Invoice(100_000, 10)]
        invoice_stats = InvoiceStats()
        invoice_stats.add_invoices(invoices)

        self.assertListEqual(invoice_stats._invoices, invoices)
Example #22
0
 def test_download(self):
     """Ensure the download method returns the file correctly"""
     invoice = Invoice(424)
     invoice.pdf_file = 'tests/invoices/download_test.pdf'
     with self.app.app_context():
         response = invoice.download()
     with open('tests/invoices/download_test.pdf', 'rb') as f:
         self.assertEqual(f.read(), response[0])
     invoice.delete_pdf()
Example #23
0
    def __init__(self, template, **kwargs):
        self.template = template
        #self.dest = dest

        self.wb = load_workbook(template)

        self.contract = Contract(self.wb.get_sheet_by_name(
            self.CONTRACT_SHEET))
        self.invoice = Invoice(self.wb.get_sheet_by_name(self.INVOICE_SHEET))
        self.details = Details(self.wb.get_sheet_by_name(self.DETAILS_SHEET))
Example #24
0
 def test_validate_args_where_item_and_action_are_none(self):
     # initialize
     expected_result = "NO_ITEM"
     invoice = Invoice()
     invoice.args = ArgsMock()
     # test
     result = invoice.validate_args()
     # verify
     self.assertEqual(result, expected_result)
     return
Example #25
0
 def test_delete(self):
     """Ensures that the delete method works by checking the data is removed from the database"""
     Invoice(424).delete()
     with database() as db:
         results = db.query(
             'SELECT * FROM invoices WHERE invoice_number = %s', 424)
         self.assertEqual(results, [])
         results = db.query(
             'SELECT * FROM invoice_items WHERE invoice_number = %s', 424)
         self.assertEqual(results, [])
Example #26
0
 def test_initialize_default_folders_and_files_where_home_path_does_not_exist(
         self):
     # initialize
     dir = dirname("/THIS/PATH/DOES/NOT/EXIST")
     invoice = Invoice()
     # test
     result = invoice.initialize_default_folders_and_files(dir)
     # verify
     self.assertTrue(result.index("HOME_PATH_DOES_NOT_EXIST") >= 0)
     return
Example #27
0
 def test_create_pdf(self):
     invoice_doc = self.wb.WorkSheets("請求書テンプレート")
     iv_data = invoice_util.get_excel_data(self.ws)
     iv = Invoice(iv_data[0])
     iv_detail = InvoiceDetail(iv_data[0])
     iv.add_detail(iv_detail)
     invoice_util.create_invoice_pdf(self.app, self.wb, invoice_doc, iv,
                                     "../pdf")
     f_list = glob.glob('../pdf/XXX株式会社*.pdf')
     self.assertEqual(len(f_list), 1)
Example #28
0
    def test_is_invoice_released(self, status: int, time_delta: int,
                                 expected: bool) -> None:
        cutoff = date.today() + timedelta(days=time_delta)

        mock_dao = Mock(spec=InvoiceDataAccessObject)
        mock_dao.lookup_status.return_value = status

        invoice = Invoice(1234, cutoff, mock_dao)

        assert invoice.is_invoice_released() == expected
Example #29
0
 def test_select_strategy_where_args_item_is_i(self):
     # initialize
     expected_result = ""
     invoice = Invoice()
     invoice.args = ArgsMock()
     invoice.args.item = "i"
     # test
     invoice.select_strategy()
     # verify
     self.assertTrue(isinstance(invoice.strategy, InvoiceStrategy))
     return
Example #30
0
 def test_validate_args_where_action_is_none(self):
     # initialize
     expected_result = "NO_ACTION"
     invoice = Invoice()
     invoice.args = ArgsMock()
     invoice.args.item = "company"
     # test
     result = invoice.validate_args()
     # verify
     self.assertEqual(result, expected_result)
     return