swhere=f"company_id={company_id} and agent_id={agent_id} and tm::date >= '{dt_fr}' and tm::date <= '{dt_to}'"
elifuser_id:
swhere=f"company_id={company_id} and user_id={user_id} and is_need_dispatch = true and is_permit = true and tm::date >= '{dt_fr}' and tm::date <= '{dt_to}'"
(select wx_headimgurl from sales_consumeraccount where id = consumer_id),
(select wx_nickname from sales_consumeraccount where id = consumer_id),
is_need_dispatch,
is_dispatched,
is_need_money_return,
is_money_returned,
remark,--10
tm,
is_permit,
coalesce((select username from company_user where id = applyer_id),''),
coalesce((select label_code from sales_consumerwinner where id = winner_id),''),
(select (select name from company_level where id = c.level_id) from company_company c where name=agent_name and ancestor_id = company_id ),
coalesce((select last_name from company_user where id = applyer_id),''),
(select (select name from company_company where id = c.parent_id) from company_company c where id=agent_id and ancestor_id = company_id),
(select (select ((select name from company_level where id = up_c.level_id)) from company_company up_c where id = c.parent_id) from company_company c where id=agent_id and ancestor_id = company_id )
FROM sales_hexiao_record WHERE
company_id = """+company_id+""" and is_agent_writeoff=False and is_need_agent_writeoff=True and
(tm BETWEEN '"""+dt_fr+"""' and '"""+dt_to+"""') order by id desc""")