Exemplo n.º 1
0
def invoices(request):
    args = {}
    args['user'] = auth.get_user(request)

    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)

        invoice = Invoice(Photo=uploaded_file_url,
                          DateTime=datetime.datetime.now(),
                          User=auth.get_user(request))
        invoice.save()

        args['uploaded_file_url'] = uploaded_file_url

    invoices_list = Invoice.objects.all()
    paginator = Paginator(invoices_list, 9)  # Show 25 contacts per page

    page = request.GET.get('page')
    try:
        invoices = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        invoices = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        invoices = paginator.page(paginator.num_pages)

    args['invoices'] = invoices

    return render(request, 'invoices.html', args)
def invoices(id=None):
    if request.method == 'GET':
        if id is not None:
            invoice = Invoice.query.get(id)
            if invoice:
                return jsonify(invoice.serialize()), 200
            return jsonify({"msg": "This invoice not found!"}), 404
        else:
            invoices = Invoice.query.all()
            invoices = list(map(lambda invoice: invoice.serialize(), invoices))
            return jsonify(invoices), 200

    elif request.method == 'PUT':
        invoice = Invoice.query.get(id)
        invoice.email_paypal = request.json.get("email_paypal", "")
        invoice.payment = request.json.get("payment", "")
        invoice.date = request.json.get("date", "")
        invoice.validity = request.json.get("validity", "")
        invoice.update()
        return jsonify('Actualizado correctamente'), 200

    elif request.method == 'DELETE':
        invoice = Invoice.query.get(id)
        invoice.delete()
        return jsonify('Borrado'), 200

    elif request.method == "POST":
        invoice = Invoice()
        invoice.email_paypal = request.json.get("email_paypal", "")
        invoice.payment = request.json.get("payment", "")
        invoice.date = request.json.get("date", "")
        invoice.validity = request.json.get("validity", "")
        invoice.premium = request.json.get("premium", "")
        invoice.save()
        return jsonify(invoice.serialize()), 201
Exemplo n.º 3
0
 def test04(self):
     luc=Contact.objects.get(id=2)
     table=Product.objects.get(id=1)
     chair=Product.objects.get(id=2)
     i=Invoice(customer=luc,creation_date="2009-04-14")
     i.save()
     i.docitem_set.create(pos=1,product=table,qty=1)
Exemplo n.º 4
0
 def test04(self):
     luc = Contact.objects.get(id=2)
     table = Product.objects.get(id=1)
     chair = Product.objects.get(id=2)
     i = Invoice(customer=luc, creation_date="2009-04-14")
     i.save()
     i.docitem_set.create(pos=1, product=table, qty=1)
Exemplo n.º 5
0
 def setUpClass(cls):
     print("Setting up")
     conn = mongoengine.connect(db=DB_NAME, host=DB_HOST)
     for n in range(1, 11):
         invoice = Invoice(x=n, invoice_number=2)
         position = Position(**POSITION).save()
         #invoice.positions = [InvoiceItem(position_id=str(position.id))]
         invoice.positions = [InvoiceItem(position=position)]
         invoice.save()
Exemplo n.º 6
0
def change_pending_status():
    if Security.is_login(SK):
        callback = request.form['callback']
        try:
            Invoice.change_pending_status(request.form['pending_id'])
        except Exception as e:
            print(e)
            return 'Failed'
        return redirect(url_for(callback))
    return redirect(url_for('login', callback=stack()[0][3]))
Exemplo n.º 7
0
    def make_invoices(self): #Function to make invoices with no arguments
        for invoice in self.policy.invoices:
            invoice.delete()

        billing_schedules = {'Annual': None, 'Semi-Annual': 3, 'Quarterly': 4, 'Monthly': 12} #Creating a dictionary that specifies the definitions of each word

        invoices = [] #Creating a list names invoices
        first_invoice = Invoice(self.policy.id, #Creating the first invoice from using Invoice() from models.py
                                self.policy.effective_date, #bill_date
                                self.policy.effective_date + relativedelta(months=1), #due date
                                self.policy.effective_date + relativedelta(months=1, days=14), #cancel date two weeks after
                                self.policy.annual_premium) #Amount due
        invoices.append(first_invoice) #Placing first invoice into the list named invoices

        if self.policy.billing_schedule == "Annual": #If the billing schedule is equal to Annual then pass
            pass
        elif self.policy.billing_schedule == "Two-Pay": #Else if the billing schedule is equto to Two-Pay
            first_invoice.amount_due = first_invoice.amount_due / billing_schedules.get(self.policy.billing_schedule) #Figuring out amount due from first invoice
            for i in range(1, billing_schedules.get(self.policy.billing_schedule)): #For every object in the range(starting at one,stopping at billing schedule)
                months_after_eff_date = i*6 #Multiplies by 6 to split 12 months into two payments
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)
                invoice = Invoice(self.policy.id, #Create an invoice for this specification
                                  bill_date,
                                  bill_date + relativedelta(months=1),
                                  bill_date + relativedelta(months=1, days=14),
                                  self.policy.annual_premium / billing_schedules.get(self.policy.billing_schedule))
                invoices.append(invoice)
        elif self.policy.billing_schedule == "Quarterly": #Else if billing schedule is Quarterly
            first_invoice.amount_due = first_invoice.amount_due / billing_schedules.get(self.policy.billing_schedule)
            for i in range(1, billing_schedules.get(self.policy.billing_schedule)):
                months_after_eff_date = i*3 #Multiplies by 3 to split 12 months into 4 payments
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)
                invoice = Invoice(self.policy.id,
                                  bill_date,
                                  bill_date + relativedelta(months=1),
                                  bill_date + relativedelta(months=1, days=14),
                                  self.policy.annual_premium / billing_schedules.get(self.policy.billing_schedule))
                invoices.append(invoice)
        elif self.policy.billing_schedule == "Monthly": #Else if billing schedule is Monthly
            first_invoice.amount_due = first_invoice.amount_due / billing_schedules.get(self.policy.billing_schedule)
            for i in range(1, billing_schedules.get(self.policy.billing_schedule)):
                months_after_eff_date = i*1 #Changing variable i to be multiplied by 1 so we have 12 monthly invoices
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)
                invoice = Invoice(self.policy.id,
                                  bill_date,
                                  bill_date + relativedelta(months=1),
                                  bill_date + relativedelta(months=1, days=14),
                                  self.policy.annual_premium / billing_schedules.get(self.policy.billing_schedule))
                invoices.append(invoice)
        else:
            print "You have chosen a bad billing schedule." #If all the if and elif statements are False then print a bad billing schedule

        for invoice in invoices: #For every invoice add the invoice and commit to database
            db.session.add(invoice)
        db.session.commit()
    def setUpClass(cls):

        cls.policy = Policy('Test Policy', date(2015, 1, 1), 1200)
        db.session.add(cls.policy)
        db.session.commit()

        cls.invoice_1 = Invoice(cls.policy.id, date(2015, 1, 1), date(2015, 1, 15), date(2015, 2, 1), 50)
        cls.invoice_2 = Invoice(cls.policy.id, date(2015, 3, 1), date(2015, 3, 1), date(2015, 2, 1), 20)
        db.session.add(cls.invoice_1)
        db.session.add(cls.invoice_2)
        db.session.commit()
Exemplo n.º 9
0
    def make_invoices(self):
        """
        Creates invoices depending on policy's billing_schedule.
        """

        billing_schedules = {
            "Annual": 1,
            "Two-Pay": 2,
            "Quarterly": 4,
            "Monthly": 12
        }
        months_after_eff_date_dict = {
            "Annual": 12,
            "Two-Pay": 6,
            "Quarterly": 3,
            "Monthly": 1,
        }

        invoices = []
        first_invoice = Invoice(
            self.policy.id,
            self.policy.effective_date,  # bill_date
            self.policy.effective_date + relativedelta(months=1),  # due
            self.policy.effective_date +
            relativedelta(months=1, days=14),  # cancel
            self.policy.annual_premium,
        )
        invoices.append(first_invoice)

        if self.policy.billing_schedule in billing_schedules:
            invoices_quantity = billing_schedules.get(
                self.policy.billing_schedule)
            first_invoice.amount_due = first_invoice.amount_due / invoices_quantity
            months_between_invoices = months_after_eff_date_dict.get(
                self.policy.billing_schedule)
            for i in range(1, invoices_quantity):
                a = i * months_between_invoices
                bill_date = self.policy.effective_date + relativedelta(
                    months=a)
                invoice = Invoice(
                    self.policy.id,
                    bill_date,
                    bill_date + relativedelta(months=1),
                    bill_date + relativedelta(months=1, days=14),
                    self.policy.annual_premium /
                    billing_schedules.get(self.policy.billing_schedule),
                )
                invoices.append(invoice)
        else:
            print "You have chosen a bad billing schedule."

        for invoice in invoices:
            db.session.add(invoice)
        db.session.commit()
Exemplo n.º 10
0
def generate_monthly_invoices(policy_id):
    # query the database to get the policy with the id
    policy = Policy.query.filter_by(id=policy_id).one()

    # check if the policy has an initial invoice generated by PolicyAccounting
    if policy.invoices:

        # check if the policy is a Policy Three plan
        if policy.policy_number == "Policy Three":
            # delete any pre-generated invoice for the policy
            for invoice in policy.invoices:
                db.session.delete(invoice)

            # set the billing schedule to 12 i.e monthly
            billing_schedule = 12
            # create an empty list to store all invoices generated for the policy
            invoices = []
            # create an instance of invoice
            first_invoice = Invoice(
                policy.id,
                policy.effective_date,  # bill_date
                policy.effective_date + relativedelta(months=1),  # due
                policy.effective_date +
                relativedelta(months=1, days=14),  # cancel
                policy.annual_premium)

            invoices.append(first_invoice)

            first_invoice.amount_due = first_invoice.amount_due / billing_schedule
            for i in range(1, billing_schedule):
                months_after_eff_date = i * 1
                bill_date = policy.effective_date + relativedelta(
                    months=months_after_eff_date)
                # create an instance of invoice
                invoice = Invoice(policy.id, bill_date,
                                  bill_date + relativedelta(months=1),
                                  bill_date + relativedelta(months=1, days=14),
                                  policy.annual_premium / billing_schedule)
                # add the generated invoice to invoice list
                invoices.append(invoice)

            # save all the generated invoices to the database
            for invoice in invoices:
                db.session.add(invoice)
            db.session.commit()
            print "Invoices generated for Policy Three (Monthly Schedule)"
        else:
            print(
                "This not a Policy Three. Get the appropriate representation of Policy Three"
            )
    else:
        print("Policy not found")
Exemplo n.º 11
0
 def test03(self):
     luc = Contact.objects.get(id=2)
     i1 = Invoice(number=2000, customer=luc, creation_date="2009-04-14")
     i1.save()
     i2 = Invoice(customer=luc, creation_date="2009-04-14")
     i2.save()
     self.assertEquals(i2.number, 2001)
Exemplo n.º 12
0
    def make_invoices(self):
        billing_schedules = {
            'Annual': 1,
            'Two-Pay': 2,
            'Quarterly': 4,
            'Monthly': 12
        }

        invoices = []

        # Create an Invoice.
        first_invoice = Invoice(
            self.policy.id,
            self.policy.effective_date,  # bill_date
            self.policy.effective_date + relativedelta(months=1),  # due date
            self.policy.effective_date +
            relativedelta(months=1, days=14),  # cancellation date
            self.policy.annual_premium)

        # Add invoice to array.
        invoices.append(first_invoice)

        # Get number of payments from billing_schedules
        num_of_payments = billing_schedules.get(
            self.policy.billing_schedule) or None

        if not num_of_payments:
            print "You have chosen a bad billing schedule."

        # Calculate first invoice amount due by dividing total by number of payments
        first_invoice.amount_due = first_invoice.amount_due / num_of_payments

        for i in range(1, num_of_payments):
            # Calculate months after effective date
            months_after_eff_date = i * (12 / num_of_payments)

            # Add months to effective date to get bill date
            bill_date = self.policy.effective_date + relativedelta(
                months=months_after_eff_date)
            invoice = Invoice(
                self.policy.id, bill_date, bill_date + relativedelta(months=1),
                bill_date + relativedelta(months=1, days=14),
                self.policy.annual_premium /
                billing_schedules.get(self.policy.billing_schedule))
            invoices.append(invoice)

        # Add new invoices to db
        for invoice in invoices:
            db.session.add(invoice)
        db.session.commit()
Exemplo n.º 13
0
    def set_data_for(self, value):

        if value:
            try:
                invoices = Invoice.select().where(Invoice.number == int(value))
            except Exception as e:
                Config.logging.error(e)
                invoices = Invoice.select().where(Invoice.location.contains(value) |
                                                  Invoice.client.contains(value))
        else:
            invoices = Invoice.select().order_by(Invoice.number.asc())

        self.data = [(invoice.owner, invoice.number, show_date(invoice.date),
                      invoice.client, "") for invoice in invoices]
def handle_request_invoice(user_id, params):
    plan = params.get('plan', None)
    plan_from_db = db_session_users.query(Plan).filter_by(
        stripe_id=plan).first()
    if not plan_from_db:
        return 'Invalid plan'
    plan_name = plan_from_db.name
    plan_id = plan_from_db.id
    current_user = db_session_users.query(User).filter_by(id=user_id).first()
    message = current_user.first_name + ' ' + current_user.last_name + ' is requesting to pay by invoice for the ' + plan_name + ' subscription. ' + current_user.first_name + ', the team at Compliance.ai will respond to your request soon!'
    try:
        email_helper.send_email(
            '*****@*****.**',
            current_user.email,
            'Invoice request from ' + current_user.first_name,
            template='feedback-inline',
            vars={
                'feedback': message,
                'User_first_name': current_user.first_name,
                'User_last_name': current_user.last_name,
            },
        )
    except SMTPException as e:
        return error_response('Could not send invoice email.', code=500)

    invoice_for_db = {
        'user_id': user_id,
        'plan_id': plan_id,
        'status': 'requested'
    }
    invoice_for_db = Invoice(invoice_for_db)
    db_session_users.add(invoice_for_db)
    db_session_users.commit()
    db_session_users.refresh(invoice_for_db)
    return {'invoice': 'invoice request sent'}
Exemplo n.º 15
0
def email_invoices_timer_callback():
    logger.info("email_invoices_timer_callback()..")
    with app.app_context():
        invoices = Invoice.all_with_email_and_not_terminated(db.session)
        for invoice in invoices:
            order = bronze_order_status(invoice)
            if order:
                if invoice.status != order["status"]:
                    invoice_url = url_for("invoice", token=invoice.token)
                    hostname = urllib.parse.urlparse(invoice_url).hostname
                    sender = "no-reply@" + hostname
                    formatted_amount = '{0:0.2f}'.format(invoice.amount /
                                                         100.0)
                    # send email
                    msg = Message('ZAP bill payment status updated',
                                  sender=sender,
                                  recipients=[invoice.email])
                    msg.html = 'Invoice <a href="{}">{}</a> has updated the {} invoice with the amount of ${} to status "{}"'.format(
                        invoice_url, invoice.token, invoice.utility_name,
                        formatted_amount, order["status"])
                    msg.body = 'Invoice {} has updated the {} invoice with the amount of ${} to status {}'.format(
                        invoice_url, invoice.utility_name, formatted_amount,
                        order["status"])
                    mail.send(msg)
                    # update invoice object
                    invoice.status = order["status"]
                    db.session.commit()
Exemplo n.º 16
0
    def make_invoices(self):
        """
        Create invoices for new Policy's instances
        """
        for invoice in self.policy.invoices:
            invoice.delete()

        invoices = []
        first_invoice = Invoice(
            self.policy.id,
            self.policy.effective_date,  #bill_date
            self.policy.effective_date + relativedelta(months=1),  #due
            self.policy.effective_date +
            relativedelta(months=1, days=14),  #cancel
            self.policy.annual_premium)
        invoices.append(first_invoice)

        if self.policy.billing_schedule == "Annual":
            invoices += self.create_invoice(first_invoice, 12)
        elif self.policy.billing_schedule == "Two-Pay":
            invoices += self.create_invoice(first_invoice, 6)
        elif self.policy.billing_schedule == "Quarterly":
            invoices += self.create_invoice(first_invoice, 3)
        elif self.policy.billing_schedule == "Monthly":
            invoices += self.create_invoice(first_invoice, 1)
        else:
            print "You have chosen a bad billing schedule."

        for invoice in invoices:
            db.session.add(invoice)
        db.session.commit()
Exemplo n.º 17
0
def index():
    db = connect_db()
    seed_db(db)
    invoice = Invoice.objects().first()
    results = process_invoice(invoice=invoice, return_dict=True)

    labels = [
        'Date', 'Ending Def Rev', 'Cumulative Revenue', 'CR Sales Revenue',
        'DR Deferred Revenue', 'DR Reserve Refunds', 'DR Contra-Revenue',
        'CR Refunds Payable', 'DR Reserve Grace Period', 'CR Contra-Revenue'
    ]
    data = []
    for (date, v) in sorted(results['revrec_schedule'].iteritems(),
                            key=lambda (k, v): (k, v)):
        row = [
            pretty_date(date), v['ending_defrev'], v['cumul_rev'], v['cr_rev'],
            v['dr_defrev'], v['dr_reserve_ref'], v['dr_contra_rev'],
            v['cr_ref_payable'], v['dr_reserve_graceperiod'],
            v['cr_contra_rev']
        ]
        data.append(row)

    return render_template('base.html',
                           labels=labels,
                           data=data,
                           invoice=invoice,
                           payment=results['payment'],
                           invoice_items=results['invoice_items'],
                           refunds=results['refunds'],
                           gp_notes=results['gp_notes'])
Exemplo n.º 18
0
 def create_invoice(self, first_invoice, period):
     """
     :param first_invoice: Invoice instance
     :param billing_schedules: dict with the schedules available
     :param period: int with the number of periods (number of invoices)
     :return: list with Invoice instances
     """
     invoices = []
     first_invoice.amount_due = first_invoice.amount_due / self.billing_schedules.get(
         self.policy.billing_schedule)
     for i in range(
             1, self.billing_schedules.get(self.policy.billing_schedule)):
         months_after_eff_date = i * period
         bill_date = self.policy.effective_date + relativedelta(
             months=months_after_eff_date)
         amount = self.policy.annual_premium / self.billing_schedules.get(
             self.policy.billing_schedule)
         invoice = Invoice(
             self.policy.id,
             bill_date,
             bill_date + relativedelta(months=1),  #due date
             bill_date + relativedelta(months=1, days=14),  #cancel date
             amount)
         invoices.append(invoice)
     return invoices
Exemplo n.º 19
0
    def post(self):
        data = flatten_arguments(self.request.arguments)
        from models import Transaction, Invoice
        from pprint import pformat

        invoice_id = data.get('invoice')
        if invoice_id:
            invoice = Invoice.get_by_id(int(invoice_id, 10))

            txn = Transaction(invoice=invoice)
            txn.identifier = data.get('txn_id')
            txn.subscription_id = data.get("subscr_id")
            txn.transaction_type = data.get('txn_type')
            txn.currency = data.get('mc_currency')
            txn.amount = data.get('mc_gross', data.get('mc_amount3'))
            txn.data = pformat(data)
            txn.put()

            if self.verify(data):
                r = self.process(data, txn=txn, invoice=invoice)
            else:
                r = self.process_invalid(data, txn=txn, invoice=invoice)
            if r:
                self.write(r)
            else:
                self.write('Nothing to see here.')
        else:
            # error.  invoice id was not found.
            pass
Exemplo n.º 20
0
def invoice_create(utility, details, email, amount, utility_name):
    # init bank recipient params
    bank_account = details["bank_account"]
    reference = details["reference"] if "reference" in details else ""
    code = details["code"] if "code" in details else ""
    particulars = details["particulars"] if "particulars" in details else ""
    # request params
    recipient_params = dict(reference=reference,
                            code=code,
                            particulars=particulars)
    params = dict(market="ZAPNZD",
                  side="sell",
                  amount=str(amount),
                  amountasquotecurrency=True,
                  recipient=bank_account,
                  customrecipientparams=recipient_params)
    # create request
    r, err = bronze_request("BrokerCreate", params)
    if not r:
        return None, err
    # extract token and create invoice
    body = r.json()
    broker_token = body["token"]
    amount_cents_zap = int(decimal.Decimal(body["amountSend"]) * 100)
    amount_cents_nzd = int(decimal.Decimal(body["amountReceive"]) * 100)
    status = body["status"]
    invoice = Invoice(email, amount_cents_nzd, amount_cents_zap, broker_token,
                      status, utility_name)
    db.session.add(invoice)
    db.session.commit()
    return invoice, None
Exemplo n.º 21
0
def index():
    db = connect_db()
    seed_db(db)
    invoice = Invoice.objects().first()
    results = process_invoice(invoice=invoice, return_dict=True)

    labels = ['Date', 'Ending Def Rev', 'Cumulative Revenue', 'CR Sales Revenue', 'DR Deferred Revenue', 
              'DR Reserve Refunds', 'DR Contra-Revenue', 'CR Refunds Payable', 'DR Reserve Grace Period',
              'CR Contra-Revenue']
    data = []
    for (date, v) in sorted(results['revrec_schedule'].iteritems(), key=lambda (k, v): (k, v)):
        row = [pretty_date(date), 
               v['ending_defrev'], 
               v['cumul_rev'],
               v['cr_rev'], 
               v['dr_defrev'], 
               v['dr_reserve_ref'], 
               v['dr_contra_rev'], 
               v['cr_ref_payable'],
               v['dr_reserve_graceperiod'],
               v['cr_contra_rev']]
        data.append(row)

    return render_template('base.html', 
                            labels=labels,
                            data=data,
                            invoice=invoice,
                            payment=results['payment'],
                            invoice_items=results['invoice_items'],
                            refunds=results['refunds'],
                            gp_notes=results['gp_notes'])
Exemplo n.º 22
0
    def make_invoices(self):
        for invoice in self.policy.invoices:
            invoice.deleted = True

        billing_schedules = {
            'Annual': None,
            'Two-Pay': 2,
            'Quarterly': 4,
            'Monthly': 12
        }

        invoices = []
        first_invoice = Invoice(
            self.policy.id,
            self.policy.effective_date,  # bill_date
            self.policy.effective_date + relativedelta(months=1),  # due
            self.policy.effective_date +
            relativedelta(months=1, days=14),  # cancel
            self.policy.annual_premium)
        invoices.append(first_invoice)

        schedule = self.policy.billing_schedule
        if schedule == "Annual":
            pass
        elif schedule in billing_schedules:
            num_payments = billing_schedules.get(schedule)
            # desire full-dollar bill amounts, but not always divisible, so add remainder to first installment
            first_invoice.amount_due = first_invoice.amount_due / num_payments + first_invoice.amount_due % num_payments

            for i in range(1, billing_schedules.get(schedule)):
                months_after_eff_date = i * 12 / num_payments
                bill_date = self.policy.effective_date + relativedelta(
                    months=months_after_eff_date)

                invoice = Invoice(
                    self.policy.id, bill_date,
                    bill_date + relativedelta(months=1),
                    bill_date + relativedelta(months=1, days=14),
                    self.policy.annual_premium /
                    billing_schedules.get(schedule))
                invoices.append(invoice)
        else:
            print "You have chosen a bad billing schedule."

        for invoice in invoices:
            db.session.add(invoice)
        db.session.commit()
Exemplo n.º 23
0
    def make_invoices(self):
        for invoice in self.policy.invoices:
            invoice.delete()

        billing_schedules = {'Annual': None, 'Semi-Annual': 3, 'Quarterly': 4, 'Monthly': 12}

        invoices = []
        first_invoice = Invoice(self.policy.id,
                                self.policy.effective_date, #bill_date
                                self.policy.effective_date + relativedelta(months=1), #due
                                self.policy.effective_date + relativedelta(months=1, days=14), #cancel
                                self.policy.annual_premium)
        invoices.append(first_invoice)

        if self.policy.billing_schedule == "Annual":
            pass
        elif self.policy.billing_schedule == "Two-Pay":
            first_invoice.amount_due = first_invoice.amount_due / billing_schedules.get(self.policy.billing_schedule)
            for i in range(1, billing_schedules.get(self.policy.billing_schedule)):
                months_after_eff_date = i*6
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)
                invoice = Invoice(self.policy.id,
                                  bill_date,
                                  bill_date + relativedelta(months=1),
                                  bill_date + relativedelta(months=1, days=14),
                                  self.policy.annual_premium / billing_schedules.get(self.policy.billing_schedule))
                invoices.append(invoice)
        elif self.policy.billing_schedule == "Quarterly":
            first_invoice.amount_due = first_invoice.amount_due / billing_schedules.get(self.policy.billing_schedule)
            for i in range(1, billing_schedules.get(self.policy.billing_schedule)):
                months_after_eff_date = i*3
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)
                invoice = Invoice(self.policy.id,
                                  bill_date,
                                  bill_date + relativedelta(months=1),
                                  bill_date + relativedelta(months=1, days=14),
                                  self.policy.annual_premium / billing_schedules.get(self.policy.billing_schedule))
                invoices.append(invoice)
        elif self.policy.billing_schedule == "Monthly":
            pass
        else:
            print "You have chosen a bad billing schedule."

        for invoice in invoices:
            db.session.add(invoice)
        db.session.commit()
Exemplo n.º 24
0
	def create_invoice(self,
					   recipient_user,
					   recipient_email,
					   recipient_name,
					   recipient_address,
					   title,
					   invoicedate,
					   duedate,
					   invoicerows,
					   processor = None,
					   processorid = None,
					   autopaymentoptions = True,
					   bankinfo = True,
					   accounting_account = None,
					   accounting_object = None):
		invoice = Invoice(
			recipient_email=recipient_email,
			recipient_name=recipient_name,
			recipient_address=recipient_address,
			title=title,
			invoicedate=invoicedate,
			duedate=duedate,
			total_amount=-1,
			bankinfo=bankinfo,
			accounting_account=accounting_account,
			accounting_object=accounting_object)
		if recipient_user:
			invoice.recipient_user = recipient_user
		if processor:
			invoice.processor = processor
		if processorid:
			invoice.processorid = processorid
		# Add our rows. Need to save the invoice first so it has an id.
		# But we expect to be in a transaction anyway.
		invoice.save()
		for r in invoicerows:
			invoice.invoicerow_set.add(InvoiceRow(invoice=invoice,
												  rowtext = r[0],
												  rowcount = r[1],
												  rowamount = r[2]))

		if autopaymentoptions:
			invoice.allowedmethods = InvoicePaymentMethod.objects.filter(auto=True)
			invoice.save()

		# That should be it. Finalize so we get a PDF, and then
		# return whatever we have.
		wrapper = InvoiceWrapper(invoice)
		wrapper.finalizeInvoice()
		return invoice
Exemplo n.º 25
0
def ws_invoices_timer_callback():
    #logger.info("ws_invoices_timer_callback()..")
    for token in ws_invoices.keys():
        #logger.info("ws_invoices_timer_callback: token: {}".format(token))
        invoice = Invoice.from_token(db.session, token)
        if invoice:
            order = bronze_order_status(invoice)
            if order:
                socketio.emit("order_status", order["status"], room=token)
Exemplo n.º 26
0
 def click_item(self, row, column, *args):
     last_column = self.hheaders.__len__() - 1
     if column != last_column:
         return
     try:
         self.parent.change_main_context(ShowInvoiceViewWidget,
                                         invoice=Invoice.get(number=(self.data[row][1])))
     except IndexError:
         pass
Exemplo n.º 27
0
 def no_payment(self, params):
   re = db.get(params['rekey'])
   invoices_count  = len(Invoice().all(keys_only=True).filter('realestate', re.key()).filter('state', Invoice._NOT_PAID).fetch(10))
   plural          = 's' if invoices_count>1 else ''
   
   context_ex = self.common_context()
   context_ex = dict({'invoices_count':invoices_count, 'plural':plural}, **context_ex)
   
   self.send_email('no_payment', re.email, u'Aviso de factura%s impaga%s' % (plural, plural), **context_ex)
Exemplo n.º 28
0
    def build(self):
        if self.__provider is None:
            raise Exception('Provider is required')
        if self.__items is None:
            raise Exception('No items')

        return Invoice(company=self.__provider,
                       issued_at=self.__issued_at,
                       items=self.__items,
                       remarks=self.__remarks)
Exemplo n.º 29
0
 def set_data_for(self, value):
     if value:
         value = str(value)
         if is_int(value):
             qs = ((Invoice.number == int(value)))
             invoices = Invoice.select().where(qs)
         else:
             invoices = []
             for clt in ProviderOrClient.select().where(
                     ProviderOrClient.name.contains(value)).iterator():
                 for invoice in clt.invoices().iterator():
                     invoices.append(invoice)
     else:
         invoices = Invoice.select()[:100]
     try:
         self.data = [(invoice.number, invoice.date, invoice.client, "")
                      for invoice in invoices]
     except Exception as e:
         print("Exception ", e)
Exemplo n.º 30
0
def test_invoice(token):
    if not app.config["DEBUG"]:
        return abort(404)
    invoice = Invoice.from_token(db.session, token)
    if token in ws_invoices:
        logger.info("sending invoice update %s" % token)
        socketio.emit("info", invoice.to_json(), json=True, room=token)
    if invoice:
        return jsonify(invoice.to_json())
    return abort(404)
Exemplo n.º 31
0
def search_invoice():
    invoice_id = request.args.get('invoice_id')
    inv = Invoice()
    inv.invoice_id = invoice_id
    invoice = inv.get_invoice_by_id()

    if invoice:
        id = invoice[0][1]
        costumer = invoice[0][2]
        date = str(datetime.strftime(invoice[0][3], '%Y-%m-%d'))
        seller = invoice[0][4]
        items = invoice[0][5]
        total = invoice[0][6]
        pending = invoice[0][7]

        return redirect(url_for('print_invoice', id=id, costumer=costumer, date=date, seller=seller,
                                items=items, total=total, pending=pending))
    else:
        return redirect(url_for('select_invoice',  nfy="No found"))
Exemplo n.º 32
0
def check_auth(token, nonce, sig, body):
    invoice = Invoice.from_token(db.session, token)
    if not invoice:
        return False, "not found", None
    res, reason = check_hmac_auth(invoice, nonce, sig, body)
    if not res:
        return False, reason, None
    # update invoice nonce
    db.session.commit()
    return True, "", invoice
Exemplo n.º 33
0
def delete_invoice():
    invoice = request.form['invoice-1']
    vali_invoice = request.form['invoice-2']
    if invoice == '' or vali_invoice == '':
        flash("Please complete all the fields.")
        return redirect(url_for('settings'))

    if invoice == vali_invoice:
        inv = Invoice()
        inv.invoice_id = invoice

        if inv.delete_invoice():
            flash("Invoice deleted successfully.")
            return redirect(url_for('settings'))
        else:
            flash("ERROR.")
            return redirect(url_for('settings'))
    else:
        flash("Invoice number didn't match.")
        return redirect(url_for('settings'))
Exemplo n.º 34
0
  def get(self, **kwargs):
    re          = db.get(self.get_realestate_key())
    invoices    = []
    
    invoices.extend( Invoice.all().filter('realestate', re.key()).filter('state', Invoice._INPROCESS).order('date') )
    invoices.extend( Invoice.all().filter('realestate', re.key()).filter('state', Invoice._NOT_PAID).filter('date <= ', datetime.now()).order('date') )
    
    total_debt  = reduce(lambda x,i: x + (i.amount if i.state == Invoice._NOT_PAID else 0), invoices, 0)

    
    params = {
      're'        :re,
      'invoices'  :invoices,
      'total_debt':total_debt,
      'mnutop'    :'cuenta',
      'plan'      :re.plan,
      'Invoice'   :Invoice,
    }
      
    return self.render_response('backend/account.html', **params)
Exemplo n.º 35
0
    def set_data_for(self, date_, provid_clt_id=None, search=None):
        self.provid_clt_id = provid_clt_id
        qs = Invoice.select().order_by(Invoice.number.asc())
        if isinstance(self.provid_clt_id, int):
            self.provider_clt = ProviderOrClient.get(id=self.provid_clt_id)
            qs = qs.select().where(Invoice.client == self.provider_clt)
        else:
            self.provider_clt = "Tous"

        self.data = [(vl.date, vl.number, vl.client.name, vl.amount_ivoice, "")
                     for vl in qs
                     if (vl.date > date_[0] and vl.date < date_[1])]
Exemplo n.º 36
0
 def test03(self):
     luc=Contact.objects.get(id=2)
     i1=Invoice(number=2000,customer=luc,creation_date="2009-04-14")
     i1.save()
     i2=Invoice(customer=luc,creation_date="2009-04-14")
     i2.save()
     self.assertEquals(i2.number,2001)
Exemplo n.º 37
0
    def get(self, **kwargs):
        re = get_or_404(kwargs['key'])

        blobs = []
        imgs = []
        props = []

        for img in ImageFile.all().filter('realestate', re.key()):
            blobs.append(img.file.key())
            imgs.append(img.key())

        blobstore.delete(blobs)
        db.delete(imgs)

        props = []
        for prop in Property.all().filter('realestate', re.key()):
            props.append(prop.key())

        db.delete(props)

        pis = []
        for pi in PropertyIndex.all().filter('realestate', re.key()):
            pis.append(pi.key())

        db.delete(pis)

        invs = []
        pays = []
        for inv in Invoice.all().filter('realestate', re.key()):
            invs.append(inv)
            if inv.payment:
                pays.append(inv.payment.key())

        db.delete(invs)
        db.delete(pays)

        usrs = []
        for usr in User.all().filter('realestate', re.key()):
            usrs.append(usr)

        db.delete(usrs)

        mRealEstateFriendship = []
        for fr in RealEstateFriendship.all().filter('realestates',
                                                    str(re.key())):
            mRealEstateFriendship.append(fr)

        db.delete(mRealEstateFriendship)

        re.delete()

        self.response.write('borrado %s' % kwargs['key'])
Exemplo n.º 38
0
    def make_invoices(self):
        for invoice in self.policy.invoices:
            invoice.deleted = True

        billing_schedules = {'Annual': None, 'Two-Pay': 2, 'Quarterly': 4, 'Monthly': 12}

        invoices = []
        first_invoice = Invoice(self.policy.id,
                                self.policy.effective_date,  # bill_date
                                self.policy.effective_date + relativedelta(months=1),  # due
                                self.policy.effective_date + relativedelta(months=1, days=14),  # cancel
                                self.policy.annual_premium)
        invoices.append(first_invoice)

        schedule = self.policy.billing_schedule
        if schedule == "Annual":
            pass
        elif schedule in billing_schedules:
            num_payments = billing_schedules.get(schedule)
            # desire full-dollar bill amounts, but not always divisible, so add remainder to first installment
            first_invoice.amount_due = first_invoice.amount_due / num_payments + first_invoice.amount_due % num_payments

            for i in range(1, billing_schedules.get(schedule)):
                months_after_eff_date = i*12/num_payments
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)

                invoice = Invoice(self.policy.id,
                                  bill_date,
                                  bill_date + relativedelta(months=1),
                                  bill_date + relativedelta(months=1, days=14),
                                  self.policy.annual_premium / billing_schedules.get(schedule))
                invoices.append(invoice)
        else:
            print "You have chosen a bad billing schedule."

        for invoice in invoices:
            db.session.add(invoice)
        db.session.commit()
Exemplo n.º 39
0
def invoices(invoice_type=CONST.INVOICE_TYPE[CONST.INVOICE_IN]):
    form = InvoiceForm()
    form_elem = ElemForm()

    if invoice_type == CONST.INVOICE_TYPE[CONST.INVOICE_IN]:
        inv_type = CONST.INVOICE_IN
    elif invoice_type == CONST.INVOICE_TYPE[CONST.INVOICE_OUT]:
        inv_type = CONST.INVOICE_OUT
        del form.ninvoice


    if request.method == "POST":
        if form.validate(current_user):
            if inv_type == CONST.INVOICE_OUT:
                ninvoice = Invoice.make_unique_num(form.dinvoice.data, form.org_uid.data)
                flash(u"Счет-фактуре присвоен номер "+ninvoice, "alert-success")
            else:
                ninvoice = form.ninvoice.data
            newinvoice = Invoice(inv_type, form.org_uid.data, form.agent_uid.data,
                                 ninvoice, form.dinvoice.data,
                                 form.sum_snds.data, form.sum_no_nds18.data,
                                 form.sum_nds18.data, form.sum_no_nds10.data,
                                 form.sum_nds10.data, current_user.uid)
            db.session.add(newinvoice)
            db.session.commit()
            flash(u"Добавлена новая счет-фактура", "alert-success")

            # clean fields
            lst_fields = ['dinvoice', 'sum_snds',
                          'sum_no_nds18', 'sum_nds18',
                          'sum_no_nds10', 'sum_nds10']
            if inv_type == CONST.INVOICE_IN:
                lst_fields.append('ninvoice')
            for fld in lst_fields:
                form[fld].raw_data = None
                form[fld].data = None

    invoices = current_user.available_invoices(inv_type=inv_type)
    sums = invoices.with_entities(func.sum(Invoice.sum_snds),
                                  func.sum(Invoice.sum_no_nds18),
                                  func.sum(Invoice.sum_nds18),
                                  func.sum(Invoice.sum_no_nds10),
                                  func.sum(Invoice.sum_nds10),
                                  func.sum(Invoice.commission)).first()

    return render_template('invoices.html', form=form, form_elem=form_elem,
                           invoices=invoices.all(),
                           invoice_type=invoice_type,
                           sums=sums,
                           edit=0)
Exemplo n.º 40
0
    def post(self):
        new_invoice = Invoice(client_name=request.json['client_name'])
        db.session.add(new_invoice)

        for item in request.json['invoice_items']:
            new_invoice_item = InvoiceItem(
                units = item['units'],
                description = item['description'],
                amount = item['amount'],
                invoice = new_invoice
            )
            db.session.add(new_invoice_item)
        db.session.commit()
        return '', 204
Exemplo n.º 41
0
 def save_model(self,request,obj,form,change): 
     #import pdb
     #pdb.set_trace()
     if form.is_valid():
         invo = form.save(commit=False)
         if change:
             if invo.auditstate == 3:
                 invosa = Invoice.objects.get(id = obj.id)
                 if invosa.auditstate != 3:
                     invosa.auditer = request.user.id
                     invosa.auditstate = 3
                     invosa.save()
         else:
             orderidindex = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
             record = Invoice.objects.filter(orderid__contains=orderidindex).order_by('-id')
             if record.count()>0:
                 last = int(record[0].orderid[14:])
                 last += 1
                 orderid = orderidindex+str(last).zfill(4)
             else:
                 orderid = orderidindex+'0001'
             invosa = Invoice(orderformtype = invo.orderformtype,
                             orderid = orderid,
                             buyerid = invo.buyerid,
                             buyername = invo.buyername,
                             buyercontactmethod = invo.buyercontactmethod,
                             buyeraddress = invo.buyeraddress,
                             buytype = invo.buytype,
                             paymoney = invo.paymoney,
                             terminalcount = invo.terminalcount,
                             paystate = invo.paystate,
                             former = request.user.id,
                             producetime = datetime.datetime.now(),
                             auditstate = 1,
                             auditer = '',
                             )
             invosa.save()
Exemplo n.º 42
0
def check():
    form = InvoiceForm()
    if form.validate_on_submit():
        invoice = Invoice(
            form.data['amount'],
            form.data['currency'],
            form.data['description']
        )
        db.session.add(invoice)
        db.session.commit()
        app.logger.info(u"invoice created: {}".format(invoice))

        # hack for passing signature check
        amount = int(invoice.amount) if (
            int(invoice.amount) == float(invoice.amount)) else invoice.amount

        payload = {
            "shop_id": SHOP_ID,
            "amount": amount,
            "currency": invoice.currency,
            'shop_invoice_id': invoice.id,
            "description": invoice.description
        }
        if invoice.currency == '980':
            payload["payway"] = 'w1_uah'
            sign = _get_sign(payload, INVOICE_KEYS)
            payload['sign'] = sign
            resp = requests.post(UAH_INVOICE_URL, json=payload)
            data = json.loads(resp.content)['data']
            app.logger.info("data: {}".format(data))
            if not data:
                return jsonify(json.loads(resp.content))
            url = data['source']
            data = data['data']

        elif invoice.currency == '643':
            sign = _get_sign(payload, TIP_KEYS)
            payload['sign'] = sign
            data = payload
            url = TIP_URL

        else:
            return jsonify({'result': 'error', 'message': 'Wrong currency'})

        app.logger.info("data sent: {}".format(data))

        return jsonify({'result': 'ok', 'data': data, 'url': url})
    return jsonify({'result': 'error', 'message': 'Form validation error'})
Exemplo n.º 43
0
    def map(self, payment):

        # Traemos la factura que este pago cancela el pago (payment)
        invoice = Invoice.all().filter('Trx_id', payment.trx_id).get()
        if not invoice:
            logging.error('No encontre factura para el pago %s' %
                          str(payment.key()))
            return ([], [])

        # Obtenemos el realestate en funcion del trx_id
        id_or_name = payment.trx_id[7:]  #YYYYMM[NI]ddddddd

        re = None
        if payment.trx_id[6] == 'I':
            re = RealEstate.get_by_id(int(id_or_name))
        else:
            re = RealEstate.get_by_key_name(id_or_name)

        if re is None:
            logging.error('No encontre el realestate para %s' % payment.trx_id)
            return ([], [])

        invoice.realestate = re

        # Ponemos la factura en estado pagada
        invoice.state = Invoice._PAID
        invoice.payment = payment
        invoice.save()

        # Acabamos de asignar un pago, deberiamos automaticamente
        # poner en ENABLED a la inmo si es que no estaba en ese estado
        # Si esta volviendo a ENABLE desde NO_PAYMENT debemos comunicarle que 'las props estan publicadas nuevamente'

        oldst = re.status

        # payment_received
        if re.status == RealEstate._ENABLED:
            send_mail('payment_received', re)
        else:
            re.status = RealEstate._ENABLED
            re.save()

            if oldst == RealEstate._NO_PAYMENT:
                send_mail('enabled_again', re, invoice)

        payment.assigned = 1
        return ([payment], [])  # update/delete
Exemplo n.º 44
0
def process():
    form = ServiceForm()
    if form.validate_on_submit():
        currency = int(form.currency.data)
        if currency == 978:
            invoice = Invoice(form.description.data, form.amount.data,
                              currency, 'payeer_usd', 'invoice')
            invoice.save()
            data = invoice.get_invoice_form_params()
            return render_template('invoice.html', data=data, title='Invoice')

        if currency == 840:
            invoice = Invoice(form.description.data, form.amount.data,
                              currency, 'payeer_usd', 'tip')
            invoice.save()
            return render_template('tip.html',
                                   invoice=invoice,
                                   form_url=app.config['PS_TIP_URL'],
                                   shop_id=app.config['PS_SHOP_ID'],
                                   title='TIP')

    return redirect(url_for('index'))
Exemplo n.º 45
0
    def __init__(self, table_p, invoice_num, parent=0, *args, **kwargs):
        # super(ShowInvoiceViewWidget, self).__init__(
        #     parent=parent, *args, **kwargs)
        QDialog.__init__(self, parent, *args, **kwargs)

        self.invoice = Invoice.get(number=invoice_num)
        self.parentWidget().setWindowTitle(
            "{} {}".format(Config.APP_NAME, "CONSULTATION DE FACTURE"))

        self.parent = parent
        self.table_p = table_p

        vbox = QVBoxLayout()
        self.title = self.invoice.type_

        self.table_show = ShowOrderTableWidget(parent=self)

        editbox = QGridLayout()
        xls_bicon = QIcon.fromTheme(
            'document-del', QIcon(u"{}xls.png".format(Config.img_cmedia)))
        pdf_icon = QIcon.fromTheme(
            'document-del', QIcon(u"{}pdf.png".format(Config.img_cmedia)))
        self.button_pdf = QPushButton(pdf_icon, u"")
        self.button_pdf.setFixedWidth(30)
        self.button_pdf.setFixedHeight(30)
        self.button_xls = QPushButton(xls_bicon, u"")
        self.button_xls.setFixedWidth(30)
        self.button_xls.setFixedHeight(30)
        self.button_pdf.released.connect(self.printer_pdf)
        self.button_xls.released.connect(self.export_xls)
        self.button_dl = DeletedBtt(u"Annuler la facture")
        self.button_dl.released.connect(self.cancellation)

        editbox.addWidget(FLabel(u"{typ} N°: {num}".format(
            num=self.invoice.number, typ=self.invoice.type_)), 0, 0)
        editbox.addWidget(FLabel(u"%s le %s" % (
            self.invoice.location, show_date(self.invoice.date))), 1, 4)
        editbox.addWidget(FLabel(u"Doit: %s " % self.invoice.client), 1, 0)
        editbox.addWidget(self.button_pdf, 1, 5)
        editbox.addWidget(self.button_dl, 0, 4)
        editbox.addWidget(self.button_xls, 1, 6)

        vbox.addLayout(editbox)
        vbox.addWidget(self.table_show)
        self.setLayout(vbox)
Exemplo n.º 46
0
    def __init__(self, invoice_num, parent=0, *args, **kwargs):
        super(ShowInvoiceViewWidget, self).__init__(
            parent=parent, *args, **kwargs)
        self.invoice = Invoice.get(number=invoice_num)
        self.parentWidget().setWindowTitle(Config.NAME_ORGA +
                                           u"  CONSULTATION DE FACTURE")

        self.parent = parent

        vbox = QVBoxLayout()
        self.title = self.invoice.type_

        self.table_show = ShowOrderTableWidget(parent=self)

        editbox = QGridLayout()
        xls_bicon = QIcon.fromTheme(
            'document-del', QIcon(u"{}xls.png".format(Config.img_cmedia)))
        pdf_icon = QIcon.fromTheme(
            'document-del', QIcon(u"{}pdf.png".format(Config.img_cmedia)))
        self.button_pdf = QPushButton(pdf_icon, u"")
        self.button_pdf.setFixedWidth(30)
        self.button_pdf.setFixedHeight(30)
        self.button_xls = QPushButton(xls_bicon, u"")
        self.button_xls.setFixedWidth(30)
        self.button_xls.setFixedHeight(30)
        self.button_pdf.released.connect(self.printer_pdf)
        self.button_xls.released.connect(self.export_xls)
        self.button_dl = Deleted_btt(u"Annuler la facture")
        self.button_dl.released.connect(self.cancellation)

        editbox.addWidget(FLabel(u"{typ} N°: {num}".format(
            num=self.invoice.number, typ=self.invoice.type_)), 0, 0)
        editbox.addWidget(FLabel(u"%s le %s" % (self.invoice.location,
                                                show_date(self.invoice.date))), 1, 4)
        editbox.addWidget(FLabel(u"Doit: %s " % self.invoice.client), 1, 0)
        # editbox.addWidget(self.button_pdf, 1, 5)
        editbox.addWidget(self.button_dl, 0, 4)
        editbox.addWidget(self.button_xls, 1, 6)

        vbox.addLayout(editbox)
        vbox.addWidget(self.table_show)
        self.setLayout(vbox)
Exemplo n.º 47
0
 def set_data_for(self, value):
     # if not value:
     #     print("is value")
     invoices = Invoice.select().order_by(Invoice.number.desc())
     if value:
         # return
         qs = (
             Invoice.location.contains(value)
             |
             # Invoice.date.contains(value) |
             Invoice.client.contains(value)
         )
         try:
             qs = qs | (Invoice.number.contains(int(value)))
         except Exception as e:
             print(e)
         # invoices = invoices.where(qs).execute()
         invoices = qs
     try:
         self.data = [(invoice.number, show_date(invoice.date), invoice.client, "") for invoice in invoices]
     except Exception as e:
         print(e)
Exemplo n.º 48
0
def confirm_purchase(invoice_id):
    import datetime
    user = g.user
    if invoice_id is None:
        i = Invoice()
        i.paid = False
        i.datecreated = datetime.datetime.utcnow()
        i.user_id = user.id
        db.session.add(i)
        db.session.commit()
        try:
            callback_url = url_for('pay_invoice', _external=True)+'?secret='+SECRET_KEY+'%26invoice_id='+str(i.id)
            url = BLOCKCHAIN_URL+'?method=create&address='+STASH_WALLET+'&callback='+callback_url
            xhr = urllib2.Request(url)
            data = json.load(urllib2.build_opener().open(xhr))
            price_data = json.load(urllib2.build_opener().open(urllib2.Request("http://blockchain.info/tobtc?currency=USD&value="+str(PRICE_OF_SERVICE))))
            exchange_data = json.load(urllib2.build_opener().open(urllib2.Request("http://blockchain.info/ticker")))
            app.logger.info("Sent to blockchain api: " + url)
        except urllib2.URLError as e:
            app.logger.error('Unable to access the blockchain.info api: ' + url)
            flash('There was an error creating a new invoice. Please try again later.')
            return redirect('/dashboard')
        i.address = data['input_address']
        i.total_btc = price_data
        i.exchange_rate_when_paid = exchange_data['USD']['last']
        db.session.commit()
        # TODO: Generate a QR code and/or other e-z payment options for BTC services
        return redirect(url_for('confirm_purchase', invoice_id=i.id))
    else:
        i = Invoice.query.get(invoice_id)
        if request.method == 'POST':
            flash('Invoice ('+i.address+') was deleted succesfully.')
            db.session.delete(i)
            db.session.commit()
            return redirect(url_for('dashboard'))
        return render_template('confirm_purchase.html', user=user, invoice=i, min_confirm=CONFIRMATION_CAP)
Exemplo n.º 49
0
    def save_b(self):
        ''' add operation '''
        # entete de la facture
        print("save")
        if not self.is_valide():
            return
        invoice_date = unicode(self.invoice_date.text())
        num_invoice = int(self.num_invoice.text())
        invoice_type = self.liste_type_invoice[
            self.box_type_inv.currentIndex()]
        lis_error = []
        invoice = Invoice()
        try:
            self.owner = Owner.get(Owner.islog == True)
        except:
            lis_error.append("Aucun utilisateur est connecté <br/>")
        paid_amount = int(self.table_invoice.paid_amount_field.text())
        try:
            clt = ProviderOrClient.get_or_create(
                self.name_client, int(self.phone.replace(" ", "")), ProviderOrClient.CLT)
        except ValueError:
            field_error(
                self.name_client_field, "Nom, numéro de téléphone du client")
        invoice.number = num_invoice
        invoice.owner = self.owner
        invoice.client = clt
        invoice.location = "Bamako"
        invoice.type_ = invoice_type
        invoice.subject = ""
        invoice.paid_amount = paid_amount
        invoice.tax = False
        try:
            invoice.save()
            if int(paid_amount) != 0 or invoice_type == Invoice.TYPE_BON:
                Refund(type_=Refund.DT, owner=self.owner, amount=paid_amount,
                       date=date_to_datetime(invoice_date), provider_client=clt,
                       invoice=Invoice.get(number=num_invoice)).save()
        except Exception as e:
            invoice.deletes_data()
            lis_error.append(
                "Erreur sur l'enregistrement d'entête de facture<br/>")
            return False
        # Save invoiceitems
        invoice = Invoice.get(Invoice.number == num_invoice)
        for name, qty, price in self.table_invoice.get_table_items():
            rep = Report()
            product = Product.get(Product.name == name)
            rep.store = 1
            rep.product = product
            rep.invoice = invoice
            rep.type_ = Report.S
            rep.cost_buying = int(product.last_report.cost_buying)
            rep.date = date_to_datetime(invoice_date)
            rep.qty = int(qty)
            rep.selling_price = int(price)
            try:
                rep.save()
            except Exception as e:
                lis_error.append(e)
        if lis_error != []:
            invoice.delete_instance()
            self.parent.Notify(lis_error, "error")
            return False
        else:
            self.parent.Notify("Facture Enregistrée avec succès", "success")

            self.change_main_context(ShowInvoiceViewWidget,
                                     invoice_num=invoice.number)
Exemplo n.º 50
0
    def save_b(self):
        ''' add operation '''
        # entete de la facture
        if not self.table_invoice.isvalid:
            return False
        try:
            num_invoice = int(self.num_invoice.text())
            self.num_invoice_error.setText(u"")
        except:
            self.pixmap = QPixmap(u"{img_media}{img}".format(img_media=Config.img_media,
                                                      img="warning.png"))
            self.num_invoice.setStyleSheet("background-color:  rgb(255, 235, 235);")
            self.num_invoice_error.setToolTip(u"Le numero de facture est obligatoire.")
            self.num_invoice_error.setPixmap(self.pixmap)
        invoice_date = str(self.invoice_date.text())
        name_client = str(self.name_client.text())
        datetime_ = date_to_datetime(invoice_date)

        values_t = self.table_invoice.get_table_items()
        if name_client == "":
            self.name_client.setStyleSheet("background-color: rgb(255, 235, 235);")
            self.pixmap = QPixmap(u"{img_media}{img}".format(img_media=Config.img_media,
                                                      img="decline.png"))
            self.name_client_error.setToolTip(u"Nom du client est obligatoire.")
            self.name_client_error.setPixmap(self.pixmap)
            return False
        # if num_invoice > Config.credit:
        #     raise_error(("Avertisement"), u"<h2>Veuillez payer la reste de la licence</h2>")
        #     return False
        invoice = Invoice()
        try:
            invoice.owner = Owner.get(islog=True)
        except:
            if Config.DEBUG:
                invoice.owner = Owner.get(username='******')
            else:
                return False

        invoice.number = num_invoice
        invoice.date_ord = datetime_
        invoice.client = name_client.capitalize()
        invoice.location = "Bamako"
        invoice.type_ = "Facture"
        invoice.subject = ""
        invoice.tax = False
        invoice.otax_rate = 18
        try:
            invoice.save()
        except:
            raise_error("Erreur", u"Impossible d'enregistrer l'entête de la facture")
            return False

        # Save orderitems
        try:
            order = Invoice.get(number=num_invoice)
        except:
            return False
        for i in values_t:
            qty, name, price = i
            description = Product.filter(name=name).get()
            item = InvoiceItem()
            item.invoices = invoice.id
            item.quantity = int(i[0])
            item.description = description
            item.price = int(i[2])
            try:
                item.save()
                self.name_client.clear()
                self.num_invoice.clear()
            except Exception as e:
                print(e)
                invoice.delete_instance()
                raise_error("Erreur", u"Ce mouvement n'a pas pu etre "
                                      u"enregistré dans les rapports")
                return False

        self.change_main_context(ShowInvoiceViewWidget,
                                        invoice=invoice)
Exemplo n.º 51
0
    def __init__(self, product="", parent=0, *args, **kwargs):
        super(InvoiceViewWidget, self).__init__(parent=parent, *args, **kwargs)
        self.parentWidget().setWindowTitle(Config.NAME_ORGA + u"      FACTURATION")
        self.parent = parent

        vbox = QVBoxLayout(self)
        hbox = QHBoxLayout(self)
        editbox = QGridLayout()

        self.num_invoice = IntLineEdit("%d" % (Invoice.select().count() + 1))
        self.num_invoice.setToolTip(u"Le numéro de la facture")
        self.num_invoice.setMaximumSize(40, self.num_invoice.maximumSize().height())
        self.num_invoice_error = ErrorLabel("")
        self.invoice_date = FormatDate(QDate.currentDate())
        self.name_client = QLineEdit()
        self.name_client.setMaximumSize(200, self.name_client.maximumSize().height())
        self.name_client.setToolTip("Taper le nom du client")
        self.name_client_error = ErrorLabel("")
        self.search_field = QLineEdit()
        self.search_field.setMaximumSize(200, self.search_field.maximumSize().height())
        self.search_field.textChanged.connect(self.finder)

        self.vline = QFrame()
        self.vline.setFrameShape(QFrame.VLine)
        self.vline.setFrameShadow(QFrame.Sunken)

        self.table_invoice = OrderTableWidget(parent=self)
        self.table_resultat = ResultatTableWidget(parent=self)
        self.table_info = InfoTableWidget(parent=self)

        self.table_resultat.refresh_("")
        editbox.addWidget(FormLabel(u"Recherche:"), 0, 0)
        editbox.addWidget(self.search_field, 1, 0)
        editbox.addWidget(self.vline, 0, 1, 2, 5)
        editbox.addWidget(FormLabel(u"Facture N°:"), 0, 2)
        editbox.addWidget(self.num_invoice, 0, 3)
        editbox.addWidget(self.num_invoice_error, 0, 4)
        editbox.addWidget(FormLabel(u"Doit:"), 1, 2)
        editbox.addWidget(self.name_client, 1, 3)
        editbox.addWidget(self.name_client_error, 1, 4)
        editbox.addWidget(FormLabel(u"Date:"), 0, 5)
        editbox.addWidget(self.invoice_date, 0, 6)

        splitter = QSplitter(Qt.Horizontal)

        splitter_left = QSplitter(Qt.Vertical)
        splitter_down = QSplitter(Qt.Vertical)
        splitter_left.addWidget(FBoxTitle(u"Les resultats"))
        splitter_left.addWidget(self.table_resultat)
        splitter_down.resize(15, 20)
        splitter_down.addWidget(self.table_info)
        splitter_rigth = QSplitter(Qt.Vertical)
        splitter_rigth.addWidget(FBoxTitle(u"Les produits vendus"))
        splitter_rigth.addWidget(self.table_invoice)
        splitter_rigth.resize(500, 900)

        splitter_left.addWidget(splitter_down)
        splitter.addWidget(splitter_left)
        splitter.addWidget(splitter_rigth)

        hbox.addWidget(splitter)
        vbox.addLayout(editbox)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
Exemplo n.º 52
0
    def post(self):
        # Get customer and create an invoice.
        customer = Customer.get_by_key_name(self.get_current_username())
        invoice = Invoice(customer=customer)
        invoice.put()

        # Now start processing subscription data.
        subscription_data = self.session['subscription-data']
        products = db.get([db.Key(key) for key in subscription_data.get('products')])
        period = subscription_data.get('period')
        subscription_period = SubscriptionPeriod.get_by_period(period)

        units = [product for product in products if 'product_keys' not in product.properties()]
        baskets = [product for product in products if 'product_keys' in product.properties()]

        activation_credentials_list = []
        orders = []
        for unit in units:
            subscription = Subscription.get_by_product_and_period(unit, period)

            order = Order(customer=customer, invoice=invoice, subscription=subscription)
            order.subscription_price = subscription.price
            order.subscription_general_sales_tax = subscription.general_sales_tax
            order.subscription_period_in_months = subscription.period_in_months
            order.subscription_free_period_in_months = subscription_period.free_period_in_months
            order.price = subscription.price + subscription.general_sales_tax
            order.subscription_currency = subscription.currency
            orders.append(order)
            order.put()

            unit_id = unit.key().id()
            activation_credentials = ActivationCredentials()
            activation_credentials.serial_number = self.get_argument('u_%d_serial_number' % unit_id)
            activation_credentials.machine_id = self.get_argument('u_%d_machine_id' % unit_id)
            activation_credentials.order = order
            activation_credentials.product = unit
            activation_credentials.customer = customer
            logging.info(activation_credentials)
            activation_credentials_list.append(activation_credentials)

        for basket in baskets:
            subscription = Subscription.get_by_product_and_period(basket, period)

            order = Order(customer=customer, invoice=invoice, subscription=subscription)
            order.subscription_price = subscription.price
            order.subscription_general_sales_tax = subscription.general_sales_tax
            order.subscription_period_in_months = subscription.period_in_months
            order.subscription_free_period_in_months = subscription_period.free_period_in_months
            order.price = subscription.price + subscription.general_sales_tax
            order.subscription_currency = subscription.currency
            orders.append(order)
            order.put()

            for unit in basket.products:
                basket_id = basket.key().id()
                unit_id = unit.key().id()

                activation_credentials = ActivationCredentials()
                activation_credentials.serial_number = self.get_argument('b_%d_u_%d_serial_number' % (basket_id, unit_id,))
                activation_credentials.machine_id = self.get_argument('b_%d_u_%d_machine_id' % (basket_id, unit_id,))
                activation_credentials.order = order
                activation_credentials.product = unit
                activation_credentials.customer = customer
                logging.info(activation_credentials)
                activation_credentials_list.append(activation_credentials)

        db.put(activation_credentials_list)
        
        invoice.total_price = sum([order.price for order in orders])
        invoice.currency = orders[0].subscription_currency
        invoice.put()
        
        self.session['activation-invoice-key'] = str(invoice.key())
        self.redirect('/activate/overview')
Exemplo n.º 53
0
def select_invoice():
    if Security.is_login(SK):
        return render_template('invoice/select_invoice.html', title='Select Invoice',
                               invoices=Invoice.get_ten_invoices(), boxes_sold=Invoice.number_of_boxes_sold())
    return redirect(url_for('login', callback=stack()[0][3]))
Exemplo n.º 54
0
def view_pending():
    if Security.is_login(SK):
        return render_template('pending/select_pending.html', callback='view_pending', title='View Pending', pending=Invoice.get_pending_invoices())
    return redirect(url_for('login', callback=stack()[0][3]))
Exemplo n.º 55
0
    def make_invoices(self, end_date_cursor = None):
        """Produces next year's worth of invoices."""
        invoices = []
        if not end_date_cursor:
            if self.policy:
                end_date_cursor = self.policy.effective_date + relativedelta(days=365)
            else:
                end_date_cursor = datetime.now().date + relativedelta(days=365)

        for invoice in self.policy.invoices:
            if not invoice.deleted:
                db.session.delete(invoice)
            else:
                invoices.append(invoice)
        
        logger.log("New invoices are being made, invoices for this policy will be have a different invoice_id",
                   "Info",
                   self.policy.id);

        billing_schedules = {'Annual': None, 'Two-Pay': 2, 'Semi-Annual': 3, 'Quarterly': 4, 'Monthly': 12}
        billing_to_months = {'Annual': 12, 'Two-Pay': 6, 'Quarterly': 3, 'Monthly': 1}

        # create the first invoice
        first_invoice = Invoice(self.policy.id,
                                self.policy.effective_date, #bill_date
                                self.policy.effective_date + relativedelta(months=1), #due
                                self.policy.effective_date + relativedelta(months=1, days=14), #cancel
                                self.policy.annual_premium)
        invoices.append(first_invoice)

        # find the months in the billing period
        if billing_to_months.has_key(self.policy.billing_schedule):
            months_in_billing_period = billing_to_months.get(self.policy.billing_schedule)
        else:
            logger.log("Client tried using %s billing schedule" % (self.policy.billing_schedule), 
                       "Info",
                       self.policy.id)
            print "You have chosen a bad billing schedule."

        del billing_schedules["Annual"] # leave out annual from here to simplify
        if self.policy.billing_schedule in billing_schedules.keys(): 
            # find amount of months between end_date_cursor and self.policy.effective_date
            months_left = (end_date_cursor - self.policy.effective_date).days / 30

            invoices_needed = int(months_left / billing_to_months.get(self.policy.billing_schedule))
            first_invoice.amount_due = first_invoice.amount_due / invoices_needed
            
            # create the correct amount of invoices based on variables above
            for i in range(1, invoices_needed):
                months_after_eff_date = i * months_in_billing_period
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)
                invoice = Invoice(self.policy.id,
                                  bill_date,
                                  bill_date + relativedelta(months=1),
                                  bill_date + relativedelta(months=1, days=14),
                                  self.policy.annual_premium / invoices_needed)
                invoices.append(invoice)

        for invoice in invoices:
            db.session.add(invoice)

        db.session.commit()
        self.policy.invoices = invoices
Exemplo n.º 56
0
    def make_invoices(self):
        """
        Populates self.policy.invoices based on the selected billing schedule.
        Should have 1 if Annual, 2 if 2-Pay, 4 if quarterly, and 12 if Monthly.
        """
        # Clear what may currently be in the list of invoices to make sure there are no duplicates.
        for invoice in self.policy.invoices:
            invoice.delete()

        billing_schedules = {'Annual': None, 'Semi-Annual': 3, 'Quarterly': 4, 'Monthly': 12}

        invoices = []
        # First record to declare the overall premium of the policy
        first_invoice = Invoice(self.policy.id,
                                self.policy.effective_date, #bill_date
                                self.policy.effective_date + relativedelta(months=1), #due
                                self.policy.effective_date + relativedelta(months=1, days=14), #cancel
                                self.policy.annual_premium)
        invoices.append(first_invoice)

        # If billing schedule is Annual, no other invoices are needed
        if self.policy.billing_schedule == "Annual":
            pass
        elif self.policy.billing_schedule == "Two-Pay":
            # Put value in a variable to save hash table look-ups
            frequency = billing_schedules.get(self.policy.billing_schedule)
            # Alter first invoice's amount to reflect a 6-month payment
            first_invoice.amount_due = first_invoice.amount_due / frequency
            for i in range(1, frequency):
                # number of months to add to the invoices' bill_date
                months_after_eff_date = i*6	# multiply by 6 for Two-Pay
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)
                invoice = Invoice(self.policy.id,
                                  bill_date,    # bill date
                                  bill_date + relativedelta(months=1),   # due date
                                  bill_date + relativedelta(months=1, days=14),   # cancel date
                                  self.policy.annual_premium / frequency)    # amount due
                invoices.append(invoice)
        elif self.policy.billing_schedule == "Quarterly":
            # Put value into variable to save hash table look-ups
            frequency = billing_schedules.get(self.policy.billing_schedule)
            # Alter first invoice's amount due to reflect a 3-month payment
            first_invoice.amount_due = first_invoice.amount_due / frequency
            for i in range(1, frequency):
                # number of months to add to invoices' bill_date
                months_after_eff_date = i*3	# multiply by 3 for Quarterly
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)
                invoice = Invoice(self.policy.id,
                                  bill_date,   # bill date
                                  bill_date + relativedelta(months=1),   # due date
                                  bill_date + relativedelta(months=1, days=14),   # cancel date
                                  self.policy.annual_premium / frequency)   # amount due
                invoices.append(invoice)
        elif self.policy.billing_schedule == "Monthly":
            # put value into variable to save hash table look-ups
            frequency = billing_schedules.get(self.policy.billing_schedule)
            # Alter the first invoice's amount due to reflect a monthly payment
            first_invoice.amount_due = first_invoice.amount_due / frequency
            for i in range(1, frequency):
                months_after_eff_date = i	# no multiple here for Monthly. "frequency" should be 1
                bill_date = self.policy.effective_date + relativedelta(months=months_after_eff_date)
                invoice = Invoice(self.policy.id,
                                bill_date,   # bill date
                                bill_date + relativedelta(months=1),  # due date
                                bill_date + relativedelta(months=1, days=14),   # cancel date
                                self.policy.annual_premium / frequency)   # amount due
                invoices.append(invoice)
        else:
            print "You have chosen a bad billing schedule."

        for invoice in invoices:
            db.session.add(invoice)
        db.session.commit()
Exemplo n.º 57
0
    def __init__(self, product="", parent=0, *args, **kwargs):
        super(InvoiceViewWidget, self).__init__(parent=parent, *args, **kwargs)
        self.parentWidget().setWindowTitle(
            Config.APP_NAME + u"      Ventes")
        self.parent = parent

        vbox = QVBoxLayout(self)
        # hbox = QHBoxLayout(self)
        editbox = QGridLayout(self)
        try:
            next_number = int(
                Invoice.select().order_by(Invoice.number.desc()).get().number) + 1
        except:
            next_number = 1
        self.num_invoice = IntLineEdit(str(next_number))
        self.num_invoice.setToolTip(u"Le numéro")
        self.num_invoice.setMaximumSize(
            40, self.num_invoice.maximumSize().height())
        self.invoice_date = FormatDate(QDate.currentDate())
        # self.name_client_field = LineEdit()

        self.string_list = [""] + ["{},{}".format(clt.name, clt.phone)
                                   for clt in ProviderOrClient.select().where(
            ProviderOrClient.type_ == ProviderOrClient.CLT).order_by(ProviderOrClient.name.desc())]

        # self.name_client_field_new = ""
        self.name_client_field = ExtendedComboBox()
        self.name_client_field.addItems(self.string_list)

        self.name_client_field.setMaximumSize(
            200, self.name_client_field.maximumSize().height())
        self.name_client_field.setToolTip("Nom, numero du client")

        self.add_clt_btt = BttSmall(u"+")
        self.add_clt_btt.clicked.connect(self.add_clt)
        self.add_clt_btt.setFixedWidth(50)

        # Combobox widget for add store
        self.liste_type_invoice = [Invoice.TYPE_FACT, Invoice.TYPE_BON]

        self.box_type_inv = QComboBox()
        for index in range(0, len(self.liste_type_invoice)):
            op = self.liste_type_invoice[index]
            sentence = u"%(name)s" % {'name': op}
            self.box_type_inv.addItem(sentence, op)

        self.search_field = LineEdit()
        self.search_field.setPlaceholderText("Rechercher un article")
        self.search_field.textChanged.connect(self.finder)
        # self.search_field.setFixedWidth(250)

        self.table_invoice = InvoiceTableWidget(parent=self)
        self.table_resultat = ResultatTableWidget(parent=self)
        self.table_info = InfoTableWidget(parent=self)
        self.table_resultat.refresh_("")
        editbox.addWidget(self.box_type_inv, 0, 2)
        editbox.addWidget(self.num_invoice, 0, 3)
        editbox.addWidget(FLabel(u"Doit :"), 1, 2)
        editbox.addWidget(self.name_client_field, 1, 3)
        # editbox.addWidget(self.add_clt_btt, 1, 4)
        editbox.addWidget(self.invoice_date, 0, 6)
        editbox.setColumnStretch(0, 1)
        editbox.setColumnStretch(5, 1)
        splitter = QSplitter(Qt.Horizontal)

        splitter_left = QSplitter(Qt.Vertical)
        splitter_left.addWidget(self.search_field)
        splitter_left.addWidget(self.table_resultat)
        # splitter_down.resize(15, 20)
        splitter_down = QSplitter(Qt.Vertical)
        splitter_down.addWidget(self.table_info)
        splitter_rigth = QSplitter(Qt.Vertical)

        # splitter_rigth.setLayout(editbox)
        splitter_rigth.addWidget(self.table_invoice)
        splitter_rigth.resize(800, 900)

        splitter_left.addWidget(splitter_down)
        splitter.addWidget(splitter_left)
        splitter.addWidget(splitter_rigth)

        vbox.addLayout(editbox)
        vbox.addWidget(splitter)
        self.setLayout(vbox)
Exemplo n.º 58
0
def create_invoice_process():

    inv = Invoice()

    try:
        inv.info = request.form['costumer']
        inv.date = datetime.strptime(request.form['date'], '%d %B, %Y')  # CONVERT STRING TO DATETIME
        category = request.form['category']
        inv.seller = request.form['seller']
        inv.invoice_id = request.form['invoice_id']
    except Exception as e:
        raise e

    try:
        inv.pending = request.form['pending']
    except Exception as e:
        inv.pending = 0

    items_list_id_quantity = []
    for x in range(1, 6):
        try:
            items_list_id_quantity.append((request.form['id'+str(x)], request.form['quantity'+str(x)]))
        except Exception as e:
            print(e)

    items_full = []
    for item in items_list_id_quantity:

        if item[0]:
            # LIST OF TUPLES WITH (ID, PRICE, QUANTITY )
            items_full.append((item[0], inv.get_price_category(item[0], category), item[1]))

    total = 0
    invoice = []
    for item in items_full:
        subtotal = 0
        quantity = int(item[2])
        price = int(item[1])
        subtotal = quantity * price
        total += subtotal

        # TODO: THIS IS STATIC. FIND A DYNAMIC SOLUTION CODE: 508
        if item[0][0] == '1':
            invoice.append((quantity, inv.get_item_description_by_id(1), price, subtotal))
        elif item[0][0] == '2':
            invoice.append((quantity, inv.get_item_description_by_id(2), price, subtotal))
        elif item[0][0] == '3':
            invoice.append((quantity, inv.get_item_description_by_id(3), price, subtotal))
        elif item[0][0] == '4':
            invoice.append((quantity, inv.get_item_description_by_id(3), price, subtotal))
        elif item[0][0] == '5':
            invoice.append((quantity, inv.get_item_description_by_id(3), price, subtotal))
        elif item[0][0] == '6':
            invoice.append((quantity, inv.get_item_description_by_id(3), price, subtotal))
        else:
            invoice.append((quantity, "Unidentified item. CODE: 580", price, subtotal))

    invoice_list = ""
    for k in invoice:
        invoice_list += str(k)
    inv.items = invoice_list.replace("'", "")
    inv.total = total

    try:
        inv.create_invoice()
    except Exception as e:
        print(e)
        return redirect(url_for('create_invoice', flash="Invoice couldn't been created."))

    return redirect(url_for('create_invoice', flash='Invoice created successfully.'))