Exemple #1
0
def doCheckout():
    invoice = Invoice()
    cartid = request.cookies.get('cart')
    fullname = request.form.get('fullname')
    address = request.form.get('address')
    phone = request.form.get('phone')
    email = request.form.get('email')
    invoice.add((cartid, fullname, address, phone, email))
    return redirect('/cart/success/'+ cartid)
Exemple #2
0
def apply_invoice(invoice_id):
    invoice = Invoice.get(invoice_id)
    if not invoice:
        abort(404)
    invoices_ids = request.values.getlist('invoices')
    invoices = Invoice.gets(invoices_ids)
    if not invoices:
        abort(403)
    emails = request.values.getlist('email')
    msg = request.values.get('msg', '')
    action = int(request.values.get('action', 0))
    to_users = invoice.client_order.direct_sales + invoice.client_order.agent_sales + \
        [invoice.client_order.creator, g.user] + \
        invoice.client_order.leaders
    send_type = "saler"
    if action == 2:
        invoice_status = INVOICE_STATUS_APPLY
        action_msg = u'客户发票开具申请'
    elif action == 3:
        to_users = User.finances()
        invoice_status = INVOICE_STATUS_APPLYPASS
        action_msg = u'同意客户发票开具申请'
        send_type = "finance"
    elif action == 4:
        invoice_status = INVOICE_STATUS_FAIL
        action_msg = u'客户发票开具申请未通过'
    if action != 10:
        for invoice in invoices:
            invoice.invoice_status = invoice_status
            invoice.create_time = datetime.date.today()
            invoice.save()
            flash(
                u'[%s 发票开具申请,发票金额%s]  %s ' %
                (invoice.company, invoice.money, action_msg), 'success')
            invoice.client_order.add_comment(
                g.user,
                u"%s,%s" % (action_msg, u'发票内容: %s; 发票金额: %s元' %
                            (invoice.detail, str(invoice.money))),
                msg_channel=1)
    else:
        action_msg = u'消息提醒'

    context = {
        "to_users": to_users,
        "action_msg": action_msg,
        "info": msg,
        "order": invoice.client_order,
        "send_type": send_type,
        "action": action,
        "invoices": invoices,
        "to_other": emails
    }
    invoice_apply_signal.send(current_app._get_current_object(),
                              context=context)
    return redirect(
        url_for("saler_client_order_invoice.index",
                order_id=invoice.client_order.id))
Exemple #3
0
 def create_invoice(cls, number, date, provider,
                         sum_without_NDS=None, sum_with_NDS=None,
                         sum_NDS=None, weight=None, responsible=None):
     invmodel = Invoice(
        number=number, date=date,
        sum_without_NDS=sum_without_NDS, sum_with_NDS=sum_with_NDS,
        sum_NDS=sum_NDS, weight=weight, responsible=responsible)
     if provider:
         invmodel.provider = provider
     db.session.add(invmodel)
     return invmodel
Exemple #4
0
def apply_invoice(invoice_id):
    invoice = Invoice.get(invoice_id)
    if not invoice:
        abort(404)
    invoices_ids = request.values.getlist('invoices')
    invoices = Invoice.gets(invoices_ids)
    if not invoices:
        abort(403)
    emails = request.values.getlist('email')
    msg = request.values.get('msg', '')
    action = int(request.values.get('action', 0))
    to_users = invoice.client_order.direct_sales + invoice.client_order.agent_sales + \
        [invoice.client_order.creator, g.user] + \
        invoice.client_order.leaders
    send_type = "saler"
    if action == 2:
        invoice_status = INVOICE_STATUS_APPLY
        action_msg = u'客户发票开具申请'
    elif action == 3:
        to_users = User.finances()
        invoice_status = INVOICE_STATUS_APPLYPASS
        action_msg = u'同意客户发票开具申请'
        send_type = "finance"
    elif action == 4:
        invoice_status = INVOICE_STATUS_FAIL
        action_msg = u'客户发票开具申请未通过'
    if action != 10:
        for invoice in invoices:
            invoice.invoice_status = invoice_status
            invoice.create_time = datetime.date.today()
            invoice.save()
            flash(u'[%s 发票开具申请,发票金额%s]  %s ' %
                  (invoice.company, invoice.money, action_msg), 'success')
            invoice.client_order.add_comment(g.user, u"%s,%s" % (
                action_msg, u'发票内容: %s; 发票金额: %s元' % (invoice.detail, str(invoice.money))), msg_channel=1)
    else:
        action_msg = u'消息提醒'

    context = {"to_users": to_users,
               "action_msg": action_msg,
               "info": msg,
               "order": invoice.client_order,
               "send_type": send_type,
               "action": action,
               "invoices": invoices,
               "to_other": emails
               }
    invoice_apply_signal.send(
        current_app._get_current_object(), context=context)
    return redirect(url_for("saler_client_order_invoice.index", order_id=invoice.client_order.id))
Exemple #5
0
def agent_invoice():
    now_date = datetime.datetime.now()
    info = request.values.get('info', '').strip()
    location = int(request.values.get('location', 0))
    year = request.values.get('year', now_date.strftime('%Y'))
    month = request.values.get('month', now_date.strftime('%m'))

    if month != '00':
        search_date = datetime.datetime.strptime(
            str(year) + '-' + str(month), '%Y-%m')
        end_search_date = (
            search_date + datetime.timedelta(days=(search_date.max.day - search_date.day) + 1)).replace(day=1)
        orders = [k for k in Invoice.query.filter(Invoice.create_time >= search_date,
                                                  Invoice.create_time < end_search_date,
                                                  Invoice.invoice_status == 0) if k.client_order.status == 1]
    else:
        orders = [k for k in Invoice.all() if k.create_time.year == int(
            year) and k.invoice_status == 0 and k.client_order.status == 1]
    if location != 0:
        orders = [k for k in orders if location in k.client_order.locations]
    if info:
        orders = [k for k in orders if info in k.client_order.search_invoice_info]
    orders = sorted(list(orders), key=lambda x: x.create_time, reverse=False)
    if request.values.get('action', '') == 'download':
        response = write_order_excel(list(orders), 'agent_invoice')
        return response
    return tpl('/saler/client_order/data_query/index.html',
               orders=orders, location=location,
               year=year, month=month, info=info,
               title=u"已开客户发票", t_type='agent_invoice')
Exemple #6
0
def new_invoice(order_id):
    order = ClientOrder.get(order_id)
    if not order:
        abort(404)
    form = InvoiceForm(request.form)
    form.client_order.choices = [(order.id, order.client.name)]
    if request.method == 'POST' and form.validate():
        if int(form.money.data) > (int(order.money) - int(order.invoice_apply_sum) - int(order.invoice_pass_sum)):
            flash(u"新建发票失败,您申请的发票超过了合同总额", 'danger')
            return redirect(url_for("finance_client_order_invoice.info", order_id=order_id))
        invoice = Invoice.add(client_order=order,
                              company=form.company.data,
                              tax_id=form.tax_id.data,
                              address=form.address.data,
                              phone=form.phone.data,
                              bank_id=form.bank_id.data,
                              bank=form.bank.data,
                              detail=form.detail.data,
                              money=form.money.data,
                              invoice_type=form.invoice_type.data,
                              creator=g.user,
                              invoice_status=0,
                              invoice_num=request.values.get(
                                  'new_invoice_num', ''),
                              back_time=form.back_time.data,
                              create_time=request.values.get('create_time',
                                                             datetime.datetime.now().strftime('%Y-%m-%d')))
        invoice.save()
        flash(u'开发票(%s)成功!' % form.company.data, 'success')
        order.add_comment(g.user, u"已开发票信息:%s" % (
            u'发票内容: %s; 发票金额: %s元' % (invoice.detail, str(invoice.money))), msg_channel=1)
    else:
        for k in form.errors:
            flash(u"新建发票失败,%s" % (form.errors[k][0]), 'danger')
    return redirect(url_for("finance_client_order_invoice.info", order_id=order.id))
Exemple #7
0
def index():
    if not g.user.is_finance():
        abort(404)
    search_info = request.args.get('searchinfo', '').strip()
    location_id = int(request.args.get('selected_location', '-1'))
    year = int(request.values.get('year', datetime.datetime.now().year))
    orders = set([
        invoice.client_order for invoice in Invoice.get_invoices_status(INVOICE_STATUS_APPLYPASS)])
    if location_id >= 0:
        orders = [o for o in orders if location_id in o.locations]
    orders = [k for k in orders if k.client_start.year == year or k.client_end.year == year]
    if search_info != '':
        orders = [
            o for o in orders if search_info.lower() in o.search_invoice_info.lower()]
    select_locations = TEAM_LOCATION_CN.items()
    select_locations.insert(0, (-1, u'全部区域'))
    select_statuses = CONTRACT_STATUS_CN.items()
    select_statuses.insert(0, (-1, u'全部合同状态'))
    for k in orders:
        k.apply_count = len(k.get_invoice_by_status(3))
    return tpl('/finance/client_order/invoice/index.html', orders=orders, locations=select_locations,
               location_id=location_id, statuses=select_statuses,
               now_date=datetime.date.today(), search_info=search_info, year=year,
               params='?&searchinfo=%s&selected_location=%s&year=%s' %
                      (search_info, location_id, str(year)))
Exemple #8
0
def update_invoice(invoice_id):
    invoice = Invoice.get(invoice_id)
    if not invoice:
        abort(404)
    if request.method == 'POST':
        company = request.values.get('edit_company', '')
        tax_id = request.values.get('edit_tax_id', '')
        detail = request.values.get('edit_detail', '')
        money = request.values.get('edit_money', 0)
        invoice_num = request.values.get('edit_invoice_num', '')
        invoice_type = request.values.get('invoice_type', 0)
        create_time = request.values.get(
            'edit_create_time', datetime.datetime.now().strftime('%Y-%m-%d'))
        if not tax_id:
            flash(u"修改发票失败,公司名称不能为空", 'danger')
        elif not detail:
            flash(u"修改发票失败,发票内容不能为空", 'danger')
        elif not money:
            flash(u"修改发票失败,发票金额不能为空", 'danger')
        elif not invoice_num:
            flash(u"修改发票失败,发票号不能为空", 'danger')
        else:
            invoice.company = company
            invoice.tax_id = tax_id
            invoice.detail = detail
            invoice.invoice_num = invoice_num
            invoice.money = money
            invoice.invoice_type = invoice_type
            invoice.create_time = create_time
            invoice.save()
            flash(u'修改发票(%s)成功!' % company, 'success')
            invoice.client_order.add_comment(g.user, u"修改发票信息,%s" % (
                u'发票内容: %s; 发票号: %s; 发票金额: %s元' % (invoice.detail, invoice_num, str(invoice.money))), msg_channel=1)
    return redirect(url_for("finance_client_order_invoice.info", order_id=invoice.client_order.id))
Exemple #9
0
def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Invoice], safe=True)
    try:
        User.create(first_name="Felician",
                    last_name="Mueni",
                    email="*****@*****.**",
                    company="Acme Corp.")
    except IntegrityError:
        pass
    try:
        Invoice.create(user_email="*****@*****.**",
                       design_fee=500,
                       hosting_fee=175,
                       domain_fee=10)
    except IntegrityError:
        pass
    DATABASE.close()
Exemple #10
0
def index():
    bootstrap.initialize()
    user = User.select().where(User.email == "*****@*****.**").get()
    invoice = Invoice.select().where(Invoice.user_email == user.email).get()
    total = invoice.design_fee + invoice.hosting_fee + invoice.developer_fee + invoice.domain_fee
    return render_template("invoice.html",
                           user=user,
                           invoice=invoice,
                           total=total)
    def update_entries(self):
        from dal.dao import Dao
        from models.invoice import Invoice

        dao = Dao(stateful=True)

        invoice_rex = self.import_spreadsheet()

        for invoice_rec in list(invoice_rex):
            ledger_rec = Invoice.get_by_invoice(dao, invoice_rec.invoice_num)
            if ledger_rec:
                ledger_rec.update_balance(dao, invoice_rec.amount)

        new_rex = Invoice.get_rex(dao)

        dao.close()

        gbl.dataset.set_ledger_data(new_rex)
        self.init_view()
def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Invoice], safe=True)
    try:
        User.create(first_name="Jane",
                    last_name="Lodipo",
                    email="*****@*****.**",
                    company="Acme Corp.")
    except IntegrityError:
        pass
    try:
        Invoice.create(user_email="*****@*****.**",
                       design_fee=500,
                       hosting_fee=200,
                       domain_fee=100,
                       developer_fee=4000)
    except IntegrityError:
        pass
    DATABASE.close()
Exemple #13
0
def delete_invoice(invoice_id):
    if not g.user.is_finance():
        abort(404)
    invoice = Invoice.get(invoice_id)
    order_id = invoice.client_order.id
    invoice.client_order.add_comment(g.user, u"删除发票信息:%s" % (
        u'发票内容: %s; 发票金额: %s元' % (invoice.detail, str(invoice.money))), msg_channel=1)
    invoice.delete()
    flash(u"删除成功", 'danger')
    return redirect(url_for("finance_client_order_invoice.info", order_id=order_id))
Exemple #14
0
def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Invoice], safe=True)
    try:
        User.create(first_name="assumpter",
                    last_name="Kimeu",
                    email="*****@*****.**",
                    company="Acme Corp.")
    except IntegrityError:
        pass
    try:
        Invoice.create(user_email="*****@*****.**",
                       design_fee=500,
                       hosting_fee=175,
                       domain_fee=10,
                       developer_fee=1000)
    except IntegrityError:
        pass
    DATABASE.close()
def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Invoice], safe=True)
    try:
        User.create(first_name="yvonne",
                    last_name="jahenda",
                    email="*****@*****.**",
                    company="Acme Corp.")
    except IntegrityError:
        pass
    for invoice in invoices:
        try:
            Invoice.create(user_email=invoice.get('user_email'),
                           design_fee=invoice.get('design_fee'),
                           hosting_fee=invoice.get('hosting_fee'),
                           developer_fee=invoice.get('developer_fee'),
                           domain_fee=invoice.get('domain_fee'))
        except IntegrityError:
            pass
    DATABASE.close()
Exemple #16
0
def create_invoice():

    name = request.form.get('name')
    street = request.form.get('street')
    housenumber = request.form.get('housenumber')
    postal = request.form.get('postal')
    city = request.form.get('city')
    country = request.form.get('country')
    phone = request.form.get('phone')

    invoice = Invoice.get_or_none(Invoice.user == current_user.id)
    if invoice:
        invoice = Invoice.update(
            name=name,
            street=street,
            housenumber=housenumber,
            postal=postal,
            city=city,
            country=country,
            phone=phone).where(Invoice.user == current_user.id)
        if invoice.execute():
            flash('wijziging is opgeslagen')
            return redirect(url_for('users.show'))
        else:
            flash('wijziging niet opgeslagen')
            return redirect(url_for('users.show'))
    else:
        invoice = Invoice(name=name,
                          street=street,
                          housenumber=housenumber,
                          postal=postal,
                          city=city,
                          country=country,
                          phone=phone,
                          user=current_user.id)
        if invoice.save():
            flash('wijziging is opgeslagen')
            return redirect(url_for('users.show'))
        else:
            flash('wijziging niet opgeslagen')
            return redirect(url_for('users.show'))
Exemple #17
0
    def __invoice_db(self):
        print(bcolors.BOLD + '---------- Invoice DB ----------' + bcolors.ENDC)
        if not self.profile:
            print(
                bcolors.HEADER + 'no profile ?> ' + bcolors.ENDC,
                bcolors.OKGREEN + 'OK' if False else bcolors.FAIL +
                "Please call __profile_db()", bcolors.ENDC)
            return
        if not self.client:
            print(
                bcolors.HEADER + 'no client ?> ' + bcolors.ENDC,
                bcolors.OKGREEN + 'OK' if False else bcolors.FAIL +
                "Please call __client_db()", bcolors.ENDC)
            return
        self.invoice = Invoice()
        self.invoice.date_expiry = '01/01/2020'
        self.invoice.date_sent = '01/01/2020'
        self.invoice.days = 10
        self.invoice.max_delay = '01/01/2020'
        self.invoice.id_client = self.client.id
        self.invoice.id_profile = self.profile.id
        self.invoice.name = 'Invoice TEST 1'
        self.invoice.sold = False
        self.invoice.project = 'TEST 1 2 3'
        self.invoice.day_rate = 5000
        self.invoice.total = '50000'
        self.invoice.tax = False

        insindao = self.fdao.insert(self.invoice)
        print(bcolors.HEADER + 'insert invoice ?> ' + bcolors.ENDC,
              bcolors.OKGREEN + 'OK' if insindao else bcolors.FAIL + "KO",
              bcolors.ENDC)
        self.invoice.sold = True
        chpyfdao = self.fdao.update(self.invoice)
        print(bcolors.HEADER + 'update invoice ?> ' + bcolors.ENDC,
              bcolors.OKGREEN + 'OK' if chpyfdao else bcolors.FAIL + "KO",
              bcolors.ENDC)
        get_invoice_list = self.fdao.get(
            self.fdao.where('id_client', self.invoice.id_client))
        print(
            bcolors.HEADER + 'get invoice ?> ' + bcolors.ENDC,
            bcolors.OKGREEN + 'OK' if get_invoice_list else bcolors.FAIL +
            "KO", bcolors.ENDC)
        if not get_invoice_list:
            return False
        self.invoice = get_invoice_list[0]
        is_change_sold = self.invoice.sold
        print(
            bcolors.HEADER + 'change to bill invoice ?> ' + bcolors.ENDC,
            bcolors.OKGREEN + 'OK' if is_change_sold else bcolors.FAIL + "KO",
            bcolors.ENDC)
        return (insindao and chpyfdao and is_change_sold)
Exemple #18
0
def index_pass():
    if not g.user.is_finance():
        abort(404)
    orders = list(ClientOrder.all())
    search_info = request.args.get('searchinfo', '').strip()
    location_id = int(request.args.get('selected_location', '-1'))
    year = int(request.values.get('year', datetime.datetime.now().year))
    page = int(request.args.get('p', 1))
    if location_id >= 0:
        orders = [o for o in orders if location_id in o.locations]
    orders = [
        k for k in orders
        if k.client_start.year == year or k.client_end.year == year
    ]
    if search_info != '':
        orders = [
            o for o in orders
            if search_info.lower() in o.search_invoice_info.lower()
        ]
    select_locations = TEAM_LOCATION_CN.items()
    select_locations.insert(0, (-1, u'全部区域'))
    select_statuses = CONTRACT_STATUS_CN.items()
    select_statuses.insert(0, (-1, u'全部合同状态'))
    paginator = Paginator(orders, ORDER_PAGE_NUM)
    try:
        orders = paginator.page(page)
    except:
        orders = paginator.page(paginator.num_pages)
    type = request.args.get('type', '')
    if type == 'excel':
        orders = set([
            invoice.client_order
            for invoice in Invoice.get_invoices_status(INVOICE_STATUS_PASS)
        ])
        xls = write_excel(list(orders))
        response = get_download_response(
            xls,
            ("%s-%s.xls" %
             (u"申请过的发票信息", datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
             ).encode('utf-8'))
        return response
    return tpl('/finance/client_order/invoice/index_pass.html',
               orders=orders,
               locations=select_locations,
               location_id=location_id,
               statuses=select_statuses,
               now_date=datetime.date.today(),
               search_info=search_info,
               page=page,
               year=year,
               params='&searchinfo=%s&selected_location=%s&year=%s' %
               (search_info, location_id, str(year)))
Exemple #19
0
def invoice_num(invoice_id):
    if not g.user.is_finance():
        abort(404)
    invoice = Invoice.get(invoice_id)
    if not invoice:
        abort(404)
    invoice_num = request.values.get('invoice_num', '')
    invoice.invoice_num = invoice_num
    invoice.save()
    flash(u'保存成功!', 'success')
    invoice.client_order.add_comment(
        g.user, u"%s" % (u'更新了发票号: %s;' % (invoice.invoice_num)), msg_channel=1)
    return redirect(url_for("finance_client_order_invoice.info", order_id=invoice.client_order.id))
def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Invoice], safe=True)
    try:
        User.create(first_name='first_name',
                    last_name='last_name',
                    email='*****@*****.**',
                    company='Acme')
    except IntegrityError:
        pass
    for invoice in invoices:
        try:
            Invoice.create(
                user_email=invoice.get('user_email'),
                design_fee=invoice.get('design_fee'),
                hosting_fee=invoice.get('hosting_fee'),
                domain_fee=invoice.get('domain_fee'),
                dev_fee=invoice.get('dev_fee'),
            )
        except IntegrityError:
            pass
    DATABASE.close()
Exemple #21
0
def delete_invoice(invoice_id):
    if not g.user.is_finance():
        abort(404)
    invoice = Invoice.get(invoice_id)
    order_id = invoice.client_order.id
    invoice.client_order.add_comment(g.user,
                                     u"删除发票信息:%s" %
                                     (u'发票内容: %s; 发票金额: %s元' %
                                      (invoice.detail, str(invoice.money))),
                                     msg_channel=1)
    invoice.delete()
    flash(u"删除成功", 'danger')
    return redirect(
        url_for("finance_client_order_invoice.info", order_id=order_id))
Exemple #22
0
 def setUp(self):
     self.fdao = InvoiceDAO(DB_PATH)
     self.invoice = Invoice()
     self.invoice.date_expiry = '01/01/2020'
     self.invoice.date_sent = '01/01/2020'
     self.invoice.days = 10
     self.invoice.max_delay = '01/01/2020'
     self.invoice.id_client = 1
     self.invoice.id_profile = 1
     self.invoice.name = 'FACTURE TEST 1'
     self.invoice.sold = False
     self.invoice.project = 'TEST 1 2 3'
     self.invoice.day_rate = 5000
     self.invoice.total = '50000'
     self.invoice.tax = False
Exemple #23
0
def show():
    user = User.get_by_id(current_user.id)
    adress = Adress.get_or_none(Adress.user == user.id)
    invoice = Invoice.get_or_none(Invoice.user == user.id)
    ad = False
    inv = False
    if adress:
        ad = True
    if invoice:
        inv = True

    return render_template('users/show.html',
                           inv=inv,
                           invoice=invoice,
                           user=user,
                           ad=ad,
                           adress=adress)
Exemple #24
0
def invoice_num(invoice_id):
    if not g.user.is_finance():
        abort(404)
    invoice = Invoice.get(invoice_id)
    if not invoice:
        abort(404)
    invoice_num = request.values.get('invoice_num', '')
    invoice.invoice_num = invoice_num
    invoice.save()
    flash(u'保存成功!', 'success')
    invoice.client_order.add_comment(g.user,
                                     u"%s" % (u'更新了发票号: %s;' %
                                              (invoice.invoice_num)),
                                     msg_channel=1)
    return redirect(
        url_for("finance_client_order_invoice.info",
                order_id=invoice.client_order.id))
Exemple #25
0
def new_invoice(order_id):
    order = ClientOrder.get(order_id)
    if not order:
        abort(404)
    form = InvoiceForm(request.form)
    form.client_order.choices = [(order.id, order.client.name)]
    if request.method == 'POST' and form.validate():
        if int(form.money.data) > (int(order.money) - int(
                order.invoice_apply_sum) - int(order.invoice_pass_sum)):
            flash(u"新建发票失败,您申请的发票超过了合同总额", 'danger')
            return redirect(
                url_for("finance_client_order_invoice.info",
                        order_id=order_id))
        invoice = Invoice.add(
            client_order=order,
            company=form.company.data,
            tax_id=form.tax_id.data,
            address=form.address.data,
            phone=form.phone.data,
            bank_id=form.bank_id.data,
            bank=form.bank.data,
            detail=form.detail.data,
            money=form.money.data,
            invoice_type=form.invoice_type.data,
            creator=g.user,
            invoice_status=0,
            invoice_num=request.values.get('new_invoice_num', ''),
            back_time=form.back_time.data,
            create_time=request.values.get(
                'create_time',
                datetime.datetime.now().strftime('%Y-%m-%d')))
        invoice.save()
        flash(u'开发票(%s)成功!' % form.company.data, 'success')
        order.add_comment(g.user,
                          u"已开发票信息:%s" %
                          (u'发票内容: %s; 发票金额: %s元' %
                           (invoice.detail, str(invoice.money))),
                          msg_channel=1)
    else:
        for k in form.errors:
            flash(u"新建发票失败,%s" % (form.errors[k][0]), 'danger')
    return redirect(
        url_for("finance_client_order_invoice.info", order_id=order.id))
Exemple #26
0
def update_invoice(invoice_id):
    invoice = Invoice.get(invoice_id)
    if not invoice:
        abort(404)
    form = InvoiceForm(request.form)
    form.client_order.choices = [(invoice.client_order.id,
                                  invoice.client_order.client.name)]
    if request.method == 'POST' and form.validate():
        back_time = request.values.get('back_time', datetime.date.today())
        if not form.tax_id.data:
            flash(u"修改发票失败,公司名称不能为空", 'danger')
        elif not form.detail.data:
            flash(u"修改发票失败,发票内容不能为空", 'danger')
        elif not form.money.data:
            flash(u"修改发票失败,发票金额不能为空", 'danger')
        else:
            invoice.company = form.company.data,
            invoice.tax_id = form.tax_id.data,
            invoice.address = form.address.data,
            invoice.phone = form.phone.data,
            invoice.bank_id = form.bank_id.data,
            invoice.bank = form.bank.data,
            invoice.detail = form.detail.data,
            invoice.money = form.money.data,
            invoice.invoice_type = form.invoice_type.data,
            invoice.creator = g.user
            invoice.create_time = datetime.date.today()
            invoice.back_time = back_time
            invoice.save()
            flash(u'修改发票(%s)成功!' % form.company.data, 'success')
            invoice.client_order.add_comment(
                g.user,
                u"修改发票信息,%s" % (u'发票内容: %s; 发票金额: %s元' %
                                (invoice.detail, str(invoice.money))),
                msg_channel=1)
    else:
        for k in form.errors:
            flash(u"修改发票失败,%s" % (form.errors[k][0]), 'danger')
    return redirect(
        url_for("saler_client_order_invoice.index",
                order_id=invoice.client_order.id))
Exemple #27
0
def update_invoice(invoice_id):
    invoice = Invoice.get(invoice_id)
    if not invoice:
        abort(404)
    if request.method == 'POST':
        company = request.values.get('edit_company', '')
        tax_id = request.values.get('edit_tax_id', '')
        detail = request.values.get('edit_detail', '')
        money = request.values.get('edit_money', 0)
        invoice_num = request.values.get('edit_invoice_num', '')
        invoice_type = request.values.get('invoice_type', 0)
        create_time = request.values.get(
            'edit_create_time',
            datetime.datetime.now().strftime('%Y-%m-%d'))
        if not tax_id:
            flash(u"修改发票失败,公司名称不能为空", 'danger')
        elif not detail:
            flash(u"修改发票失败,发票内容不能为空", 'danger')
        elif not money:
            flash(u"修改发票失败,发票金额不能为空", 'danger')
        elif not invoice_num:
            flash(u"修改发票失败,发票号不能为空", 'danger')
        else:
            invoice.company = company
            invoice.tax_id = tax_id
            invoice.detail = detail
            invoice.invoice_num = invoice_num
            invoice.money = money
            invoice.invoice_type = invoice_type
            invoice.create_time = create_time
            invoice.save()
            flash(u'修改发票(%s)成功!' % company, 'success')
            invoice.client_order.add_comment(
                g.user,
                u"修改发票信息,%s" %
                (u'发票内容: %s; 发票号: %s; 发票金额: %s元' %
                 (invoice.detail, invoice_num, str(invoice.money))),
                msg_channel=1)
    return redirect(
        url_for("finance_client_order_invoice.info",
                order_id=invoice.client_order.id))
Exemple #28
0
def agent_invoice():
    now_date = datetime.datetime.now()
    info = request.values.get('info', '').strip()
    location = int(request.values.get('location', 0))
    year = request.values.get('year', now_date.strftime('%Y'))
    month = request.values.get('month', now_date.strftime('%m'))

    if month != '00':
        search_date = datetime.datetime.strptime(
            str(year) + '-' + str(month), '%Y-%m')
        end_search_date = (search_date + datetime.timedelta(
            days=(search_date.max.day - search_date.day) + 1)).replace(day=1)
        orders = [
            k for k in Invoice.query.filter(
                Invoice.create_time >= search_date, Invoice.create_time <
                end_search_date, Invoice.invoice_status == 0)
            if k.client_order.status == 1
        ]
    else:
        orders = [
            k for k in Invoice.all() if k.create_time.year == int(year)
            and k.invoice_status == 0 and k.client_order.status == 1
        ]
    if location != 0:
        orders = [k for k in orders if location in k.client_order.locations]
    if info:
        orders = [
            k for k in orders if info in k.client_order.search_invoice_info
        ]
    orders = sorted(list(orders), key=lambda x: x.create_time, reverse=False)
    if request.values.get('action', '') == 'download':
        response = write_order_excel(list(orders), 'agent_invoice')
        return response
    return tpl('/saler/client_order/data_query/index.html',
               orders=orders,
               location=location,
               year=year,
               month=month,
               info=info,
               title=u"已开客户发票",
               t_type='agent_invoice')
Exemple #29
0
def index():
    if not g.user.is_finance():
        abort(404)
    search_info = request.args.get('searchinfo', '').strip()
    location_id = int(request.args.get('selected_location', '-1'))
    year = int(request.values.get('year', datetime.datetime.now().year))
    orders = set([
        invoice.client_order
        for invoice in Invoice.get_invoices_status(INVOICE_STATUS_APPLYPASS)
    ])
    if location_id >= 0:
        orders = [o for o in orders if location_id in o.locations]
    orders = [
        k for k in orders
        if k.client_start.year == year or k.client_end.year == year
    ]
    if search_info != '':
        orders = [
            o for o in orders
            if search_info.lower() in o.search_invoice_info.lower()
        ]
    select_locations = TEAM_LOCATION_CN.items()
    select_locations.insert(0, (-1, u'全部区域'))
    select_statuses = CONTRACT_STATUS_CN.items()
    select_statuses.insert(0, (-1, u'全部合同状态'))
    for k in orders:
        k.apply_count = len(k.get_invoice_by_status(3))
    return tpl('/finance/client_order/invoice/index.html',
               orders=orders,
               locations=select_locations,
               location_id=location_id,
               statuses=select_statuses,
               now_date=datetime.date.today(),
               search_info=search_info,
               year=year,
               params='?&searchinfo=%s&selected_location=%s&year=%s' %
               (search_info, location_id, str(year)))
Exemple #30
0
def update_invoice(invoice_id):
    invoice = Invoice.get(invoice_id)
    if not invoice:
        abort(404)
    form = InvoiceForm(request.form)
    form.client_order.choices = [
        (invoice.client_order.id, invoice.client_order.client.name)]
    if request.method == 'POST' and form.validate():
        back_time = request.values.get('back_time', datetime.date.today())
        if not form.tax_id.data:
            flash(u"修改发票失败,公司名称不能为空", 'danger')
        elif not form.detail.data:
            flash(u"修改发票失败,发票内容不能为空", 'danger')
        elif not form.money.data:
            flash(u"修改发票失败,发票金额不能为空", 'danger')
        else:
            invoice.company = form.company.data,
            invoice.tax_id = form.tax_id.data,
            invoice.address = form.address.data,
            invoice.phone = form.phone.data,
            invoice.bank_id = form.bank_id.data,
            invoice.bank = form.bank.data,
            invoice.detail = form.detail.data,
            invoice.money = form.money.data,
            invoice.invoice_type = form.invoice_type.data,
            invoice.creator = g.user
            invoice.create_time = datetime.date.today()
            invoice.back_time = back_time
            invoice.save()
            flash(u'修改发票(%s)成功!' % form.company.data, 'success')
            invoice.client_order.add_comment(g.user, u"修改发票信息,%s" % (
                u'发票内容: %s; 发票金额: %s元' % (invoice.detail, str(invoice.money))), msg_channel=1)
    else:
        for k in form.errors:
            flash(u"修改发票失败,%s" % (form.errors[k][0]), 'danger')
    return redirect(url_for("saler_client_order_invoice.index", order_id=invoice.client_order.id))
Exemple #31
0
def index_pass():
    if not g.user.is_finance():
        abort(404)
    orders = list(ClientOrder.all())
    search_info = request.args.get('searchinfo', '').strip()
    location_id = int(request.args.get('selected_location', '-1'))
    year = int(request.values.get('year', datetime.datetime.now().year))
    page = int(request.args.get('p', 1))
    if location_id >= 0:
        orders = [o for o in orders if location_id in o.locations]
    orders = [k for k in orders if k.client_start.year == year or k.client_end.year == year]
    if search_info != '':
        orders = [
            o for o in orders if search_info.lower() in o.search_invoice_info.lower()]
    select_locations = TEAM_LOCATION_CN.items()
    select_locations.insert(0, (-1, u'全部区域'))
    select_statuses = CONTRACT_STATUS_CN.items()
    select_statuses.insert(0, (-1, u'全部合同状态'))
    paginator = Paginator(orders, ORDER_PAGE_NUM)
    try:
        orders = paginator.page(page)
    except:
        orders = paginator.page(paginator.num_pages)
    type = request.args.get('type', '')
    if type == 'excel':
        orders = set([invoice.client_order for invoice in Invoice.get_invoices_status(
            INVOICE_STATUS_PASS)])
        xls = write_excel(list(orders))
        response = get_download_response(
            xls, ("%s-%s.xls" % (u"申请过的发票信息", datetime.datetime.now().strftime('%Y%m%d%H%M%S'))).encode('utf-8'))
        return response
    return tpl('/finance/client_order/invoice/index_pass.html', orders=orders, locations=select_locations,
               location_id=location_id, statuses=select_statuses,
               now_date=datetime.date.today(), search_info=search_info, page=page, year=year,
               params='&searchinfo=%s&selected_location=%s&year=%s' %
                      (search_info, location_id, str(year)))
    def _get_data(self):
        from dal.dao import Dao
        from tests.ledger_data.test_data import invoices_q2_pre_query

        from models.employee import Employee
        from models.department import Department
        from models.grant_admin import GrantAdmin
        from models.invoice import Invoice
        from models.assignment import Assignment

        dao = Dao(db_path=self.db_path, stateful=True)
        self._emp_rex = Employee.get_all(dao)
        self._dept_rex = Department.get_all(dao)
        self._grant_admin_rex = GrantAdmin.get_all(dao)
        invoices_unpaid = Invoice.get_rex(dao)
        # invoices_unpaid = invoices_q2
        self._invoices_sent = [
            invoice for invoice in invoices_unpaid if invoice.sent
        ]
        self._invoices_unsent = [
            invoice for invoice in invoices_unpaid if not invoice.sent
        ]
        self._asn_rex = Assignment.get_billables(dao)
        dao.close()
Exemple #33
0
def invoice():

    invoices = Invoice.select()
    return render_template("invoiced.html", invoices=invoices)
    def testUpdateEntryWithAmountChange(self):
        self.view.set_year(2020)
        self.view.set_qtr(1)

        self.presenter.run_query()

        # select an entry
        with patch('lib.ui_lib.show_error', return_value=None) as popup_mock:
            click_list_ctrl(self.view.work_list_ctrl, 0)

        # verify no salary popup not called
        popup_mock.assert_not_called()

        # verify details
        expected = {
            'dept': None,
            'admin_approved': False,
            'va_approved': False,
            'invoice_num': 'K0H1002',
            'amount': 4942.04,
            'short_code': '445566',
            'grant_admin': None,
            'grant_admin_email': None
        }
        self.assertEqual(self.view.get_form_values(), expected)

        # verify display only items
        self.assertEqual(self.view.prj_lbl.GetLabelText(), 'Prj 297')
        self.assertEqual(self.view.asn_lbl.GetLabelText(),
                         'GEHRIG,HENRY LOUIS: 10% effort, from 10/19 thru 12/19 (92 days)')
        self.assertEqual(self.view.cost_lbl.GetLabelText(),
                         'Salary: $104,971, Fringe: 33.5%, Total/Day: $537.18')
        self.assertEqual(self.view.amount_ctrl.GetValue(), '4,942.04')

        # edit details
        click_combobox_ctrl(self.view.dept_ctrl, 2)
        check_checkbox_ctrl(self.view.admin_approved_ctrl)
        check_checkbox_ctrl(self.view.va_approved_ctrl)

        # change amount and simulate lost focus event
        enter_in_textbox_ctrl(self.view.amount_ctrl, '1000')
        self.presenter.update_amount_balance('1000')

        click_combobox_ctrl(self.view.grant_admin_ctrl, 3)

        # verify grant admin email is done
        self.assertEqual(self.view.get_grant_admin_email(), '*****@*****.**')

        with patch('dal.dao.Dao._Dao__write') as write_mock:
            write_mock.return_value = 1
            with patch('lib.ui_lib.show_msg') as popup_mock:
                popup_mock.return_value = None
                click_button(self.view.save_form_btn)

        # verify the DB call
        self.assertEqual(write_mock.call_count, 1)
        args, kwargs = write_mock.call_args
        self.assertEqual(len(args), 2)
        self.assertEqual(len(kwargs), 0)
        sql = ("UPDATE ledger "
               "SET dept=?,admin_approved=?,va_approved=?,invoice_num=?,"
               "amount=?,balance=?,short_code=?,"
               "grant_admin=?,grant_admin_email=?,sent=? "
               "WHERE id=?;")
        vals = [
            'CARDIOLOGY', '1', '1', 'K0H1002',
            '1000.0', '1000.0','445566',
            'MARX,HARPO', '*****@*****.**', '0', 2]
        self.assertEqual(args[0], sql)
        self.assertEqual(args[1], vals)

        # verify user notification
        popup_mock.assert_called_once_with('Ledger updated!', 'Hooray')

        # verify list updated
        expected_item = Invoice({
            'admin_approved': True,
            'amount': 1000.0,
            'asn_id': 2272,
            'balance': 1000.0,
            'days': 92,
            'dept': 'CARDIOLOGY',
            'effort': 10,
            'employee': 'GEHRIG,HENRY LOUIS',
            'fringe': 33.5,
            'frum': '1910',
            'grant_admin': 'MARX,HARPO',
            'grant_admin_email': '*****@*****.**',
            'id': 2,
            'invoice_num': 'K0H1002',
            'paid': False,
            'project': 'Prj 297',
            'quarter': 20201,
            'salary': 104971,
            'short_code': '445566',
            'thru': '1912',
            'total_day': 537.18,
            'va_approved': True,
            'sent': False
        })
        self.assertEqual(self.view.get_work_list_selection(), expected_item)
Exemple #35
0
def cost():
    client_invoices = list(Invoice.all())
    medium_invoices = list(MediumInvoice.all())
    medium_invoice_pays = list(MediumInvoicePay.all())
    medium_invoice_rebate_invoice = list(MediumRebateInvoice.all())
    agent_invoices = list(AgentInvoice.all())
    agent_invoice_pays = list(AgentInvoicePay.all())
    back_moneys = list(BackMoney.all())
    back_money_rebates = list(BackInvoiceRebate.all())

    now_date = datetime.datetime.now()
    info = request.values.get('info', '').strip()
    location = int(request.values.get('location', 0))
    year = request.values.get('year', now_date.strftime('%Y'))
    month = request.values.get('month', now_date.strftime('%m'))

    if month != '00':
        search_date = datetime.datetime.strptime(
            str(year) + '-' + str(month), '%Y-%m')
        orders = set([
            k.client_order for k in ClientOrderExecutiveReport.query.filter_by(
                month_day=search_date) if k.status == 1
        ])
    else:
        orders = [
            k for k in ClientOrder.all() if k.client_start.year == int(year)
            or k.client_end.year == int(year)
        ]
    if location != 0:
        orders = [k for k in orders if location in k.locations]
    if info:
        orders = [k for k in orders if info in k.search_info]

    orders = sorted(list(orders), key=lambda x: x.client_start, reverse=False)
    for order in orders:
        order.pass_invoice_sum = sum([
            k.money for k in client_invoices
            if k.invoice_status == 0 and k.client_order == order
        ])
        order.back_money_sum = sum(
            [k.money for k in back_moneys if k.client_order == order])
        order.back_money_rebate_sum = sum(
            [k.money for k in back_money_rebates if k.client_order == order])
        order.agent_invoice_sum = sum(
            [k.money for k in agent_invoices if k.client_order == order])

        agent_invoice_pay_sum = 0.0
        invoices = [k for k in agent_invoices if k.client_order == order]
        for invoice in invoices:
            agent_invoice_pay_sum += sum([
                k.money for k in agent_invoice_pays
                if k.pay_status == 0 and k.agent_invoice == invoice
            ])
        order.agent_invoice_pay_sum = agent_invoice_pay_sum

        order.medium_invoice_sum = sum(
            [k.money for k in medium_invoices if k.client_order == order])
        invoices = [k for k in medium_invoices if k.client_order == order]
        order.medium_invoice_pay_sum = sum([
            k.money for k in medium_invoice_pays
            if k.pay_status == 0 and k.medium_invoice in invoices
        ])
        order.medium_invoice_rebate_invoice_sum = sum([
            k.money for k in medium_invoice_rebate_invoice
            if k.client_order == order and k.invoice_status == 0
        ])
        for m in order.medium_orders:
            m.medium_invoice_sum = sum([
                k.money for k in medium_invoices
                if k.client_order == order and k.medium == m.medium
            ])
            m_invoices = [
                k for k in medium_invoices
                if k.client_order == order and k.medium == m.medium
            ]
            m.medium_invoice_pay_sum = sum([
                k.money for k in medium_invoice_pays
                if k.pay_status == 0 and k.medium_invoice in m_invoices
            ])
            m.medium_invoice_rebate_invoice_sum = sum([
                k.money for k in medium_invoice_rebate_invoice
                if k.client_order == order and k.invoice_status == 0
                and k.medium == m.medium
            ])
    if request.values.get('action', '') == 'download':
        response = write_order_excel(list(orders))
        return response
    return tpl('cost.html',
               orders=orders,
               location=location,
               year=year,
               month=month,
               info=info)
Exemple #36
0
def all_list():
    invoices = Invoice.list()
    return render_template('list.html', invoices=invoices)
Exemple #37
0
def cost():
    client_invoices = list(Invoice.all())
    medium_invoices = list(MediumInvoice.all())
    medium_invoice_pays = list(MediumInvoicePay.all())
    medium_invoice_rebate_invoice = list(MediumRebateInvoice.all())
    agent_invoices = list(AgentInvoice.all())
    agent_invoice_pays = list(AgentInvoicePay.all())
    back_moneys = list(BackMoney.all())
    back_money_rebates = list(BackInvoiceRebate.all())

    now_date = datetime.datetime.now()
    info = request.values.get('info', '').strip()
    location = int(request.values.get('location', 0))
    year = request.values.get('year', now_date.strftime('%Y'))
    month = request.values.get('month', now_date.strftime('%m'))

    if month != '00':
        search_date = datetime.datetime.strptime(
            str(year) + '-' + str(month), '%Y-%m')
        orders = set([k.client_order for k in ClientOrderExecutiveReport.query.filter_by(
            month_day=search_date) if k.status == 1])
    else:
        orders = [k for k in ClientOrder.all() if k.client_start.year == int(
            year) or k.client_end.year == int(year)]
    if location != 0:
        orders = [k for k in orders if location in k.locations]
    if info:
        orders = [k for k in orders if info in k.search_info]

    orders = sorted(list(orders), key=lambda x: x.client_start, reverse=False)
    for order in orders:
        order.pass_invoice_sum = sum(
            [k.money for k in client_invoices if k.invoice_status == 0 and k.client_order == order])
        order.back_money_sum = sum(
            [k.money for k in back_moneys if k.client_order == order])
        order.back_money_rebate_sum = sum(
            [k.money for k in back_money_rebates if k.client_order == order])
        order.agent_invoice_sum = sum(
            [k.money for k in agent_invoices if k.client_order == order])

        agent_invoice_pay_sum = 0.0
        invoices = [k for k in agent_invoices if k.client_order == order]
        for invoice in invoices:
            agent_invoice_pay_sum += sum(
                [k.money for k in agent_invoice_pays if k.pay_status == 0 and k.agent_invoice == invoice])
        order.agent_invoice_pay_sum = agent_invoice_pay_sum

        order.medium_invoice_sum = sum(
            [k.money for k in medium_invoices if k.client_order == order])
        invoices = [k for k in medium_invoices if k.client_order == order]
        order.medium_invoice_pay_sum = sum(
            [k.money for k in medium_invoice_pays if k.pay_status == 0 and k.medium_invoice in invoices])
        order.medium_invoice_rebate_invoice_sum = sum(
            [k.money for k in medium_invoice_rebate_invoice if k.client_order == order and k.invoice_status == 0])
        for m in order.medium_orders:
            m.medium_invoice_sum = sum(
                [k.money for k in medium_invoices if k.client_order == order and k.medium == m.medium])
            m_invoices = [
                k for k in medium_invoices if k.client_order == order and k.medium == m.medium]
            m.medium_invoice_pay_sum = sum(
                [k.money for k in medium_invoice_pays if k.pay_status == 0 and k.medium_invoice in m_invoices])
            m.medium_invoice_rebate_invoice_sum = sum(
                [k.money for k in medium_invoice_rebate_invoice if k.client_order == order and
                 k.invoice_status == 0 and k.medium == m.medium])
    if request.values.get('action', '') == 'download':
        response = write_order_excel(list(orders))
        return response
    return tpl('cost.html', orders=orders, location=location,
               year=year, month=month, info=info)
    def testAddEntryWithAmountChange(self):
        self.view.set_year(2020)
        self.view.set_qtr(1)

        self.presenter.run_query()

        # select an entry
        with patch('lib.ui_lib.show_error', return_value=None) as popup_mock:
            click_list_ctrl(self.view.work_list_ctrl, 4)

        # verify no salary popup not called
        popup_mock.assert_not_called()

        # verify details
        expected = {
            'dept': None,
            'admin_approved': False,
            'va_approved': False,
            'invoice_num': None,
            'amount': 3272.65,
            'short_code': None,
            'grant_admin': None,
            'grant_admin_email': None
        }
        self.assertEqual(self.view.get_form_values(), expected)

        # verify display only items
        self.assertEqual(self.view.prj_lbl.GetLabelText(), 'Prj 315')
        self.assertEqual(self.view.asn_lbl.GetLabelText(),
                         'BANKS,ERNEST: 20% effort, from 10/19 thru 12/19 (92 days)')
        self.assertEqual(self.view.cost_lbl.GetLabelText(),
                         'Salary: $44,444, Fringe: 4.4%, Total/Day: $177.86')
        self.assertEqual(self.view.amount_ctrl.GetValue(), '3,272.65')
        # self.assertEqual(self.view.paid_ctrl.GetValue(), False)
        # self.assertEqual(self.view.balance_ctrl.GetValue(), '3,272.65')

        # edit details
        enter_in_textbox_ctrl(self.view.invoice_ctrl, 'K0H0002')

        # change amount and simulate lost focus event
        enter_in_textbox_ctrl(self.view.amount_ctrl, '1000')
        self.presenter.update_amount_balance('1000')

        enter_in_textbox_ctrl(self.view.short_code_ctrl, '123456')
        click_combobox_ctrl(self.view.dept_ctrl, 2)
        check_checkbox_ctrl(self.view.admin_approved_ctrl)
        check_checkbox_ctrl(self.view.va_approved_ctrl)
        click_combobox_ctrl(self.view.grant_admin_ctrl, 3)

        # verify grant admin email is done
        self.assertEqual(self.view.get_grant_admin_email(), '*****@*****.**')

        with patch('dal.dao.Dao._Dao__write') as write_mock:
            write_mock.return_value = 4
            with patch('lib.ui_lib.show_msg') as popup_mock:
                popup_mock.return_value = None
                click_button(self.view.save_form_btn)

        # verify the DB call
        self.assertEqual(write_mock.call_count, 1)
        args, kwargs = write_mock.call_args
        self.assertEqual(len(args), 2)
        self.assertEqual(len(kwargs), 0)
        sql = ("INSERT INTO ledger "
               "(quarter,dept,admin_approved,va_approved,invoice_num,"
               "asn_id,project,employee,salary,fringe,total_day,frum,thru,"
               "effort,days,amount,paid,balance,short_code,"
               "grant_admin,grant_admin_email) "
               "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
        vals = ['20201', 'CARDIOLOGY', '1', '1', 'K0H0002',
                '2396', 'Prj 315', 'BANKS,ERNEST', '44444', '4.4',
                '177.86', '1910', '1912', '20', '92', '1000.0',
                '0', '1000.0', '123456', 'MARX,HARPO', '*****@*****.**'
        ]
        self.assertEqual(args[0], sql)
        self.assertEqual(args[1], vals)

        # verify user notification
        popup_mock.assert_called_once_with('Ledger updated!', 'Hooray')

        # verify list updated
        expected_item = Invoice({
            'admin_approved': True,
            'amount': 1000.0,
            'asn_id': 2396,
            'balance': 1000.0,
            'days': 92,
            'dept': 'CARDIOLOGY',
            'effort': 20,
            'employee': 'BANKS,ERNEST',
            'fringe': 4.4,
            'frum': '1910',
            'grant_admin': 'MARX,HARPO',
            'grant_admin_email': '*****@*****.**',
            'id': 4,
            'invoice_num': 'K0H0002',
            'paid': False,
            'project': 'Prj 315',
            'quarter': 20201,
            'salary': 44444,
            'short_code': '123456',
            'thru': '1912',
            'total_day': 177.86,
            'va_approved': True
        })
        self.assertEqual(self.view.get_work_list_selection(), expected_item)
Exemple #39
0
 def setUp(self):
     Base.metadata.create_all(self.engine)
     self.invoice = Invoice(serial="1")
     self.session.add(self.invoice)
     self.session.commit()
    def run_query(self):
        qtr_frum, qtr_thru = self.get_query_params()
        # import datetime as dt

        # today = dt.date.today()
        # qtr_frum, qtr_thru = ml.get_quarter_interval(today.year, today.month)
        # self.quarter = int(ml.get_todays_quarter())

        # qtr_frum =
        # Exclude the sent invoices
        sent = gbl.dataset.get_sent_invoices(self.quarter)
        excluded_ids = [invoice.asn_id for invoice in sent]

        # Get ledger records for quarter
        ledger_rex = gbl.dataset.get_unsent_invoices(self.quarter)

        # Get the assignment ids for the assignments already in the ledger
        excluded_ids += [rec.asn_id for rec in ledger_rex]

        # Get the billable assignments for quarter
        asns = gbl.dataset.get_asn_data(self.quarter)

        # Get the assignments not already in the ledger
        asns = [a for a in asns if a.id not in excluded_ids]

        # Need new ledger records for assignments not already in the ledger
        new_rex = []
        for asn in asns:
            emp = gbl.dataset.get_emp_rec(asn.employee_id)
            days = self.get_total_days_asn(qtr_frum, qtr_thru, asn.frum,
                                           asn.thru)
            amt, day_total = self.calculate_cost(emp.salary, emp.fringe,
                                                 asn.effort, days)
            new_rec = Invoice({
                'id': None,
                'quarter': self.quarter,
                'dept': None,
                'admin_approved': 0,
                'va_approved': 0,
                'invoice_num': None,
                'project': asn.project,
                'employee': asn.employee,
                'effort': asn.effort,
                'salary': emp.salary,
                'fringe': emp.fringe,
                'total_day': day_total,
                'days': days,
                'amount': amt,
                'frum': asn.frum if asn.frum > qtr_frum else qtr_frum,
                'thru': asn.thru if asn.thru < qtr_thru else qtr_thru,
                'paid': 0,
                'balance': amt,
                'short_code': None,
                'grant_admin': None,
                'grant_admin_email': None,
                'asn_id': asn.id,
                'sent': 0
            })
            new_rex.append(new_rec)

        # Combine the records already in ledger with the new ones
        model = ledger_rex + new_rex
        gbl.dataset.set_unsent_invoices(model)

        # Update the view
        self.view.load_work_grid(model)
def add_invoice(form):
    cdao = ClientDAO()
    client = cdao.get(
        cdao.where('name', form['invoice_client'].split(' -- ')[0]))
    if not client:
        logging.warning('(Invoice) This client doesnt exist: ' +
                        form['invoice_client'])
        return 1, None
    client = client[0]
    profileSession = get_profile_from_session()
    if profileSession.id:
        id_profile = profileSession.id
    else:
        logging.warning('(Invoice) Session closed: ' + profileSession.id)
        return 2, None
    invoice = Invoice()
    invoice.name = form['invoice_name']
    invoice.project = form['invoice_project']
    invoice.day_rate = float(form['invoice_day_rate'])
    invoice.days = int(form['invoice_days'])
    invoice.date_sent = '/'.join(reversed(form['invoice_datesent'].split('-')))
    invoice.date_expiry = '/'.join(
        reversed(form['invoice_dateexpiry'].split('-')))
    invoice.max_delay = '/'.join(reversed(form['invoice_delay'].split('-')))
    invoice.tax = form['invoice_tax'] == 'True'
    invoice.total = (invoice.day_rate * invoice.days)
    invoice.id_client = client.id
    invoice.id_profile = id_profile
    fdao = InvoiceDAO()

    if fdao.insert(invoice):
        logging.info('add invoice %s OK', invoice.name)
        if id_profile in CACHE_INVOICE.keys():
            del CACHE_INVOICE[id_profile]
        return 3, invoice
    else:
        logging.info('add invoice %s FAILED', invoice.name)
        return 4, None