Exemplo n.º 1
0
def main():
    parser = ArgumentParser()
    parser.add_argument('--amount', type=int, help='amount')

    parser.add_argument('--type',
                        type=str,
                        default='expence',
                        help='income or expence')

    parser.add_argument('--time', type=str, default='today')

    parser.add_argument('--des', type=str, default="", help='description')
    FLAGS, unparsed = parser.parse_known_args()

    pattern = re.compile('[0-9]{2} [A-Z][a-z]{2} [0-9]{4}')
    if FLAGS.time == 'yesterday':
        time = datetime.now() - timedelta(days=1)
    if pattern.match(FLAGS.time):
        time = FLAGS.time
    else:
        time = datetime.now()

    if FLAGS.amount:
        if FLAGS.type == 'income':

            msg = "Type the income's source index (or type a new index name): "
            db = Database()
            srcs = db.get_sources()
            for src in srcs:
                msg += '\n {}. {}'.format(srcs.index(src), src)
            msg += '\n'
            src_index = input(msg)
            try:
                src = srcs[int(src_index)]
            except ValueError:
                src = src_index
            income = Income(FLAGS.amount, src, time, FLAGS.des)
            income.save()
        elif FLAGS.type == 'expence':
            msg = "Type the expence's category index (or type a new index name): "
            db = Database()
            cats = db.get_categories()
            for cat in cats:
                msg += '\n {}. {}'.format(cats.index(cat), cat)
            msg += '\n'
            cat_index = input(msg)
            try:
                cat = cats[int(cat_index)]
            except ValueError:
                cat = cat_index
            expence = Expence(FLAGS.amount, cat, time, FLAGS.des)
            expence.save()
    else:
        print("At least you must enter amount!")
Exemplo n.º 2
0
 def CreateIncome(self, amount, note, date, cat):
     """
     Insert an Income entry into the db
     """
     income = Income(amount=amount, note=note, date=date, category_id=cat)
     self.session.add(income)
     self.session.flush()
     self.session.commit()
     return income
Exemplo n.º 3
0
def income_create_alexa(amount):
    user = User.query.filter_by(id=1).first()
    amount = float(amount)
    description = "Income"
    print(user, file=sys.stderr)
    new_income_statement = Income(str(1), amount, description)
    db_session.add(new_income_statement)
    db_session.commit()
    print('Created Income Statement', file=sys.stderr)
    return '{"success": "200"}'
Exemplo n.º 4
0
def add_transfer(transfer_request: TransferRequest,
                 background_tasks: BackgroundTasks,
                 db: Session = Depends(get_db)):
    expense = Expenses()
    expense.amount = transfer_request.amount
    expense.expense_date = transfer_request.expense_date
    expense.paid_to = 'TRANSFER'
    expense.budget_entry_id = transfer_request.budget_entry_id
    expense.account_id = transfer_request.account_id

    income = Income()
    income.source = transfer_request.account_id
    income.amount = transfer_request.amount
    income.income_date = transfer_request.expense_date
    income.account_id = transfer_request.to_account_id

    db.add(expense)
    db.add(income)

    background_tasks.add_task(update_account_balance,
                              transfer_request.account_id,
                              transfer_request.amount, False, db)
    background_tasks.add_task(update_account_balance,
                              transfer_request.to_account_id,
                              transfer_request.amount, True, db)

    return {
        "code": "success",
        "message": "transfer done was added to the database"
    }
Exemplo n.º 5
0
def add_income(income_request: IncomeRequest,
               background_tasks: BackgroundTasks,
               db: Session = Depends(get_db)):
    income = Income()
    income.source = income_request.source
    income.amount = income_request.amount
    income.income_date = income_request.income_date
    income.taxes = income_request.taxes
    income.saved = income_request.saved
    # add saved account_to
    income.income_type_id = income_request.income_type_id
    income.account_id = income_request.account_id

    db.add(income)
    db.commit()

    net_income = income.amount - income.taxes - income.saved
    background_tasks.add_task(update_account_balance, income.account_id,
                              net_income, True, db)

    return {"code": "success", "message": "income was added to the database"}
Exemplo n.º 6
0
def IncomeView(request):
    if request.method == 'POST':
        form = IncomeForm(request.POST)
        if form.validate():
            dataFromForm = {}
            for field in form:
                dataFromForm[field.name] = field._value()
            newRecord = Income(**dataFromForm)
            session.add(newRecord)
            session.commit()


#            return HttpResponseRedirect('cache/inc.html') # show saved record
    else:
        form = IncomeForm()
    return render(request, 'cache/inpt.html', {'form': form})
Exemplo n.º 7
0
def initialize():
    db.drop_all()
    db.metadata.create_all(db.engine,
                           tables=[
                               Person.__table__, Address.__table__,
                               Income.__table__, Patrimony.__table__
                           ])

    list_persons = []
    list_incomes = []
    list_address = []
    list_patrimony = []
    for person_info in persons:
        person = Person(cpf=person_info.get('cpf'),
                        nome=person_info.get('nome'))

        address = Address(rua=person_info['endereco']['rua'],
                          numero=person_info['endereco']['numero'],
                          cidade=person_info['endereco']['cidade'],
                          estado=person_info['endereco']['estado'],
                          person_id=person_info.get('cpf'))

        list_address.append(address)
        list_persons.append(person)

        for income_info in person_info.get('fonte_renda'):
            income = Income(tipo=income_info.get('tipo'),
                            valor=income_info.get('valor'),
                            person_id=person_info.get('cpf'))
            list_incomes.append(income)

        for patrimony_info in person_info.get('lista_bens'):
            patrimony = Patrimony(tipo=patrimony_info.get('tipo'),
                                  valor=patrimony_info.get('valor'),
                                  person_id=person_info.get('cpf'))
            list_patrimony.append(patrimony)
    db.session.add_all(list_persons)
    db.session.add_all(list_incomes)
    db.session.add_all(list_address)
    db.session.add_all(list_patrimony)
    db.session.commit()
Exemplo n.º 8
0
def income_create():
    try:
        csrf = session.get('csrf', {})
        uid = csrf[csrf.index(":") + 2:len(csrf) - 1]
        print(uid, file=sys.stderr)
        if len(csrf) == 0:
            return render_template("index.html")
        else:
            user = User.query.filter_by(id=uid).first()
            amount = float(request.form["amount"])
            description = "Income"
            print(user, file=sys.stderr)
            new_income_statement = Income(str(user.id), amount, description)
            db_session.add(new_income_statement)
            db_session.commit()
            print('Created Income Statement', file=sys.stderr)
            return redirect(url_for('.home_page'))
    except:
        print("ERROR OCCURED", file=sys.stderr)
        session.pop('csrf', None)
        return render_template("index.html")
Exemplo n.º 9
0
def isoS():

    if request.method == 'POST':

        monsel, oder, peep, serv, invo, inco, cache, modata, modlink, fdata, invooder = init_storage_zero(
        )
        invojo, filesel, docref, search11, search12, search21, search31 = init_storage_blank(
        )
        leftscreen = 1
        docref = ' '
        err = ['All is well', ' ', ' ', ' ', ' ']
        ldata = None
        #today = datetime.datetime.today().strftime('%Y-%m-%d')
        today = datetime.date.today()
        invodate = datetime.date.today()
        leftsize = 10
        monvec = [
            'Month', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
            'Sep', 'Oct', 'Nov', 'Dec'
        ]
        monlvec = [
            'January', 'February', 'March', 'April', 'May', 'June', 'July',
            'August', 'September', 'October', 'November', 'December'
        ]

        match = request.values.get('Match')
        modify = request.values.get('Modify')
        vmod = request.values.get('Vmod')
        minvo = request.values.get('MakeI')
        mpack = request.values.get('MakeP')
        viewo = request.values.get('ViewO')
        viewi = request.values.get('ViewI')
        viewp = request.values.get('ViewP')
        analyze = request.values.get('Analyze')
        print = request.values.get('Print')
        addE = request.values.get('addentity')
        addS = request.values.get('addservice')
        recpay = request.values.get('RecPay')
        hispay = request.values.get('HisPay')
        monsel = request.values.get('monsel')

        returnhit = request.values.get('Return')
        deletehit = request.values.get('Delete')
        # hidden values
        update = request.values.get('Update')
        invoupdate = request.values.get('invoUpdate')
        recupdate = request.values.get('recUpdate')
        modlink = request.values.get('passmodlink')
        emailnow = request.values.get('emailnow')
        emailinvo = request.values.get('emailInvo')
        newjob = request.values.get('NewJ')
        thisjob = request.values.get('ThisJob')

        oder = request.values.get('oder')
        invo = request.values.get('invo')
        invooder = request.values.get('invooder')
        cache = request.values.get('cache')
        peep = request.values.get('peep')
        serv = request.values.get('serv')
        inco = request.values.get('inco')

        modlink = nonone(modlink)
        oder = nonone(oder)
        invo = nonone(invo)
        invooder = nonone(invooder)
        peep = nonone(peep)
        serv = nonone(serv)
        monsel = nonone(monsel)
        inco = nonone(inco)
        modal = 0

        if returnhit is not None:
            modlink = 0
            invo = 0
            invooder = 0
            inco = 0
# ____________________________________________________________________________________________________________________B.UpdateDatabases.Storage
        if update is not None and modlink == 1:
            if oder > 0:
                modata = Storage.query.get(oder)
                desc = request.values.get('desc')
                amount = request.values.get('amount')
                thiscomp = request.values.get('thiscomp')
                dstart = request.values.get('dstart')
                balfwd = request.values.get('pybal')
                modata.Description = desc
                modata.Amount = amount
                modata.Date = dstart
                modata.BalFwd = balfwd
                ldat = People.query.filter(People.Company == thiscomp).first()
                if ldat is not None:
                    acomp = ldat.Company
                    aid = ldat.id
                else:
                    acomp = None
                    aid = None
                modata.Company = acomp
                modata.Pid = aid
                modata.Label = modata.Jo + ' ' + thiscomp + ' ' + amount
                db.session.commit()
                err[3] = 'Modification to Storage JO ' + modata.Jo + ' completed.'
                modlink = 0
            if peep > 0:
                modata = People.query.get(peep)
                modata.Ptype = 'Storage'
                vals = [
                    'company', 'fname', 'mnames', 'lname', 'addr1', 'addr2',
                    'addr3', 'idtype', 'tid', 'tel', 'email', 'assoc1',
                    'assoc2', 'date1'
                ]
                a = list(range(len(vals)))
                i = 0
                for v in vals:
                    a[i] = request.values.get(v)
                    i = i + 1
                modata.Company = a[0]
                modata.First = a[1]
                modata.Middle = a[2]
                modata.Last = a[3]
                modata.Addr1 = a[4]
                modata.Addr2 = a[5]
                modata.Addr3 = a[6]
                modata.Idtype = a[7]
                modata.Idnumber = a[8]
                modata.Telephone = a[9]
                modata.Email = a[10]
                modata.Associate1 = a[11]
                modata.Associate2 = a[12]
                modata.Date1 = a[13]
                db.session.commit()
                err = [
                    ' ', ' ', 'Modification to Entity ID ' + str(modata.id) +
                    ' completed.', ' ', ' '
                ]
                modlink = 0
                # And now update the crossover to Storage in case the Company info changed:
                cross = Storage.query.filter(Storage.Pid == peep)
                for cros in cross:
                    cros.Company = a[0]
                db.session.commit()

            if serv > 0:
                modata = Services.query.get(serv)
                vals = ['service', 'price']
                a = list(range(len(vals)))
                i = 0
                for v in vals:
                    a[i] = request.values.get(v)
                    i = i + 1
                modata.Service = a[0]
                modata.Price = a[1]
                db.session.commit()
                err = [
                    ' ', ' ', 'Modification to Services Data with ID ' +
                    str(modata.id) + ' completed.', ' ', ' '
                ]
                modlink = 0

            if inco > 0:
                modata = Income.query.get(inco)
                vals = ['desc', 'recamount', 'custref', 'recdate']
                i = 0
                for v in vals:
                    a[i] = request.values.get(v)
                    i = i + 1
                modata.Description = a[0]
                modata.Amount = a[1]
                modata.Ref = a[2]
                modata.Date = a[3]
                db.session.commit()
                err = [
                    ' ', ' ', 'Modification to Income Data with ID ' +
                    str(modata.id) + ' completed.', ' ', ' '
                ]
# ____________________________________________________________________________________________________________________E.UpdateDatabases.Storage
# ____________________________________________________________________________________________________________________B.UpdateInvoice.Storage
        if invoupdate is not None and monsel != 0:
            leftsize = 8
            odata1 = Storage.query.get(invooder)
            invojo = popjo(invooder, monsel)
            ldata = Invoices.query.filter(Invoices.SubJo == invojo).all()
            invodate = request.values.get('invodate')
            total = 0
            for data in ldata:
                iqty = request.values.get('qty' + str(data.id))
                iqty = nononef(iqty)
                data.Description = request.values.get('desc' + str(data.id))
                deach = request.values.get('cost' + str(data.id))
                if deach is not None:
                    deach = "{:.2f}".format(float(deach))
                    amount = iqty * float(deach)
                else:
                    deach = "{:.2f}".format(0.00)
                    amount = 0.00
                total = total + amount
                amount = "{:.2f}".format(amount)
                data.Qty = iqty
                data.Ea = deach
                data.Amount = amount
                data.Total = 0.00
                data.Date = invodate
                db.session.commit()

            if total > 0 and ldata is not None:
                for data in ldata:
                    data.Total = "%0.2f" % total
                    db.session.commit()
                odata1.Amount = "%0.2f" % total
                db.session.commit()

            #Remove zeros from invoice in case a zero was the mod
            Invoices.query.filter(Invoices.Qty == 0).delete()
            db.session.commit()

            #Create invoice code for order
            err = [
                ' ', ' ', 'Invoice created for Storage JO: ' + invojo, ' ', ' '
            ]
            ldata = Invoices.query.filter(Invoices.SubJo == invojo).all()
# ____________________________________________________________________________________________________________________E.UpdateInvoice.Storage

        odata = Storage.query.order_by(Storage.Jo).all()
        cdata = People.query.filter(People.Ptype == 'Storage').order_by(
            People.Company).all()
        sdata = Services.query.all()

        oder, peep, serv, numchecked = numcheck(3, odata, cdata, sdata, 0, 0,
                                                ['oder', 'peep', 'serv'])

        # ____________________________________________________________________________________________________________________E.SearchFilters.Storage

        # ____________________________________________________________________________________________________________________B.EmailInvoice.Storage
        if emailinvo is not None:
            leftsize = 10
            leftscreen = 1
            modlink = 0
            modata = Storage.query.get(invooder)
            invojo = popjo(invooder, monsel)
            ldata = Invoices.query.filter(Invoices.SubJo == invojo).order_by(
                Invoices.Ea.desc()).all()
            pdata1 = People.query.filter(People.id == modata.Pid).first()
            ldat = Invoices.query.filter(Invoices.SubJo == invojo).first()
            if pdata1 is None:
                err = [
                    ' ', ' ',
                    'There is no Billing information for this selection', ' ',
                    ' '
                ]
            else:
                email = pdata1.Email
                company = pdata1.Company
            docref = ldat.Original
            if 'vinvoice' not in docref:
                err = [
                    ' ', ' ',
                    'There is no document available for this selection', ' ',
                    ' '
                ]
            else:
                if email is not None:
                    import invoice_mimemail_S
                    invoice_mimemail_S.main(invojo, docref, email, monsel,
                                            inco, company)
                    if inco == 0:
                        for data in ldata:
                            data.Status = "E"
                            db.session.commit()
                    else:
                        for data in ldata:
                            data.Status = "P"
                            db.session.commit()
            invooder = 0
            invo = 0
            inco = 0

# ____________________________________________________________________________________________________________________E.EmailInvoice.Storage
# ____________________________________________________________________________________________________________________B.Viewers.Storage
        if viewo is not None and numchecked == 1:
            err = [
                ' ', ' ', 'There is no document available for this selection',
                ' ', ' '
            ]
            if oder > 0:
                modata = Storage.query.get(oder)
                if modata.Original is not None:
                    if len(modata.Original) > 5:
                        docref = modata.Original
                        leftscreen = 0
                        leftsize = 8
                        modlink = 0
                        err = [
                            ' ', ' ', 'Viewing document ' + docref, ' ', ' '
                        ]

        if (viewo is not None or viewi is not None
                or viewp is not None) and numchecked != 1:
            err = [
                'Must check exactly one box to use this option', ' ', ' ', ' ',
                ' '
            ]

        if viewi is not None and numchecked == 1:
            err = [
                'There is no document available for this selection', ' ', ' ',
                ' ', ' '
            ]
            if monsel == 0:
                err[1] = 'Need to select the month'
            if oder > 0 and monsel > 0:
                invooder = oder
                modata = Storage.query.get(oder)
                invojo = popjo(oder, monsel)
                ldat = Invoices.query.filter(Invoices.SubJo == invojo).first()
                if ldat.Original is not None:
                    docref = ldat.Original
                    leftscreen = 0
                    leftsize = 8
                    modlink = 5
                    err = [' ', ' ', 'Viewing document ' + docref, ' ', ' ']
# ____________________________________________________________________________________________________________________E.Viewers.Storage
# ____________________________________________________________________________________________________________________B.ModifyEntries.Storage
        if (modify is not None or vmod is not None) and numchecked == 1:
            modlink = 1
            leftsize = 8

            if oder > 0:
                modata = Storage.query.get(oder)
                if vmod is not None:
                    err = [
                        ' ', ' ',
                        'There is no document available for this selection',
                        ' ', ' '
                    ]
                    if modata.Original is not None:
                        if len(modata.Original) > 5:
                            leftscreen = 0
                            docref = modata.Original
                            err = ['All is well', ' ', ' ', ' ', ' ']

            if serv > 0:
                modata = Services.query.get(serv)
                if vmod is not None:
                    err = [
                        ' ', ' ',
                        'There is no document available for this selection',
                        ' ', ' '
                    ]

            if peep > 0:
                modata = People.query.get(peep)
                if vmod is not None:
                    err = [
                        ' ', ' ',
                        'There is no document available for this selection',
                        ' ', ' '
                    ]

        if (modify is not None or vmod is not None) and numchecked != 1:
            modlink = 0
            err[0] = ' '
            err[2] = 'Must check exactly one box to use this option'
# ____________________________________________________________________________________________________________________E.ModifyEntries.Storage
# ____________________________________________________________________________________________________________________B.AddEntries.Storage

        if addS is not None and serv > 0 and numchecked == 1:
            leftsize = 8
            modlink = 2
            modata = Services.query.get(serv)

        if addS is not None and numchecked == 0:
            leftsize = 8
            modlink = 1
            #We will create a blank line and simply modify that by updating:
            input = Services(Service='New', Price=0.00)
            db.session.add(input)
            db.session.commit()
            modata = Services.query.filter(Services.Service == 'New').first()
            serv = modata.id
            err = [' ', ' ', 'Enter Data for New Service', ' ', ' ']

        if addS is not None and numchecked > 1:
            modlink = 0
            err[0] = ' '
            err[2] = 'Must check exactly one box to use this option'

        if addE is not None and peep > 0 and numchecked == 1:
            leftsize = 8
            modlink = 3
            modata = People.query.get(peep)

        if addE is not None and numchecked == 0:
            leftsize = 8
            modlink = 1
            #We will create a blank line and simply modify that by updating:
            input = People(Company='New',
                           First='',
                           Middle='',
                           Last='',
                           Addr1='',
                           Addr2='',
                           Addr3='',
                           Idtype='',
                           Idnumber='',
                           Telephone='',
                           Email='',
                           Associate1='',
                           Associate2='',
                           Date1=today,
                           Date2=None,
                           Original=None,
                           Ptype='Storage',
                           Temp1=None,
                           Temp2=None)
            db.session.add(input)
            db.session.commit()
            modata = People.query.filter((People.Company == 'New') &
                                         (People.Ptype == 'Storage')).first()
            peep = modata.id
            modata.Company = ''
            db.session.commit()
            modata = People.query.get(peep)
            err = [' ', ' ', 'Enter Data for New Company', ' ', ' ']

        if addE is not None and numchecked > 1:
            modlink = 0
            err[0] = ' '
            err[2] = 'Must check exactly one box to use this option'
# ____________________________________________________________________________________________________________________E.AddEntries.Storage
# ____________________________________________________________________________________________________________________B.ReceivePayment.Storage

        if (recpay is not None and oder > 0 and numchecked == 1
                and monsel > 0) or recupdate is not None:
            leftsize = 8
            if recpay is not None:
                invooder = oder
            odat = Storage.query.get(invooder)
            invojo = popjo(invooder, monsel)
            ldat = Invoices.query.filter(Invoices.SubJo == invojo).first()
            err = ['Have no Invoice to Receive Against', ' ', ' ', ' ', ' ']
            if ldat is not None:
                invodate = ldat.Date
                if ldat.Original is not None:
                    docref = ldat.Original
                    leftscreen = 0
                    leftsize = 8

                incdat = Income.query.filter(Income.SubJo == invojo).first()
                if incdat is None:
                    err = ['Creating New Payment on SubJo', ' ', ' ', ' ', ' ']
                    paydesc = 'Received payment on Invoice ' + invojo + ' for month of ' + monvec[
                        monsel]
                    recamount = str(ldat.Amount)
                    custref = 'ChkNo'
                    recdate = datetime.date(today.year, monsel, 28)
                    input = Income(Jo=odat.Jo,
                                   SubJo=invojo,
                                   Pid=odat.Pid,
                                   Description=paydesc,
                                   Amount=recamount,
                                   Ref=custref,
                                   Date=recdate,
                                   Original=None)
                    db.session.add(input)
                    payment = 0
                else:
                    recamount = request.values.get('recamount')
                    custref = request.values.get('custref')
                    desc = request.values.get('desc')
                    recdate = request.values.get('recdate')
                    incdat.Amount = recamount
                    incdat.Ref = custref
                    incdat.Description = desc
                    incdat.Date = recdate
                db.session.commit()
                payment = [recamount, custref, recdate]

                modata = Income.query.filter(Income.SubJo == invojo).first()
                inco = modata.id
                err = [' ', ' ', 'Amend Payment for Invoice', ' ', ' ']

                ldata = Invoices.query.filter(
                    Invoices.SubJo == invojo).order_by(
                        Invoices.Ea.desc()).all()
                pdata1 = People.query.filter(People.id == odat.Pid).first()
                cache = nonone(odat.Cache) + 1

                basejo = odat.Jo
                involine, paidline, refline, balline = money12(basejo)

                balduenow = balline[monsel]
                try:
                    balduenow = float[balduenow]
                except:
                    balduenow = 0.00
                if balduenow < .001:
                    for data in ldata:
                        data.Status = "P"
                        db.session.commit()

                import make_S_invoice
                make_S_invoice.main(odat, ldata, pdata1, invojo, involine,
                                    paidline, refline, balline, invodate,
                                    cache, payment)

                if cache > 1:
                    docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + 'c' + str(
                        cache) + '.pdf'
                    # Store for future use
                else:
                    docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + '.pdf'

                odat.Cache = cache
                idat = Invoices.query.filter(Invoices.SubJo == invojo).first()
                idat.Original = docref
                db.session.commit()
                leftscreen = 0
                err[4] = 'Viewing ' + docref

        if recpay is not None and (oder == 0 or numchecked != 1
                                   or monsel == 0):
            err = ['Invalid selections:', '', '', '', '']
            if oder == 0:
                err[1] = 'Must select a Storage Job'
            if numchecked != 1:
                err[2] = 'Must select exactly one Storage Job'
            if monsel == 0:
                err[3] = 'Must select a month to apply payment'
# ____________________________________________________________________________________________________________________E.ReceivePayment.Storage
# ____________________________________________________________________________________________________________________B.PaymentHistory.Storage
        if hispay is not None or modlink == 7:
            if oder == 0 and invooder == 0:
                err[1] = 'Must select a Storage Job'
            else:
                if oder != 0:
                    invooder = oder
                modata = Storage.query.get(invooder)
                ldata = Invoices.query.filter(
                    Invoices.Jo == modata.Jo).order_by(Invoices.SubJo).all()
                fdata = Income.query.filter(Income.Jo == modata.Jo).order_by(
                    Income.SubJo).all()
                #Check to see if we need to delete anything from history
                killthis = request.values.get('killthis')
                if killthis is not None and modlink == 7:
                    for data in ldata:
                        testone = request.values.get('bill' + str(data.id))
                        if testone:
                            kill = int(testone)
                            Invoices.query.filter(Invoices.id == kill).delete()
                            db.session.commit()
                    for data in fdata:
                        testone = request.values.get('pay' + str(data.id))
                        if testone:
                            kill = int(testone)
                            Income.query.filter(Income.id == kill).delete()
                            db.session.commit()
                    ldata = Invoices.query.filter(
                        Invoices.Jo == modata.Jo).order_by(
                            Invoices.SubJo).all()
                    fdata = Income.query.filter(
                        Income.Jo == modata.Jo).order_by(Income.SubJo).all()

                leftsize = 8
                modlink = 7
# ____________________________________________________________________________________________________________________E.PaymentHistory.Storage
# ____________________________________________________________________________________________________________________B.Delete.Storage
        if deletehit is not None and numchecked == 1:
            if oder > 0:
                Storage.query.filter(Storage.id == oder).delete()
                odata = Storage.query.all()
            if peep > 0:
                People.query.filter(People.id == peep).delete()
                cdata = People.query.filter(
                    People.Ptype == 'Storage').order_by(People.Company).all()
            if serv > 0:
                Services.query.filter(Services.id == serv).delete()
                sdata = Services.query.all()
            db.session.commit()
        if deletehit is not None and numchecked != 1:
            err = [
                ' ', ' ',
                'Must have exactly one item checked to use this option', ' ',
                ' '
            ]
# ____________________________________________________________________________________________________________________E.Delete.Storage
# ____________________________________________________________________________________________________________________B.Invoicing.Storage
        if ((minvo is not None and oder > 0)
                or invoupdate is not None) and monsel > 0:
            err = ['Could not create invoice', ' ', ' ', ' ', ' ']
            # First time through: have an order to invoice
            if oder > 0:
                invooder = oder
            myo = Storage.query.get(invooder)
            fee = myo.Amount
            #Check to see if we have the required data to make an invoice:
            invojo = popjo(invooder, monsel)
            thismonth = calendar.month_name[monsel]
            invodate = request.values.get('invodate')

            invo = 1
            leftsize = 8
            cache = nonone(myo.Cache) + 1
            mys = Services.query.get(serv)
            if mys is not None:
                addserv = mys.Service
                price = mys.Price
                qty = 1
                d = datetime.date(today.year, monsel, 1)
                descript = 'Monthly Storage Fee for Month of ' + thismonth
                input = Invoices(Jo=myo.Jo,
                                 SubJo=invojo,
                                 Pid=myo.Pid,
                                 Service=addserv,
                                 Description=descript,
                                 Ea=price,
                                 Qty=qty,
                                 Amount=price,
                                 Total=price,
                                 Date=d,
                                 Original=None,
                                 Status='New')
                db.session.add(input)
                db.session.commit()

            ldata = Invoices.query.filter(Invoices.SubJo == invojo).first()
            if ldata is None:
                invodate = datetime.date(today.year, monsel, 1)
                #See if there is an invoice from previous month to copy from
                try:
                    invojoprev = popjo(invooder, monsel - 1)
                    invodate = datetime.date(today.year, monsel, 1)
                    ldata2 = Invoices.query.filter(
                        Invoices.SubJo == invojoprev).all()
                    for data in ldata2:
                        mydescript = data.Description
                        newdescript = data.Description
                        for i in range(12):
                            if monlvec[i] in newdescript:
                                j = i + 1
                                if j == 12:
                                    j = 0
                                mydescript = newdescript.replace(
                                    monlvec[i], monlvec[j])

                        input = Invoices(Jo=myo.Jo,
                                         SubJo=invojo,
                                         Pid=myo.Pid,
                                         Service=data.Service,
                                         Description=mydescript,
                                         Ea=data.Ea,
                                         Qty=data.Qty,
                                         Amount=data.Amount,
                                         Date=invodate,
                                         Total=data.Total,
                                         Original=None,
                                         Status='New')
                        db.session.add(input)
                        db.session.commit()
                except:
                    if mys is None:
                        addserv = 'Monthly Storage'
                        price = fee
                    else:
                        addserv = mys.Service
                        price = mys.Price

                    qty = 1
                    invodate = datetime.date(today.year, monsel, 1)
                    descript = 'Monthly Storage Fee for Month of ' + thismonth
                    input = Invoices(Jo=myo.Jo,
                                     SubJo=invojo,
                                     Pid=myo.Pid,
                                     Service=addserv,
                                     Description=descript,
                                     Ea=price,
                                     Qty=qty,
                                     Amount=price,
                                     Date=invodate,
                                     Total=price,
                                     Original=None,
                                     Status='New')
                    db.session.add(input)
                    db.session.commit()
                else:
                    ldat = Invoices.query.filter(
                        Invoices.SubJo == invojo).first()
                    if ldat is None:
                        if mys is None:
                            addserv = 'Monthly Storage'
                            price = fee
                        else:
                            addserv = mys.Service
                            price = mys.Price

                        qty = 1
                        invodate = datetime.date(today.year, monsel, 1)
                        descript = 'Monthly Storage Fee for Month of ' + thismonth
                        input = Invoices(Jo=myo.Jo,
                                         SubJo=invojo,
                                         Pid=myo.Pid,
                                         Service=addserv,
                                         Description=descript,
                                         Ea=price,
                                         Qty=qty,
                                         Amount=price,
                                         Date=invodate,
                                         Total=price,
                                         Original=None,
                                         Status='New')
                        db.session.add(input)
                        db.session.commit()
                    ldat = Invoices.query.filter(
                        Invoices.SubJo == invojo).first()
                    invodate = ldat.Date

            # If have ldata:
            err = [' ', ' ', 'Created invoice for JO= ' + invojo, ' ', ' ']

            ldata = Invoices.query.filter(Invoices.SubJo == invojo).order_by(
                Invoices.Ea.desc()).all()
            pdata1 = People.query.filter(People.id == myo.Pid).first()

            odat = Storage.query.get(invooder)
            basejo = odat.Jo
            involine, paidline, refline, balline = money12(basejo)

            import make_S_invoice
            make_S_invoice.main(odat, ldata, pdata1, invojo, involine,
                                paidline, refline, balline, invodate, cache, 0)

            if cache > 1:
                docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + 'c' + str(
                    cache) + '.pdf'
                # Store for future use
            else:
                docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + '.pdf'

            odat.Path = docref
            odat.Cache = cache
            idat = Invoices.query.filter(Invoices.SubJo == invojo).first()
            idat.Original = docref
            db.session.commit()
            leftscreen = 0
            err[4] = 'Viewing ' + docref
            modata = Storage.query.get(invooder)
        elif minvo is not None and monsel == 0:
            err = [' ', ' ', 'Choose a Month for the Invoice', ' ', ' ']
        elif minvo is not None:
            err = [
                ' ', ' ', 'Must select at least 1 Job for this selection', ' ',
                ' '
            ]
# ____________________________________________________________________________________________________________________E.Invoicing.Storage

# ____________________________________________________________________________________________________________________B.NewJob.Storage
        if newjob is not None:
            err = ['Select Source Document from List']
            fdata = myoslist(f'tmp/{scac}/data/vunknown')
            modlink = 4
            leftsize = 8
            leftscreen = 0
            docref = f'tmp/{scac}/data/vunknown/NewJob.pdf'

        if newjob is None and modlink == 4:
            filesel = request.values.get('FileSel')
            if filesel != '1':
                fdata = myoslist(f'tmp/{scac}/data/vunknown')
                leftsize = 8
                leftscreen = 0
                docref = f'tmp/{scac}/data/vunknown/' + filesel

        if thisjob is not None:
            modlink = 0
            #Create the new database entry for the source document
            filesel = request.values.get('FileSel')
            if filesel != '1':
                docold = f'tmp/{scac}/data/vunknown/' + filesel
                docref = f'tmp/{scac}/data/vorders/' + filesel
                shutil.move(addpath(docold), addpath(docref))
            else:
                docref = ''
            sdate = request.values.get('dstart')
            if sdate is None:
                sdate = today

            jtype = 'S'
            nextjo = newjo(jtype, sdate)

            thisdesc = request.values.get('thisdesc')
            thisamt = request.values.get('thisamt')
            thiscomp = request.values.get('thiscomp')
            pybal = request.values.get('pybal')
            ldat = People.query.filter(People.Company == thiscomp).first()
            if ldat is not None:
                acomp = ldat.Company
                aid = ldat.id
            else:
                acomp = None
                aid = None
            label = nextjo + ' ' + thiscomp + ' ' + thisamt
            input = Storage(Jo=nextjo,
                            Description=thisdesc,
                            BalFwd=pybal,
                            Amount=thisamt,
                            Status='New',
                            Cache=1,
                            Original=docref,
                            Path=None,
                            Pid=aid,
                            Company=thiscomp,
                            Date=sdate,
                            Label=label)

            db.session.add(input)
            db.session.commit()
            modata = Storage.query.filter(Storage.Jo == nextjo).first()
            csize = People.query.filter(People.Ptype == 'Storage').order_by(
                People.Company).all()
            oder = modata.id
            leftscreen = 1
            err = ['All is well', ' ', ' ', ' ', ' ']
            odata = Storage.query.all()
# ____________________________________________________________________________________________________________________E.New Job.Storage
# ____________________________________________________________________________________________________________________B.Matching.Storage
        if match is not None:
            if oder > 0 and peep > 0 and numchecked == 2:
                myo = Storage.query.get(oder)
                myp = People.query.get(peep)
                myo.Pid = peep
                myo.Company = myp.Company
                db.session.commit()
            if numchecked != 2:
                err[1] = 'Must select exactly 2 boxes to use this option.'
                err[0] = ' '
# ____________________________________________________________________________________________________________________E.Matching.Storage

# Create the time oriented data for the columns
        bm, cm = timedata(odata)
    #This is the else for 1st time through
    else:
        # ____________________________________________________________________________________________________________________B.STORAGEnotPost

        odata = Storage.query.order_by(Storage.Jo).all()
        cdata = People.query.filter(People.Ptype == 'Storage').order_by(
            People.Company).all()
        sdata = Services.query.all()
        ldata = None
        today = datetime.datetime.today().strftime('%Y-%m-%d')
        invodate = today
        monsel, oder, peep, serv, invo, inco, cache, modata, modlink, fdata, invooder = init_storage_zero(
        )
        invojo, filesel, docref, search11, search12, search21, search31 = init_storage_blank(
        )
        monvec = [
            'All', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
            'Sep', 'Oct', 'Nov', 'Dec'
        ]
        leftscreen = 1
        leftsize = 10
        docref = ' '
        err = ['All is well', ' ', ' ', ' ', ' ']
        bm, cm = timedata(odata)
    docref = docref.replace('tmp/vinvoice', f'tmp/{scac}/data/vinvoice')
    return odata, cdata, sdata, oder, peep, serv, err, modata, modlink, fdata, today, inco, leftscreen, docref, leftsize, ldata, monsel, monvec, invo, invooder, invojo, cache, filesel, bm, cm, invodate
Exemplo n.º 10
0
from models import Asset, Outcome, Income

from finance_manager import FinanceManager
from data import asset_data, outcome_data, income_data

assets = [Asset(**item) for item in asset_data]
outcomes = [Outcome(**item) for item in outcome_data]

incomes = [Income(**item) for item in income_data]

FinanceManager.commit(incomes)
# FinanceManager.commit(assets)
# FinanceManager.commit(outcomes)
Exemplo n.º 11
0
def isoH():

    if request.method == 'POST':
        username = session['username'].capitalize()
        from viewfuncs import d2s, newjo, popjo, jovec, timedata, nonone, nononef, GetCo, init_horizon_zero, numcheck, sdiff, calendar7_weeks, GetCo3
        cars, auto, peep, invo, cache, modata, modlink, invooder, stamp, fdata, csize, invodate, inco, cdat, pb, passdata, vdata, caldays, daylist, weeksum, nweeks = init_horizon_zero(
        )
        filesel = ''
        docref = ''
        doctxt = ''
        displdata = 0
        err = ['All is well', ' ', ' ', ' ', ' ']

        # ____________________________________________________________________________________________________________________B.FormVariables.Dealer
        leftsize = 10
        today = datetime.date.today()
        jobdate = datetime.date.today()

        match = request.values.get('Match')
        modify = request.values.get('Modify')
        vmod = request.values.get('Vmod')
        minvo = request.values.get('MakeI')
        mbill = request.values.get('MakeB')
        viewo = request.values.get('ViewO')
        viewi = request.values.get('ViewI')
        addE = request.values.get('addentity')
        addA = request.values.get('addauto')
        returnhit = request.values.get('Return')
        deletehit = request.values.get('Delete')
        datatable1 = request.values.get('datatable1')
        datatable2 = request.values.get('datatable2')
        datatable3 = request.values.get('datatable3')
        dlist = [datatable1, datatable2, datatable3]

        # hidden values
        update = request.values.get('Update')
        invoupdate = request.values.get('invoUpdate')
        modlink = request.values.get('passmodlink')
        emailnow = request.values.get('emailnow')
        emailinvo = request.values.get('emailInvo')
        newjob = request.values.get('NewJ')
        thisjob = request.values.get('ThisJob')
        recpay = request.values.get('RecPay')
        hispay = request.values.get('HisPay')
        recupdate = request.values.get('recUpdate')

        calendar = request.values.get('Calendar')
        calupdate = request.values.get('calupdate')

        cars = request.values.get('cars')
        peep = request.values.get('peep')
        auto = request.values.get('auto')

        invo = request.values.get('invo')
        invooder = request.values.get('invooder')
        cache = request.values.get('cache')

        modata = 0
        idata = 0
        leftscreen = 1
        docref = ''
        ldata = None

        modlink = nonone(modlink)
        cars = nonone(cars)
        peep = nonone(peep)
        auto = nonone(auto)

        invo = nonone(invo)
        invooder = nonone(invooder)
        cache = nonone(cache)

        if returnhit is not None:
            modlink = 0
            invooder = 0
            cars = 0
            invo = 0

# ____________________________________________________________________________________________________________________E.FormVariables.Dealer
# ____________________________________________________________________________________________________________________B.DataModifications.Dealer

        if update is not None and modlink == 2:
            modata = People.query.get(peep)
            vals = [
                'company', 'fname', 'mnames', 'lname', 'addr1', 'addr2',
                'addr3', 'idtype', 'tid', 'tel', 'email', 'assoc1', 'assoc2',
                'date1', 'ptype'
            ]
            a = list(range(len(vals)))
            i = 0
            for v in vals:
                a[i] = request.values.get(v)
                i = i + 1

            try:
                sdate1dt = datetime.datetime.strptime(a[13], "%Y-%m-%d")
            except:
                a[13] = datetime.datetime.today().strftime('%Y-%m-%d')

            input = People(Company=a[0],
                           First=a[1],
                           Middle=a[2],
                           Last=a[3],
                           Addr1=a[4],
                           Addr2=a[5],
                           Addr3=a[6],
                           Idtype=a[7],
                           Idnumber=a[8],
                           Telephone=a[9],
                           Email=a[10],
                           Associate1=a[11],
                           Associate2=a[12],
                           Date1=a[13],
                           Ptype=a[14],
                           Date2=None,
                           Original=None,
                           Temp1=None,
                           Temp2=None)
            db.session.add(input)
            db.session.commit()
            err = [' ', ' ', 'New Entity Added to Database.', ' ', ' ']
            modlink = 0

        if (update is not None and modlink == 1) or (update is not None
                                                     and modlink == 10):
            if cars > 0:
                modata = Dealer.query.get(cars)
                vals = [
                    'cost', 'sale', 'bfee', 'tow', 'repair', 'oitem', 'ocost',
                    'modelyear', 'make', 'model', 'color', 'vin', 'dfee',
                    'thiscompany'
                ]
                a = list(range(len(vals)))
                i = 0
                for v in vals:
                    a[i] = request.values.get(v)
                    i = i + 1
                modata.Cost = a[0]
                modata.Sale = a[1]
                modata.Bfee = a[2]
                modata.Tow = a[3]
                modata.Repair = a[4]
                modata.Oitem = a[5]
                modata.Ocost = a[6]
                modata.Year = a[7]
                modata.Make = a[8]
                modata.Model = a[9]
                modata.Color = a[10]
                modata.Vin = a[11]
                modata.DocumentFee = a[12]
                modata.Company = a[13]
                pdat = People.query.filter(People.Company == a[13]).first()
                if pdat is not None:
                    modata.Pid = pdat.id
                try:
                    modata.Label = modata.Jo + ' ' + a[13]
                except:
                    err[4] = 'Cannot create Label with missing information (company, Year, Make, Model)'
                db.session.commit()
                err = [
                    ' ', ' ', 'Modification to Auto Sale JO ' + modata.Jo +
                    ' completed.', ' ', ' '
                ]
                modlink = 0

            if peep > 0:
                modata = People.query.get(peep)
                vals = [
                    'company', 'fname', 'mnames', 'lname', 'addr1', 'addr2',
                    'addr3', 'idtype', 'tid', 'tel', 'email', 'assoc1',
                    'assoc2', 'date1', 'role'
                ]
                a = list(range(len(vals)))
                i = 0
                for v in vals:
                    a[i] = request.values.get(v)
                    i = i + 1

                modata.First = a[1]
                modata.Middle = a[2]
                modata.Last = a[3]
                modata.Addr1 = a[4]
                modata.Addr2 = a[5]
                modata.Addr3 = a[6]
                modata.Idtype = a[7]
                modata.Idnumber = a[8]
                modata.Telephone = a[9]
                modata.Email = a[10]
                modata.Associate1 = a[11]
                modata.Associate2 = a[12]
                modata.Date1 = a[13]
                modata.Ptype = a[14]
                #Need to infuse change into Autos if it is a Tow Company:
                if modata.Ptype == 'TowCo' or a[14] == 'TowCo':
                    adat = Autos.query.filter(
                        Autos.TowCompany == modata.Company).first()
                    if adat is not None:
                        adat.TowCompany = a[0]

                modata.Company = a[0]

                db.session.commit()
                err = [
                    ' ', ' ', 'Modification to Entity ID ' + str(modata.id) +
                    ' completed.', ' ', ' '
                ]
                modlink = 0

            if auto > 0 or modlink == 10:

                if modlink == 10:
                    filesel = request.values.get('FileSel')
                    if filesel != '1':
                        oldref = f'tmp/{scac}/data/vunknown/' + filesel
                        oldtxt = oldref.split('.', 1)[0] + '.txt'
                    else:
                        oldref = ''
                        oldtxt = ''
                    modata = Autos.query.filter(Autos.Status == 'New').first()
                    auto = modata.id
                    docref = f'tmp/{scac}/data/vdispatch/DISP' + str(
                        auto) + '.pdf'
                    doctxt = f'tmp/{scac}/data/vdispatch/DISP' + str(
                        auto) + '.txt'
                    try:
                        shutil.move(addpath(oldref), addpath(docref))
                    except:
                        err[3] = '.pdf file already moved'
                    try:
                        shutil.move(addpath(oldtxt), addpath(doctxt))
                    except:
                        err[4] = '.txt file already moved'
                    modata.Original = docref
                    modlink = 0
                else:
                    modata = Autos.query.get(auto)

                vals = [
                    'modelyear', 'make', 'model', 'color', 'vin', 'title',
                    'state', 'empweight', 'dispatched', 'owner', 'towcompany',
                    'towcost', 'delto', 'orderid', 'newtowcompany',
                    'towcostea', 'pufrom', 'cvalue', 'ncars'
                ]
                a = list(range(len(vals)))
                for i, v in enumerate(vals):
                    a[i] = request.values.get(v)
                modata.Year = a[0]
                modata.Make = a[1]
                modata.Model = a[2]
                modata.Color = a[3]
                modata.VIN = a[4]
                modata.Title = a[5]
                modata.State = a[6]
                modata.EmpWeight = a[7]
                modata.Dispatched = a[8]
                modata.Owner = a[9]
                company = a[10]
                if company == '1':
                    modata.TowCompany = a[14]
                    input = People(Company=a[14],
                                   First='',
                                   Middle='',
                                   Last='',
                                   Addr1='',
                                   Addr2='',
                                   Addr3='',
                                   Idtype='',
                                   Idnumber='',
                                   Telephone='',
                                   Email='',
                                   Associate1='',
                                   Associate2='',
                                   Date1=today,
                                   Date2=None,
                                   Original='',
                                   Ptype='TowCo',
                                   Temp1='',
                                   Temp2='')
                    db.session.add(input)
                    modata.TowCompany = a[14]
                else:
                    modata.TowCompany = company
                modata.TowCost = d2s(a[11])
                modata.Delto = a[12]
                modata.Pufrom = a[16]
                modata.Value = d2s(a[17])
                ncars = a[18]
                try:
                    ncars = int(a[18])
                    towcost = float(d2s(a[11]))
                    towcostea = towcost / float(ncars)
                    towcostea = str(towcostea)
                    towcostea = d2s(towcostea)
                    modata.TowCostEa = towcostea
                except:
                    modata.TowCostEa = a[15]
                    ncars = 0
                modata.Ncars = ncars
                sdate1 = request.values.get('date1')
                try:
                    sdate1dt = datetime.datetime.strptime(sdate1, "%Y-%m-%d")
                except:
                    sdate1 = today.strftime('%Y-%m-%d')

                sdate2 = request.values.get('date2')
                try:
                    sdate2dt = datetime.datetime.strptime(sdate2, "%Y-%m-%d")
                except:
                    sdate2 = today.strftime('%Y-%m-%d')
                modata.Date1 = sdate1
                modata.Date2 = sdate2
                modata.Orderid = a[13]
                modata.Status = 'Novo'

                db.session.commit()
                err = [
                    ' ', ' ', 'Modification to Auto Data ' + str(modata.id) +
                    ' completed.', ' ', ' '
                ]
                modlink = 0

# ____________________________________________________________________________________________________________________E.DataModifications.Dealer
# ____________________________________________________________________________________________________________________B.InvoiceUpdate.Dealer

        if invoupdate is not None:
            leftsize = 8
            hdata1 = Dealer.query.get(invooder)
            invodate = request.values.get('invodate')
            #if invodate is None:
            #invodate=today
            idata = Invoices.query.filter(Invoices.Jo == hdata1.Jo).all()
            for data in idata:
                iqty = request.values.get('qty' + str(data.id))
                iqty = nononef(iqty)
                data.Description = request.values.get('desc' + str(data.id))
                deach = request.values.get('cost' + str(data.id))
                if deach is not None:
                    deach = "{:.2f}".format(float(deach))
                else:
                    deach = "{:.2f}".format(0.00)
                data.Qty = iqty
                data.Ea = deach
                data.Date = invodate
                db.session.commit()
            #Remove zeros from invoice in case a zero was the mod
            Invoices.query.filter(Invoices.Qty == 0).delete()
            db.session.commit()
            #Create invoice code for order
            err = [' ', ' ', 'Invoice created for JO: ' + hdata1.Jo, ' ', ' ']
            idat = Invoices.query.filter(Invoices.Jo == hdata1.Jo).first()
            invodate = idat.Date

            idata = Invoices.query.filter(Invoices.Jo == hdata1.Jo).all()
            amt = 0.0
            for data in idata:
                amt = amt + float(data.Qty) * float(data.Ea)
            hdata1.Charge = "%0.2f" % amt
            hdata1.Status = 'Invoiced'
            db.session.commit()
            invo = 1
            # Regenerate invoice with new data
            idata = Invoices.query.filter(Invoices.Jo == hdata1.Jo).order_by(
                Invoices.Ea.desc()).all()
            pdat = People.query.filter(People.id == hdata1.Pid).first()
            cache = cache + 1

            import make_H_invoice
            make_H_invoice.main(hdata1, idata, pdat, cache, invodate, 0)

            if cache > 0:
                docref = f'tmp/{scac}/data/vinvoice/INV' + hdata1.Jo + 'c' + str(
                    cache) + '.pdf'
            else:
                docref = f'tmp/{scac}/data/vinvoice/INV' + hdata1.Jo + '.pdf'
            hdata1.Ipath = docref
            hdata1.Cache = cache
            db.session.commit()
            leftscreen = 0
            err[3] = 'invooder=' + str(invooder)
            err[4] = 'Viewing ' + docref
            modata = Dealer.query.get(invooder)
# ____________________________________________________________________________________________________________________E.InvoiceUpdate.Dealer
# ____________________________________________________________________________________________________________________B.SetBaseData.Dealer

        hdata = Dealer.query.all()
        adata = Autos.query.all()
        pdata = People.query.filter((People.Ptype == 'Jays')
                                    | (People.Ptype == 'TowCo')).all()
        # ____________________________________________________________________________________________________________________E.SetBaseData.Dealer
        # ____________________________________________________________________________________________________________________B.Numcheck.Dealer

        try:
            cars, auto, peep, numchecked = numcheck(3, hdata, adata, pdata, 0,
                                                    0,
                                                    ['cars', 'auto', 'peep'])
        except:
            cars = 0
            auto = 0
            peep = 0
            numchecked = 0

# ____________________________________________________________________________________________________________________E.Numcheck.Dealer
# ____________________________________________________________________________________________________________________B.Views.Dealer

        if (viewo is not None or viewi is not None) and numchecked == 1:
            err = [
                ' ', ' ', 'There is no document available for this selection',
                ' ', ' '
            ]

            if cars > 0 and viewi is not None:
                modata = Dealer.query.get(cars)
                if modata.Ipath is not None:
                    docref = modata.Ipath

            if cars > 0 and viewo is not None:
                modata = Dealer.query.get(cars)
                if modata.Apath is not None:
                    docref = modata.Apath

            if auto > 0:
                modata = Autos.query.get(auto)
                if modata.Original is not None:
                    docref = modata.Original

            if (auto > 0 or cars > 0) and docref:
                if len(docref) > 5:
                    leftscreen = 0
                    leftsize = 10
                    modlink = 0
                    err = ['All is well', ' ', ' ', ' ', ' ']

        if (viewo is not None or viewi is not None) and numchecked != 1:
            err = [
                'Must check exactly one box to use this option', ' ', ' ', ' ',
                ' '
            ]
# ____________________________________________________________________________________________________________________E.Views.Dealer
# ____________________________________________________________________________________________________________________B.ModifySetup.Dealer

        if (modify is not None or vmod is not None) and numchecked == 1:
            modlink = 1
            leftsize = 8
            if cars > 0:
                fdata = myoslist(f'tmp/{scac}/data/vunknown')
                fdata.sort()
                modata = Dealer.query.get(cars)
                jobdate = modata.Date
                if vmod is not None:
                    err = [
                        ' ', ' ',
                        'There is no document available for this selection',
                        ' ', ' '
                    ]
                    if modata.Apath is not None:
                        if len(modata.Apath) > 5:
                            leftscreen = 0
                            docref = f'tmp/{scac}/data/vcarbuy/' + modata.Apath
                            err = ['All is well', ' ', ' ', ' ', ' ']

            if peep > 0:
                modata = People.query.get(peep)
                if vmod is not None:
                    err = [
                        ' ', ' ',
                        'There is no document available for this selection',
                        ' ', ' '
                    ]
                    if modata.Original is not None:
                        if len(modata.Original) > 5:
                            leftscreen = 0
                            docref = f'tmp/{scac}/data/vpersons/' + modata.Original
                            err = ['All is well', ' ', ' ', ' ', ' ']
            if auto > 0:
                modata = Autos.query.get(auto)
                if vmod is not None:
                    err = [
                        ' ', ' ',
                        'There is no document available for this selection',
                        ' ', ' '
                    ]
                    if modata.Original is not None:
                        if len(modata.Original) > 5:
                            leftscreen = 0
                            leftsize = 8
                            docref = modata.Original
                            doctxt = docref.split('.', 1)[0] + '.txt'
                            err = ['All is well', ' ', ' ', ' ', ' ']

        if (modify is not None or vmod is not None) and numchecked != 1:
            modlink = 0
            err[0] = ' '
            err[2] = 'Must check exactly one box to use this option'
# ____________________________________________________________________________________________________________________E.ModifySetup.Dealer
# ____________________________________________________________________________________________________________________B.AddItemsSetup.Dealer

        if addE is not None and peep > 0 and numchecked == 1:
            modlink = 2
            modata = People.query.get(peep)

        if addE is not None:
            leftsize = 8
            modlink = 1
            #We will create a blank line and simply modify that by updating:
            input = People(Company='New',
                           First=None,
                           Middle=None,
                           Last=None,
                           Addr1=None,
                           Addr2=None,
                           Addr3=None,
                           Idtype=None,
                           Idnumber=None,
                           Telephone=None,
                           Email=None,
                           Associate1=None,
                           Associate2=None,
                           Date1=None,
                           Date2=None,
                           Original=None,
                           Ptype='Dealer',
                           Temp1=None,
                           Temp2=None,
                           Accountid=None)
            db.session.add(input)
            db.session.commit()
            modata = People.query.filter((People.Company == 'New')
                                         & (People.Ptype == 'Dealer')).first()
            if modata is not None:
                peep = modata.id
            else:
                peep = 0
            err = [' ', ' ', 'Enter Data for New Entity', ' ', ' ']

        if addA is not None or modlink == 10:
            leftscreen = 0
            leftsize = 8
            if modlink == 10:
                titledata = General.query.filter(
                    (General.Subject.contains('title'))
                    & (General.Category.contains('1'))).all()
                fdata = []
                displdata = []
                for title in titledata:
                    fdata.append(title.Path)
                    displdata.append(title.Category)
                filesel = request.values.get('FileSel')
                docref = f'tmp/{scac}/data/vgeneral/' + filesel
                doctxt = docref.split('.', 1)[0] + '.txt'

            if modlink != 10:
                titledata = General.query.filter(
                    (General.Subject.contains('title'))
                    & (General.Category.contains('1'))).all()
                fdata = []
                displdata = []
                for title in titledata:
                    file1 = f'tmp/{scac}/data/vgeneral/' + title.Path
                    fdata.append(title.Path)
                    displdata.append(title.Category)

                docref = f'tmp/{scac}/data/vgeneral/' + fdata[0]
                doctxt = ''
                #We will create a blank line and simply modify that by updating:
                input = Autos(Jo=None,
                              Hjo=None,
                              Year=None,
                              Make=None,
                              Model=None,
                              Color=None,
                              VIN=None,
                              Title=None,
                              State=None,
                              EmpWeight=None,
                              Dispatched=None,
                              Value=None,
                              TowCompany=None,
                              TowCost=None,
                              TowCostEa=None,
                              Original=None,
                              Status='New',
                              Date1=None,
                              Date2=None,
                              Pufrom=None,
                              Delto=None,
                              Ncars=None,
                              Orderid=None)
                db.session.add(input)
                db.session.commit()
                modata = Autos.query.filter(Autos.Status == 'New').first()
                if modata is not None:
                    auto = modata.id
                else:
                    auto = 0
                modlink = 10

            err = [' ', ' ', 'Enter Data for New Auto', ' ', ' ']
# ____________________________________________________________________________________________________________________E.AddItemsSetup.Dealer
# ____________________________________________________________________________________________________________________B.Email.Dealer

        if emailinvo is not None:
            leftsize = 8
            leftscreen = 0
            modlink = 0
            modata = Dealerquery.get(invooder)
            ldata = Invoices.query.filter(Invoices.Jo == modata.Jo).order_by(
                Invoices.Ea.desc()).all()
            jo = modata.Jo
            pdat = People.query.filter(People.id == modata.Pid).first()
            if pdat is None:
                err = [
                    ' ', ' ',
                    'There is no Billing information for this selection', ' ',
                    ' '
                ]
            else:
                email = pdat.Email
            docref = modata.Ipath
            modata.Status = 'EmlInvo'
            db.session.commit()

            if 'vinvoice' not in docref:
                err = [
                    ' ', ' ',
                    'There is no document available for this selection', ' ',
                    ' '
                ]
            else:
                if email is not None:
                    import invoice_mimemail2
                    invoice_mimemail2.main(jo, docref, email)
# ____________________________________________________________________________________________________________________E.Email.Dealer
# ____________________________________________________________________________________________________________________B.Delete.Dealer

        if deletehit is not None and numchecked == 1:
            if cars > 0:
                Dealer.query.filter(Dealer.id == cars).delete()
            if peep > 0:
                People.query.filter(People.id == peep).delete()
            if auto > 0:
                Autos.query.filter(Autos.id == auto).delete()
            db.session.commit()

            pdata = GetCo('Jays', 'All')
            hdata = Dealer.query.order_by(Dealer.Jo).all()
            adata = Autos.query.all()

        if deletehit is not None and numchecked != 1:
            err = [
                ' ', ' ',
                'Must have exactly one item checked to use this option', ' ',
                ' '
            ]
# ____________________________________________________________________________________________________________________E.Delete.Dealer
# ____________________________________________________________________________________________________________________B.ReceivePayment.Dealer

        if (recpay is not None and cars > 0
                and numchecked == 1) or recupdate is not None:
            leftsize = 8
            if recpay is not None:
                invooder = cars
            hdat = Dealer.query.get(invooder)
            invojo = hdat.Jo
            ldat = Invoices.query.filter(Invoices.Jo == invojo).first()
            err = ['Have no Invoice to Receive Against', ' ', ' ', ' ', ' ']
            if ldat is not None:
                idate = ldat.Date
                if ldat.Original is not None:
                    docref = ldat.Original
                    leftscreen = 0
                    leftsize = 8

                incdat = Income.query.filter(Income.Jo == invojo).first()
                if incdat is None:
                    err = ['Creating New Payment on Jo', ' ', ' ', ' ', ' ']
                    paydesc = 'Receive payment on Invoice ' + invojo
                    recamount = str(ldat.Amount)
                    custref = 'ChkNo'
                    recdate = today
                    input = Income(Jo=hdat.Jo,
                                   SubJo=None,
                                   Pid=hdat.Pid,
                                   Description=paydesc,
                                   Amount=recamount,
                                   Ref=custref,
                                   Date=recdate,
                                   Original=None)
                    db.session.add(input)
                    payment = 0
                else:
                    recamount = request.values.get('recamount')
                    custref = request.values.get('custref')
                    desc = request.values.get('desc')
                    recdate = request.values.get('recdate')
                    incdat.Amount = recamount
                    incdat.Ref = custref
                    incdat.Description = desc
                    incdat.Date = recdate
                db.session.commit()
                payment = [recamount, custref, recdate]

                modata = Income.query.filter(Income.Jo == invojo).first()
                inco = modata.id
                err = [' ', ' ', 'Amend Payment for Invoice', ' ', ' ']

                ldata = Invoices.query.filter(Invoices.Jo == invojo).order_by(
                    Invoices.Ea.desc()).all()
                pdat = People.query.filter(People.id == hdat.Pid).first()
                cache = nonone(hdat.Cache) + 1

                import make_H_invoice
                make_H_invoice.main(hdat, ldata, pdat, cache, invodate,
                                    payment)

                if cache > 1:
                    docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + 'c' + str(
                        cache) + '.pdf'
                    # Store for future use
                else:
                    docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + '.pdf'

                hdat.Cache = cache
                hdat.Status = 'Paid'
                idat = Invoices.query.filter(Invoices.Jo == invojo).first()
                idat.Original = docref
                db.session.commit()
                leftscreen = 0
                err[4] = 'Viewing ' + docref

        if recpay is not None and (cars == 0 or numchecked != 1):
            err = ['Invalid selections:', '', '', '', '']
            if cars == 0:
                err[1] = 'Must select a Dealer Job'
            if numchecked != 1:
                err[2] = 'Must select exactly one Dealer Job'
# ____________________________________________________________________________________________________________________E.Receive Payment.Dealer
# ____________________________________________________________________________________________________________________B.Payment History.Dealer
        if hispay is not None or modlink == 7:
            if cars == 0 and invooder == 0:
                err[1] = 'Must select an Dealer Job'
            else:
                if cars != 0:
                    invooder = cars
                modata = Dealer.query.get(invooder)
                idata = Invoices.query.filter(
                    Invoices.Jo == modata.Jo).order_by(Invoices.Jo).all()
                fdata = Income.query.filter(Income.Jo == modata.Jo).order_by(
                    Income.Jo).all()
                #Check to see if we need to delete anything from history
                killthis = request.values.get('killthis')
                if killthis is not None and modlink == 7:
                    for data in idata:
                        testone = request.values.get('bill' + str(data.id))
                        if testone:
                            kill = int(testone)
                            Invoices.query.filter(Invoices.id == kill).delete()
                            db.session.commit()
                    for data in fdata:
                        testone = request.values.get('pay' + str(data.id))
                        if testone:
                            kill = int(testone)
                            Income.query.filter(Income.id == kill).delete()
                            db.session.commit()
                    idata = Invoices.query.filter(
                        Invoices.Jo == modata.Jo).order_by(Invoices.Jo).all()
                    fdata = Income.query.filter(
                        Income.Jo == modata.Jo).order_by(Income.Jo).all()

                leftsize = 8
                modlink = 7
# ____________________________________________________________________________________________________________________E.PaymentHistory.Dealer

# ____________________________________________________________________________________________________________________B.Invoice.Dealer

        if (minvo is not None and cars > 0):
            err = ['Could not create invoice', ' ', ' ', ' ', ' ']
            # First time through: have an order to invoice
            if cars > 0:
                invooder = cars
            myo = Dealer.query.get(invooder)
            #Check to see if we have the required data to make an invoice:
            bid = myo.Pid

            if bid is None:
                err[1] = 'No Billing Data'

            if bid:
                invo = 1
                leftsize = 8
                if myo.Cache is not None:
                    cache = myo.Cache + 1
                else:
                    cache = 1

                hdata = Dealer.query.filter(Dealer.Jo == myo.Jo).all()
                total = 0
                #Delete previous invoices created for this Jo
                killdata = Invoices.query.filter(
                    Invoices.Jo == myo.Jo).delete()
                for data in hdata:
                    qty = 1
                    towcost = nononef(data.Tow)
                    repaircost = nononef(data.Repair)
                    othercost = nononef(data.Ocost)
                    buyerfee = nononef(data.Bfee)
                    carcost = nononef(data.Sale)
                    docfee = nononef(data.DocumentFee)

                    total = total + towcost + repaircost + othercost + buyerfee + carcost + docfee
                    if carcost > 0:
                        descript = data.Year + ' ' + data.Make + ' ' + data.Model + ' VIN:' + data.Vin
                        input = Invoices(Jo=myo.Jo,
                                         SubJo=None,
                                         Pid=bid,
                                         Service='Car Purchase',
                                         Description=descript,
                                         Ea=carcost,
                                         Qty=qty,
                                         Amount=carcost,
                                         Total=total,
                                         Date=today,
                                         Original=None,
                                         Status='New')
                        db.session.add(input)
                        db.session.commit()
                    if buyerfee > 0:
                        descript = 'Buyer fee for VIN: ' + data.Vin
                        input = Invoices(Jo=myo.Jo,
                                         SubJo=None,
                                         Pid=bid,
                                         Service='Buyer Fee',
                                         Description=descript,
                                         Ea=buyerfee,
                                         Qty=qty,
                                         Amount=buyerfee,
                                         Total=total,
                                         Date=today,
                                         Original=None,
                                         Status='New')
                        db.session.add(input)
                        db.session.commit()
                    if towcost > 0:
                        descript = 'Towing cost for VIN: ' + data.Vin
                        input = Invoices(Jo=myo.Jo,
                                         SubJo=None,
                                         Pid=bid,
                                         Service='Towing',
                                         Description=descript,
                                         Ea=towcost,
                                         Qty=qty,
                                         Amount=towcost,
                                         Total=total,
                                         Date=today,
                                         Original=None,
                                         Status='New')
                        db.session.add(input)
                        db.session.commit()
                    if repaircost > 0:
                        descript = 'Repair cost for VIN: ' + data.Vin
                        input = Invoices(Jo=myo.Jo,
                                         SubJo=None,
                                         Pid=bid,
                                         Service='Repairs',
                                         Description=descript,
                                         Ea=repaircost,
                                         Qty=qty,
                                         Amount=repaircost,
                                         Total=total,
                                         Date=today,
                                         Original=None,
                                         Status='New')
                        db.session.add(input)
                        db.session.commit()
                    if docfee > 0:
                        descript = 'Dealer document fee for VIN: ' + data.Vin
                        input = Invoices(Jo=myo.Jo,
                                         SubJo=None,
                                         Pid=bid,
                                         Service='Document Fee',
                                         Description=descript,
                                         Ea=docfee,
                                         Qty=qty,
                                         Amount=docfee,
                                         Total=total,
                                         Date=today,
                                         Original=None,
                                         Status='New')
                        db.session.add(input)
                        db.session.commit()
                    if othercost > 0:
                        descript = data.Oitem + ' for VIN: ' + data.Vin
                        input = Invoices(Jo=myo.Jo,
                                         SubJo=None,
                                         Pid=bid,
                                         Service=data.Oitem,
                                         Description=descript,
                                         Ea=othercost,
                                         Qty=qty,
                                         Amount=othercost,
                                         Total=total,
                                         Date=today,
                                         Original=None,
                                         Status='New')
                        db.session.add(input)
                        db.session.commit()

                #Cycle through again so all the line items have the correct total amount
                idata = Invoices.query.filter(Invoices.Jo == myo.Jo).all()
                if idata is not None:
                    for data in idata:
                        data.Total = total
                        db.session.commit()

                ldat = Invoices.query.filter(Invoices.Jo == myo.Jo).first()
                if ldat is None:
                    invo = 0
                    leftsize = 10
                    err = [
                        ' ', ' ',
                        'No services on invoice yet and none selected', ' ',
                        ' '
                    ]
                else:
                    invo = 1
                    leftsize = 8
                    invodate = ldat.Date
                    err = [
                        ' ', ' ', 'Created invoice for JO= ' + myo.Jo, ' ', ' '
                    ]
                    ldata = Invoices.query.filter(
                        Invoices.Jo == myo.Jo).order_by(
                            Invoices.Ea.desc()).all()
                    pdat = People.query.filter(People.id == myo.Pid).first()

                    import make_H_invoice
                    make_H_invoice.main(myo, ldata, pdat, cache, invodate, 0)

                    if cache > 0:
                        docref = f'tmp/{scac}/data/vinvoice/INV' + myo.Jo + 'c' + str(
                            cache) + '.pdf'
                        # Store for future use
                    else:
                        docref = f'tmp/{scac}/data/vinvoice/INV' + myo.Jo + '.pdf'
                    myo.Ipath = docref
                    myo.Cache = cache
                    db.session.commit()
                    leftscreen = 0
                    err[3] = 'invooder=' + str(invooder)
                    err[4] = 'Viewing ' + docref
                    modata = Dealer.query.get(invooder)

        elif minvo is not None:
            err = [
                ' ', ' ', 'Must select at least 1 Job for this selection', ' ',
                ' '
            ]
# ____________________________________________________________________________________________________________________E.Invoice.Dealer
# ____________________________________________________________________________________________________________________B.Newjob.Dealer
        if newjob is not None:
            err = ['Select Source Document from List']
            jobdate = datetime.date.today()
            modlink = 4
            leftsize = 8
            leftscreen = 0
            docref = f'tmp/{scac}/data/vunknown/NewJob.pdf'
            doctxt = ''

        if newjob is None and modlink == 4:
            filesel = request.values.get('FileSel')
            fdata = myoslist(f'tmp/{scac}/data/vunknown')
            fdata.sort()
            jobdate = request.values.get('dstart')
            leftsize = 8
            leftscreen = 0
            if filesel != '1':
                docref = f'tmp/{scac}/data/vunknown/' + filesel
                doctxt = docref.split('.', 1)[0] + '.txt'
            else:
                docref = ''
                doctxt = ''

        if thisjob is not None:
            modlink = 0
            #Create the new database entry for the source document
            filesel = request.values.get('FileSel')
            if filesel != '1':
                docold = f'tmp/{scac}/data/vunknown/' + filesel
                docref = f'tmp/{scac}/data/vcarbuy/' + filesel
                try:
                    shutil.move(addpath(docold), addpath(docref))
                except:
                    err[0] = 'File moved'
            else:
                docref = ''
            sdate = request.values.get('dstart')
            if sdate is None:
                sdate = today

            jtype = 'J'
            nextjo = newjo(jtype, sdate)

            company = request.values.get('thiscompany')
            bid = People.query.filter(People.Company == company).first()
            if bid is not None:
                idb = bid.id
            else:
                idb = 0

            input = Dealer(Jo=nextjo,
                           Pid=idb,
                           Company=company,
                           Aid=0,
                           Make=None,
                           Model=None,
                           Year=None,
                           Vin=None,
                           Cost=None,
                           Sale=None,
                           Bfee=None,
                           Tow=None,
                           Repair=None,
                           Oitem=None,
                           Ocost=None,
                           Ipath=None,
                           Apath=filesel,
                           Cache=0,
                           Status='New',
                           Label=None,
                           Date=sdate,
                           DocumentFee='')

            db.session.add(input)
            db.session.commit()
            modata = Dealer.query.filter(Dealer.Jo == nextjo).first()
            cars = modata.id
            leftscreen = 0
            err = ['All is well', ' ', ' ', ' ', ' ']
# ____________________________________________________________________________________________________________________E.Newjob.Dealer
# ____________________________________________________________________________________________________________________B.Match.Dealer

        if match is not None:

            if cars > 0 and peep > 0 and numchecked == 2:
                mys = Dealer.query.get(cars)
                myp = People.query.get(peep)
                mys.Pid = myp.id
                mys.Company = myp.Company

                db.session.commit()

            if cars > 0 and auto > 0 and numchecked == 2:
                mys = Dealer.query.get(cars)
                mya = Autos.query.get(auto)
                thisjo = mys.Jo
                mya.Hjo = thisjo
                # Check to see if we need a new JO line because we already have a car assigned
                if mys.Aid > 0 and mys.Aid != auto:
                    #We need a new line item
                    input = Dealer(Jo=thisjo,
                                   Pid=mys.Pid,
                                   Company=mys.Company,
                                   Aid=0,
                                   Make=None,
                                   Model=None,
                                   Year=None,
                                   Vin=None,
                                   Cost=None,
                                   Sale=None,
                                   Bfee=None,
                                   Tow=None,
                                   Repair=None,
                                   Oitem=None,
                                   Ocost=None,
                                   Ipath=None,
                                   Apath=None,
                                   Cache=0,
                                   Status='New',
                                   Label=None,
                                   DocumentFee='')
                    db.session.add(input)
                    db.session.commit()
                    mys = Dealer.query.filter((Dealer.Jo == thisjo)
                                              & (Dealer.Aid == 0)).first()

                mys.Aid = auto
                mys.Make = mya.Make
                mys.Model = mya.Model
                mys.Year = mya.Year
                mys.Vin = mya.VIN
                mys.Status = 'Car'
                mya.Status = 'M'
                db.session.commit()

            if numchecked != 2:
                err[1] = 'Must select exactly 2 boxes to use this option.'
                err[0] = ' '

# ____________________________________________________________________________________________________________________E.Match.Dealer
# ____________________________________________________________________________________________________________________B.Calendar.Dealer
        if calendar is not None or calupdate is not None:
            leftscreen = 2
            if calupdate is not None:
                waft = request.values.get('waft')
                wbef = request.values.get('wbef')
                waft = nonone(waft)
                wbef = nonone(wbef)
                nweeks = [wbef, waft]
            else:
                nweeks = [2, 3]
            caldays, daylist, weeksum = calendar7_weeks('Dealer', nweeks)

# ____________________________________________________________________________________________________________________E.Calendar.Dealer

#This is the else for 1st time through (not posting data from Dealer.html)
    else:
        from viewfuncs import GetCo, popjo, jovec, timedata, nonone, nononef, init_horizon_zero, GetCo3
        #today = datetime.date.today().strftime('%Y-%m-%d')
        #now = datetime.datetime.now().strftime('%I:%M %p')
        jobdate = datetime.date.today()
        idata = 0
        leftscreen = 1
        cars, auto, peep, invo, cache, modata, modlink, invooder, stamp, fdata, csize, invodate, inco, cdat, pb, passdata, vdata, caldays, daylist, weeksum, nweeks = init_horizon_zero(
        )
        leftscreen = 1
        dlist = ['off'] * 3
        dlist[1] = 'on'
        filesel = ''
        docref = ''
        doctxt = ''
        leftsize = 10
        err = ['All is well', ' ', ' ', ' ', ' ']
        displdata = 0

    if fdata == 0:
        fdata = myoslist('data/vunknown')
        fdata.sort()
    pdata = GetCo('Jays', 'All')
    sdata = Services.query.all()
    hdata = Dealer.query.all()
    adata = Autos.query.all()
    leftsize = 8

    return hdata, adata, pdata, idata, fdata, displdata, cars, invooder, auto, peep, err, modata, caldays, daylist, nweeks, invodate, doctxt, sdata, dlist, modlink, inco, invo, cache, filesel, leftscreen, docref, leftsize, jobdate