示例#1
0
async def login(*, account, passwd):
    email = account
    passwd = passwd.strip()
    if not email:
        return returnData(0, "认证")
    if not passwd:
        return returnData(0, "认证")
    whereu = "email = '%s'" % (email)
    try:
        users = await Users.findAll(where=whereu)
    except:
        return returnData(0, "认证")
    users = obj2str(users)
    if len(users) == 1:
        user = users[0]
        if user.passwd == passwd:
            r = web.Response()
            r.set_cookie(COOKIE_NAME,
                         user2cookie(user, 86400),
                         max_age=86400,
                         httponly=True)
            user.passwd = "******"
            user.msg = "登陆成功"
            user.status = 1
            r.content_type = 'application/json'
            r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
            return r
        else:
            return returnData(0, "认证")
    else:
        return returnData(0, "认证")
示例#2
0
async def index(*, keyword=None, rangeDate=None, moneyStatus=None,invStatus=None, mediaType=None, isExport=None, isSearch=None, year=None, page=1, pageSize=50):

    page = int(page)
    pageSize = int(pageSize)

    # 合计金额, 只统计当前页面显示数据
    totalMoney = 0

    where = baseWhere = await addAffDateWhere(rangeDate, isSearch, 'i.is_delete')
    if keyword:
        where = "{} and (income_id like '%%{}%%' or c.name like '%%{}%%')".format(where, keyword, keyword)
    if moneyStatus and moneyStatus.isdigit():
        where = "{} and money_status = {}".format(where, moneyStatus)
    if invStatus and invStatus.isdigit():
        where = "{} and inv_status = {}".format(where, invStatus)
    if mediaType and mediaType.isdigit():
        where = "{} and media_type = {}".format(where, mediaType)
    
    sql = "SELECT count(*) c FROM income i INNER JOIN `client` c ON i.`client_id` = c.`id` where {}".format(where)
    rs = await Income.query(sql)

    total, limit, p = totalLimitP(rs, page, pageSize)
    if total == 0:
        return dict(total = total, page = p, list = (), other = {
            'moneyStatusMap': moneyStatusMap,
            'invStatusMap': invStatusMap,
            'mediaTypeMap': mediaTypeMap,
            'totalMoney': round(totalMoney, 2)
        })

    sql = "SELECT i.*,c.name company_name FROM income i INNER JOIN `client` c ON i.`client_id` = c.`id` where %s order by %s" % (where, 'income_id desc')

    if not isExport or int(isExport) != 1:
        sql = '%s limit %s' % (sql, limit)

    lists = await Income.query(sql)

    # 将获得数据中的日期转换为字符串
    lists = obj2str(lists)

    for item in lists:
        item['money_status_text'] = moneyStatusMap[item['money_status']]
        item['inv_status_text'] = invStatusMap[item['inv_status']]
        item['media_type_text'] = mediaTypeMap[item['media_type']]
        totalMoney += item['money']

    if isExport and int(isExport) == 1:
        return await export(lists)

    return {
        'total': total,
        'page': p,
        'list': lists,
        'other': {
            'moneyStatusMap': moneyStatusMap,
            'invStatusMap': invStatusMap,
            'mediaTypeMap': mediaTypeMap,
            'totalMoney': round(totalMoney, 2)
        }
    }
示例#3
0
async def login(*, account, passwd):
    email = account
    if not email:
        raise ValueError('email', 'Invalid email.')
    if not passwd:
        raise ValueError('passwd', 'Invalid password.')
    whereu = "email = '%s'" % (email)
    users = await Users.findAll(where=whereu)
    users = obj2str(users)
    if len(users) != 1:
        logging.info("no such user or more than one")
        return returnData(0, "密码错误,")
    user = users[0]
    if user.passwd != passwd:
        return returnData(0, "密码错误,")
    r = web.Response()
    r.set_cookie(COOKIE_NAME,
                 user2cookie(user, 86400),
                 max_age=86400,
                 httponly=True)
    user.passwd = "******"
    user.msg = "登陆成功"
    user.status = 1
    r.content_type = 'application/json'
    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')
    return r
示例#4
0
async def info(*, id=0):

    id = int(id)

    if not id:
        return returnData(0, '查询', 'ID不存在')

    sql = "SELECT s.id,s.client_id, s.income_id,s.balance,s.pay_company, s.stype, i.aff_date,i.money,i.money_status,i.cost, i.inv_status, c.invoice,c.name company_name \
            FROM settlement s \
            INNER JOIN income i ON s.`income_id` = i.`id` \
            INNER JOIN `client` c ON s.`client_id` = c.`id` \
            WHERE s.id= %s" % id

    info = await Settlement.query(sql)

    if not info:
        return returnData(0, '查询')

    res = returnData(1, '查询')

    res['info'] = obj2str((info))[0]

    # 收入状态
    res['info']['money_status_text'] = income.moneyStatusMap[res['info']
                                                             ['money_status']]
    res['info']['inv_status_text'] = income.invStatusMap[res['info']
                                                         ['inv_status']]

    # 结算比例
    rate = round(res['info']['balance'] / res['info']['money'] * 100, 3)
    res['info']['rate'] = "%s%%" % rate

    return res
示例#5
0
async def detail(*, id=0):
    """获得收入报表详情
    """

    res = {
        'status': 1,
        'msg': '查询成功',
        'info': []
    }

    if not id:
        return returnData(0, '查询', '收入ID不存在')


    sql = "SELECT i.income_id, i.`aff_date`, i.`money`, i.money_status,i.inv_status,i.cost, \
            c.`name` company_name, c.`invoice` FROM income i \
            INNER JOIN `client` c ON i.`client_id` = c.`id` \
            where i.id = %s" % id

    info = await Income.query(sql)

    if not info:
        return returnData(0, '查询')

    res['info'] = obj2str((info))[0]

    res['info']['money_status_text'] = moneyStatusMap[res['info']['money_status']]
    res['info']['inv_status_text'] = invStatusMap[res['info']['inv_status']]

    return res
示例#6
0
async def get_role(request):
    sql_role = 'select id,title from role'
    try:
        id_roles = await Role.query(sql_role)
        id_roles = obj2str(id_roles)
    except:
        raise ValueError("/apis/manger/init_role获取用户角色错误")
    return {"id_roles": id_roles}
示例#7
0
async def managerInfo(*, id):
    if id:
        where = " id = %s " % (id)
        users = await Users.findAll(where=where)
        users = obj2str(users)
        if len(users) != 1:
            return returnData(0, "编辑")

        return {"info": users[0]}
示例#8
0
async def apis_main_operate(*, page=1, pageSize=15):
    email = configs.user.name
    user_info = await Users.findOne(where="email='%s'" % email)
    ids = user_info['read_log_ids']
    page = int(page)
    pageSize = int(pageSize)
    sql_re = 'select sy.id sys_id,u.name,inc.income_id,sy.operate,sy.add_date,c.name gongsi,inc.name yewu,inc.money,inc.inv_status from  syslog sy  inner join users u on u.email = sy.username inner join income inc on inc.id = sy.affetced_id  inner join client c on c.id = inc.client_id  where sy.`table` in  ("INCOME","SETTLEMENT")  and u.is_delete = 0 and c.is_delete = 0 and inc.is_delete = 0 and sy.is_delete = 0   order by  sy.id desc limit 0,15  '
    try:
        res = await Syslogs.query(sql_re)
    except:
        logging.ERROR("查询income,syslog,数据库错误,url /apis/main/index")
        res = ()
    res = obj2str(res)
    if len(res) < 1:
        total = 0
    else:
        total = len(res)
    wheres = ' status = 0 '
    wherei = ' finished = 0 '
    try:
        settle = await Settlement.findAll(where=wheres)
        settle = len(settle)
        income = await Invoice.findAll(where=wherei)
        invoice = len(income)
    except:
        logging.ERROR("查询数据错误 数据库表 settlement invoice")
        return dict(total=total,
                    page=(0, 0),
                    list=res,
                    other=({
                        "settle": "error",
                        "invoice": "error"
                    }))
    week_ago = (datetime.datetime.now() -
                datetime.timedelta(hours=24 * 7)).strftime('%Y-%m-%d')
    week_sql = "SELECT * FROM `client` WHERE indate_end < '{}'".format(
        week_ago)
    clients = await Client.query(week_sql)
    expire_ = len(clients)

    other = dict(settle=settle, invoice=invoice, expire_=expire_)

    for i in res:
        i["operate"] = operateMaps[i['operate']]
        if ids and i['sys_id'] and str(i['sys_id']) in ids:
            i['is_read'] = 1
        else:
            i['is_read'] = 0
        if i["inv_status"] == 0:
            i["inv_status"] = "未开票"
        elif i["inv_status"] == 1:
            i["inv_status"] = "不开票"
        elif i["inv_status"] == 2:
            i["inv_status"] = "已开票"
        else:
            i["inv_status"] = "状态错误"
    return {"total": 1, "page": (1, 1), "list": res, "other": other}
示例#9
0
async def index(*, keyword=None, status=None, page=1, pageSize=10):
    page = int(page)
    pageSize = int(pageSize)

    # 当前日期
    currDate = time.strftime('%Y-%m-%d')

    where = '1 = 1'
    if keyword:
        where = "name like '%%{}%%'".format(keyword)
    if status and status.isdigit():
        if int(status) == 0:
            where = "%s and indate_end < '%s'" % (where, currDate)
        else:
            where = "%s and indate_end >= '%s'" % (where, currDate)

    total = await Client.findNumber('count(id)', where)
    total, limit, p = totalLimitP(total, page, pageSize, True)

    if total == 0:
        return dict(total=total, page=p, list=())
    clients = await Client.findAll(orderBy='indate_end',
                                   where=where,
                                   limit=limit)

    # 将获得数据中的日期转换为字符串
    clients = obj2str(clients)

    # 获得每个客户下的投放数和回款数
    selectField = "count(*) tfCount, sum(money) tfMoney"
    for item in clients:
        # 投放数
        where = 'is_delete = 0 and client_id=%s' % item.id
        info = await Income.findOne(selectField, where)
        item['tfCount'] = round(info['tfCount'], 2) if info['tfCount'] else 0

        # 投放金额
        item['tfMoney'] = round(info['tfMoney'], 2) if info['tfMoney'] else 0

        # 回款金额
        where = "%s and money_status = 1" % where
        field = "count(*) hkCount, sum(money) hkMoney"
        info = await Income.findOne(field, where)
        item['hkMoney'] = round(info['hkMoney'], 2) if info['hkMoney'] else 0

        # 回款数
        item['hkCount'] = round(info['hkCount'], 2) if info['hkCount'] else 0
        item['invoice'] = replLineBreak(item['invoice'])
        # 合同是否有效
        item['indate_status'] = item['indate_end'] >= currDate
        timedelta = datetime.datetime.strptime(
            item['indate_end'], '%Y-%m-%d') - datetime.datetime.strptime(
                datetime.datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
        item['timedelta'] = timedelta.days
        # print(item['sortFlag'])  datetime.datetime.strptime(detester,’%Y-%m-%d') item['sortFlag'] =
    res = sortFunc(*clients)
    return {'total': total, 'page': p, 'list': res}
示例#10
0
async def index(*, keyword=None, operate=None, module=None, page=1, pageSize=10):
    page = int(page)
    pageSize = int(pageSize)
    email = configs.user.name
    user_info = await Users.findOne(where="email='%s'" % email)
    ids = user_info['read_log_ids']
    # 当前日期
    # currDate = time.strftime('%Y-%m-%d')

    where = "s.is_delete =0"
    if keyword:
        where = "{} and (s.username like '%%{}%%' or i.income_id like '%%{}%%')".format(where, keyword, keyword)
    if operate and operate in operateMaps.keys():
        where = "%s and operate = '%s'" % (where, operate)
    if module and module in moduleMaps.keys():
        where = "%s and module = '%s'" % (where, module)
    
    sql = sqlTpl.format('count(*) c', where)
    rs = await Syslogs.query(sql)
    total, limit, p = totalLimitP(rs, page, pageSize)
    
    if total == 0:
        return dict(total = total, page = p, list = (), other={
            'operateMaps': operateMaps,
            'moduleMaps': moduleMaps
        })
    
    where = "%s order by %s limit %s" % (where, 's.id desc', limit)
    sql = sqlTpl.format(selectField, where)
   
    lists = await Syslogs.query(sql)

    # 将获得数据中的日期转换为字符串
    lists = obj2str(lists)

    # 获得每个客户下的投放数和回款数
    for item in lists:
        if ids and item['id'] and str(item['id']) in ids:
            item['is_read'] = 1
        else:
            item['is_read'] = 0
        item['operate_text'] = operateMaps[item['operate']]
        item['module_text'] = moduleMaps[item['module']]
        item['money_status_text'] = moneyStatusMap[item['money_status']]
        item['inv_status_text'] = invStatusMap[item['inv_status']]
       

    return {
        'total': total,
        'page': p,
        'list': lists,
        'other': {
            'operateMaps': operateMaps,
            'moduleMaps': moduleMaps
        }
    }
示例#11
0
async def lookAll(*, page=1, pageSize=30):
    page = int(page)
    pageSize = int(pageSize)
    where = '1 = 1'

    total = await Users.findNumber('count(id)', where)
    p = (math.ceil(total / pageSize), page)
    if total == 0:
        return dict(total=total, page=p, list=())
    users = await Users.findAll(orderBy='id desc', where=where, limit=pageSize)
    users = obj2str(users)
    roles = await Role.findAll()
    roles = obj2str(roles)
    roles_template = {}
    for role in roles:
        roles_template[role["id"]] = role["title"]
    for item in users:
        item["passwd"] = "******"
        item["role"] = roles_template[item["role"]]
    return {'total': total, 'page': p, 'list': users}
示例#12
0
async def index(*, page=1, pageSize=10):

    page = int(page)
    pageSize = int(pageSize)

    lists = await Role.findAll(orderBy="id asc")

    # 将获得数据中的日期转换为字符串
    lists = obj2str(lists)

    return {'total': 0, 'page': [1, 10], 'list': lists}
示例#13
0
async def info(*, id):

    action = '查询'
    id = int(id)

    if not id:
        return returnData(0, action, 'ID不存在')

    info = await Rule.find(id)
    if not info:
        return returnData(0, action)

    res = returnData(1, action)
    res['info'] = obj2str([info])[0]

    return res
示例#14
0
async def index(*, keyword=None, page=1, pageSize=10):

    page = int(page)
    pageSize = int(pageSize)

    where = "1=1"
    if keyword:
        where = "{} and title like '%%{}%%'".format(where, keyword)

    lists = await Rule.findAll(where=where, orderBy="sort desc, id asc")

    # 将获得数据中的日期转换为字符串
    lists = obj2str(lists)

    for item in lists:
        item['menustatus_text'] = menuStatusMap[item['menustatus']]
        item['authopen_text'] = authopenMap[item['authopen']]

    lists = ruleTree(lists, True)
    return {'total': 0, 'page': [1, 10], 'list': lists}
示例#15
0
async def info(*, id):
    id = int(id)

    if not id:
        return returnData(0, '查询', 'ID不存在')

    info = await Client.find(id)

    if not info:
        return returnData(0, '查询')

    info = obj2str([info])[0]
    info['indate'] = "%s - %s" % (info['indate_start'], info['indate_end'])
    del info['indate_start']
    del info['indate_end']

    res = returnData(1, '查询')

    res['info'] = info

    return res
示例#16
0
async def info(*, id=0):

    id = int(id)
    res = {'status': 1, 'msg': '查询成功', 'info': []}

    if not id:
        return returnData(0, '查询', 'id不存在')

    sql = "SELECT inv.id, inv.income_id, i.aff_date,i.money, c.invoice,c.name company_name \
            FROM invoice inv \
            INNER JOIN income i ON inv.`income_id` = i.`id` \
            INNER JOIN `client` c ON i.`client_id` = c.`id` \
            WHERE inv.id = %s" % id

    info = await Invoice.query(sql)

    if not info:
        return returnData(0, '查询')

    res['info'] = obj2str((info))[0]

    return res
示例#17
0
async def lookAll(*, page=1, pageSize=30):
    page = int(page)
    pageSize = int(pageSize)
    where = '1 = 1'

    total = await Users.findNumber('count(id)', where)
    p = (math.ceil(total / pageSize), page)
    if total == 0:
        return dict(total=total, page=p, list=())
    users = await Users.findAll(orderBy='id desc', where=where, limit=pageSize)

    users = obj2str(users)

    for item in users:
        item["passwd"] = "******"
        if item["role"] == 0:
            item["role"] = "管理员"
        elif item["role"] == 1:
            item["role"] = "运营侧"
        elif item["role"] == 2:
            item["role"] = "财务侧"
        else:
            item["role"] = "角色错误"
    return {'total': total, 'page': p, 'list': users}
示例#18
0
async def index(*,
                keyword=None,
                rangeDate=None,
                status=None,
                isSearch=None,
                page=1,
                pageSize=10):

    page = int(page)
    pageSize = int(pageSize)

    # 合计收入金额
    totalMoney = 0
    # 合计结算金额
    totalBalance = 0

    where = "s.is_delete = 0"
    if keyword:
        where = "{} and i.income_id like '%%{}%%' or c.name like '%%{}%%'".format(
            where, keyword, keyword)
    if status and status.isdigit():
        where = "{} and s.status = {}".format(where, status)
    if rangeDate:
        startDate, endDate = rangeDate.split(' - ')
        if startDate and endDate:
            where = "{} and aff_date >= '{}' and aff_date < '{}'".format(
                where, startDate, endDate)

    # 获得总条数和分页数
    sql = sqlTpl.format('count(*) c', where)
    rs = await Settlement.query(sql)
    total, limit, p = totalLimitP(rs, page, pageSize)
    if total == 0:
        return dict(total=total,
                    page=p,
                    list=(),
                    other={
                        'statusMap': statusMap,
                        'totalMoney': 0,
                        'totalBalance': 0
                    })

    # 查询列表数据
    where = " %s order by %s limit %s" % (where, 's.status asc, s.id desc',
                                          limit)
    sql = sqlTpl.format(selectField, where)
    lists = await Settlement.query(sql)

    # 将获得数据中的日期转换为字符串
    lists = obj2str(lists)

    for item in lists:
        statusDate = item['add_date']
        item['status_text'] = statusMap[item['status']]
        if int(item['status']) == 1:
            statusDate = item['finished_time']

        item['status_text'] = "%s<br/>%s" % (item['status_text'], statusDate)
        item['invoice'] = replLineBreak(item['invoice'])
        item['stype_text'] = stypeMap[item['stype']]
        totalMoney += item['money']
        totalBalance += item['balance']

    return {
        'total': total,
        'page': p,
        'list': lists,
        'other': {
            'statusMap': statusMap,
            'totalMoney': round(totalMoney, 2),
            'totalBalance': round(totalBalance, 2),
        }
    }
示例#19
0
async def board_index(*,
                      keyword=None,
                      rangeDate=None,
                      moneyStatus=None,
                      invStatus=None,
                      mediaType=None,
                      isExport=None,
                      page=1,
                      pageSize=10):
    page = int(page)
    pageSize = int(pageSize)
    totalMoney = 0
    affField = "aff_date"
    where = "where  inc.is_delete = 0 and c.is_delete = 0 "

    if keyword:
        where = "{}  and inc.income_id like '%%{}%%' or c.name like '%%{}%%'".format(
            where, keyword, keyword)

    localtimes = time.localtime()
    currYear = localtimes[0]
    currMonth = localtimes[1]
    if not rangeDate or rangeDate.find(' - ') != 7:
        endYear = currYear
        endMonth = currMonth + 1
        if currMonth == 13:
            endMonth = 1
            endYear += 1

        startDate = "%s-%s" % (currYear, str(currMonth).zfill(2))
        endDate = "%s-%s" % (endYear, str(endMonth).zfill(2))
    if rangeDate:
        startDate, endDate = rangeDate.split(' - ')
        if startDate == endDate:
            where = " {} and {} = '{}' ".format(where, affField, startDate)
        else:
            where = " {} and {} >= '{}' and {} <= '{}' ".format(
                where, affField, startDate, affField, endDate)
    if invStatus:
        where = "{} and inv_status={} ".format(where, int(invStatus))
    if mediaType:
        where = "{} and media_type={} ".format(where, int(mediaType))
    if moneyStatus:
        where = "{} and money_status={} ".format(where, int(moneyStatus))

    # if not isExport or int(isExport) != 1:
    #     sql = '%s limit %s' % (sql, limit)

    limit = "%s,%s" % ((page - 1) * pageSize, pageSize)
    sql_total = 'select count(*) cc from income inc inner join client c on inc.client_id = c.id %s' % (
        where)
    re = await Income.query(sql_total)
    total = re[0]["cc"]
    p = (math.ceil(total / pageSize), page)
    if total == 0:
        return dict(total=total,
                    page=(0, 0),
                    list=(),
                    other={'totalMoney': round(totalMoney, 2)})

    sql_re = 'SELECT inc.comments,inc.cost,inc.income_id,c.name,inc.business_type,inc.name cname,inc.aff_date,inc.money,inc.money_status,inc.inv_status,inc.media_type,inc.id income_table_id,inc.income_company,inc.return_money_date from income inc inner join client c on inc.client_id = c.id ' + where + 'order by  inc.income_id  desc limit %s' % (
        limit)
    res = await Income.query(sql_re)
    res = obj2str(res)
    for item in res:
        # item['status'] = statusMap[item['status']]
        item['media_type'] = mediaTypeMap[item['media_type']]
        totalMoney = totalMoney + item['money']

    if isExport and int(isExport) == 1 and rangeDate:
        startDate, endDate = rangeDate.split(' - ')
        if startDate == endDate:
            where_t = " {} and {} = '{}' ".format(where, affField, startDate)
        else:
            where_t = " {} and {} >= '{}' and {} <= '{}' ".format(
                where, affField, startDate, affField, endDate)
        sql_re_t = 'SELECT inc.comments,inc.cost,inc.income_id,c.name,inc.business_type,inc.name cname,inc.aff_date,inc.money,inc.money_status,inc.inv_status,inc.media_type,inc.id income_table_id,inc.income_company,inc.return_money_date from income inc inner join client c on inc.client_id = c.id ' + where_t + 'order by  inc.income_id  desc'
        res_t = await Income.query(sql_re_t)
        res_t = obj2str(res_t)
        for item in res_t:
            if item["money_status"] == 0:
                item["money_status"] = "未回款"
            if item["money_status"] == 1:
                item["money_status"] = "已回款"
            if item["inv_status"] == 0:
                item["inv_status"] = "未开票"
            if item["inv_status"] == 1:
                item["inv_status"] = "不开票"
            if item["inv_status"] == 2:
                item["inv_status"] = "已开票"
        return await export(res_t)

    if isExport and int(isExport) == 1:
        for item in res:
            if item["money_status"] == 0:
                item["money_status"] = "未回款"
            if item["money_status"] == 1:
                item["money_status"] = "已回款"
            if item["inv_status"] == 0:
                item["inv_status"] = "未开票"
            if item["inv_status"] == 1:
                item["inv_status"] = "不开票"
            if item["inv_status"] == 2:
                item["inv_status"] = "已开票"
        return await export(res)

    return {
        'total': total,
        'page': p,
        'list': res,
        'other': {
            'moneyStatusMap': moneyStatusMap,
            'invStatusMap': invStatusMap,
            'mediaTypeMap': mediaTypeMap,
            'totalMoney': round(totalMoney, 2)
        }
    }
示例#20
0
async def invoiceApply_index(*, keyword=None,rangeDate=None,isExport=None,isSearch=None, page=1, pageSize=10):
    page = int(page)
    pageSize = int(pageSize)

    sql_total = 'select count(*)  co  from invoice where is_delete = 0'
    try:
        rs = await Invoice.query(sql_total)
        if rs[0]["co"] == 0:
            return dict(total=0, page=(0, 0), list=())
    except:
        raise ValueError("查询数据库错误,/apis/invoiceApply_index/index")
    total = rs[0]["co"]

    limit = ((page - 1) * pageSize, pageSize)
    p = (math.ceil(total / pageSize), page)
    #页面大小问题考虑不了
    sql_res1 = 'select inv.income_id income_id_ids,inv.id invid,inv.info,inv.finished,inv.finished_time,inv.comments from invoice  inv where is_delete = 0  order by inv.id desc limit %s,%s '  %(limit[0],limit[1])
    try:
        res1 = await Invoice.query(sql_res1)
    except:
        raise ValueError("/apis/invoiceApply_index/index,应该是表字段有变化,total查询已经通过了")
    res1 = obj2str(res1)
    res = []
    for i in res1:
        i["info"] = i["info"].replace('\n', '<br/>')
        income_ids = i["income_id_ids"].split(",")
        if len(income_ids) == 1:
                sql_res2 = 'SELECT c.name,inc.aff_date,inc.income_id,inc.money,inc.income_company FROM income inc INNER JOIN `client` c ON inc.`client_id` = c.id where inc.id = %s' %(income_ids[0])
                try:
                    res2 = await  Income.query(sql_res2)
                except:
                    raise ValueError("/apis/invoiceApply_index/index,二次查询错误")
                if i["comments"]:
                    i["comments"] = i["comments"].replace('\n', '<br/>')
                i["show"] = 1
                i["rowspan"] = 1
                i["name"] = res2[0]["name"]
                i["aff_date"] = res2[0]["aff_date"]
                i["income_id"] = res2[0]["income_id"]
                i["money"] = res2[0]["money"]
                i["income_company"] = res2[0]["income_company"]
                if i["finished"] == 0:
                    res.insert(0,i)
                else:
                    res.append(i)
        else:
            for j in income_ids:
                sql_res2 = 'SELECT c.name,inc.aff_date,inc.income_id,inc.money,inc.income_company FROM income inc INNER JOIN `client` c ON inc.`client_id` = c.id where inc.id = %s' % (j)
                try:
                    res2 = await Income.query(sql_res2)
                except:
                    raise ValueError("/apis/invoiceApply_index/index,二次查询错误")
                tmp = {}
                tmp["invid"] = i["invid"]
                tmp["info"] = i["info"]
                tmp["finished"] = i["finished"]
                tmp["finished_time"] = i["finished_time"]
                if i["comments"]:
                    tmp["comments"] = i["comments"].replace('\n', '<br/>')
                tmp["name"] = res2[0]["name"]
                tmp["aff_date"] = res2[0]["aff_date"]
                tmp["income_id"] = res2[0]["income_id"]
                tmp["money"] = res2[0]["money"]
                tmp["income_company"] = res2[0]["income_company"]
                if  income_ids.index(j) == 0:
                    tmp["show"] = 1
                    tmp["rowspan"] = len(income_ids)
                    if tmp["finished"] == 0:
                        res.insert(0,tmp)
                    else:
                        res.append(tmp)
                else:
                    tmp["show"] = 0
                    if tmp["finished"] ==0:
                        res.insert(int(income_ids.index(j)),tmp)
                    else:
                        res.append(tmp)

    if keyword  and isSearch:
        search_res = []
        search_total = 0
        cname = keyword.strip()
        for sear in res:
            if sear["name"] == cname:
                search_res.append(sear)
        search_total = len(search_res)
        p = (math.ceil(search_total / pageSize), page)
        if isExport == 1:
            for item in search_res:
                if item["finished"] == 0:
                    item["finished"] = "否"
                if item["finished"] == 1:
                    item["finished"] = "是"
            return await export(res)

        return {
            'total': search_total,
            'page': p,
            'list': search_res
        }
    if rangeDate or (keyword and isSearch):
        search_res = []
        search_total = 0
        start_date = rangeDate.split(" - ")[0]
        start_date = time.strptime(start_date,'%Y-%m')
        end_date = rangeDate.split(" - ")[1]
        end_date = time.strptime(end_date,'%Y-%m')
        for search_date in res:
            if time.strptime(search_date["aff_date"],'%Y-%m') >= start_date and time.strptime(search_date["aff_date"],'%Y-%m') <= end_date:
                search_res.append(search_date)
        search_total = len(search_res)
        p = (math.ceil(search_total / pageSize), page)
        if isExport == 1:
            for item in search_res:
                if item["finished"] == 0:
                    item["finished"] = "否"
                if item["finished"] == 1:
                    item["finished"] = "是"
            return await export(res)
        return {
            'total': search_total,
            'page': p,
            'list': search_res
        }

    if isExport:
        for item in res:
            if item["finished"] == 0:
                item["finished"] = "否"
            if item["finished"] == 1:
                item["finished"] = "是"
        return await export(res)

    return {
        'total':total,
        'page':p,
        'list':res
    }
示例#21
0
async def index(*,
                keyword=None,
                rangeDate=None,
                status=None,
                page=1,
                pageSize=10):
    page = int(page)
    pageSize = int(pageSize)
    year = time.strftime('%Y')

    # 合计金额
    totalMoney = 0

    where = "inv.is_delete = 0"
    if keyword:
        where = "{} and (i.income_id like '%%{}%%' or c.name like '%%{}%%')".format(
            where, keyword, keyword)
    if status and status.isdigit():
        where = "{} and finished = {}".format(where, status)
    if rangeDate:
        startDate, endDate = rangeDate.split(' - ')
        if startDate and endDate:
            where = "{} and aff_date >= '{}' and aff_date < '{}'".format(
                where, startDate, endDate)

    sql = sqlTpl.format('count(*) c', where)
    rs = await Invoice.query(sql)

    total, limit, p = totalLimitP(rs, page, pageSize)
    if total == 0:
        return dict(total=total,
                    page=p,
                    list=(),
                    other={
                        'statusMap': statusMap,
                        'totalMoney': round(totalMoney, 2)
                    })

    where = " %s order by %s limit %s" % (
        where, 'inv.finished asc, inv.id desc', limit)
    sql = sqlTpl.format(selectField, where)
    lists = await Invoice.query(sql)

    # 将获得数据中的日期转换为字符串
    lists = obj2str(lists)

    for item in lists:
        statusDate = item['add_date']
        item['status_text'] = statusMap[item['finished']]
        if int(item['finished']) == 1:
            statusDate = item['finished_time']

        item['status_text'] = "%s<br/>%s" % (item['status_text'], statusDate)
        item['info'] = replLineBreak(item['info'])
        item['comments'] = replLineBreak(item['comments'])
        totalMoney += item['money']

        if item['in_id'].find(',') > 0:
            income_ids = await Income.findCols('income_id',
                                               "id in (%s)" % item['in_id'])
            if income_ids:
                item['income_id'] = ','.join(income_ids)

    return {
        'total': total,
        'page': p,
        'list': lists,
        'other': {
            'statusMap': statusMap,
            'totalMoney': round(totalMoney, 2)
        }
    }