Commit 587d15cd by 王昆

gsb

parent 21b11b0a
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
var rule =require("../../../utils/invoiceRule/rule");
var Context =require("../../../utils/stateChain/context");
var Calculation = require("../../../utils/strategies/calculation");
// var rule =require("../../../utils/invoiceRule/rule");
// var Context =require("../../../utils/stateChain/context");
// var Calculation = require("../../../utils/strategies/calculation");
class ActionAPI extends APIBase {
constructor() {
super();
this.iinvoiceSve = system.getObject("service.invoice.iinvoiceSve");
this.context=new Context();
// this.context=new Context();
}
/**
* 接口跳转
......@@ -30,13 +30,13 @@ class ActionAPI extends APIBase {
var opResult = null;
switch (action_type) {
case "invoiceApply": // 发票申请
opResult = await rule.dispatcher(action_body);
// opResult = await rule.dispatcher(action_body);
break;
case "invoicePage": // 发票申请列表页(平台)
opResult = await rule.dispatcher(action_body);
// opResult = await rule.dispatcher(action_body);
break;
case "deliverInvoicePage": // 发票申请列表页(交付商)
opResult = await rule.dispatcher(action_body);
// opResult = await rule.dispatcher(action_body);
break;
case "handleStatus": //进度处理
break;
......@@ -132,7 +132,7 @@ class ActionAPI extends APIBase {
// break;
case "test": // 查询业务进度
opResult = await this.iinvoiceSve.allNames(action_body);
opResult = await this.iinvoiceSve.buildOrderProcess(action_body);
break;
default:
......
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const moment = require('moment');
var rule =require("../../../utils/invoiceRule/rule");
const Decimal = require('decimal.js');
class ApplyService extends ServiceBase {
class ApplyService {
constructor() {
super("invoice", ServiceBase.getDaoName(ApplyService));
let is = system.getObject("util.invoiceStatus");
this.invoiceStatus = is.status;
this.delivererDao = system.getObject("db.invoice.delivererDao");
this.invoiceDao = system.getObject("db.invoice.invoiceDao");
//最大的发票总额度
this.MAX_TOTAL_AMOUNT = 500000000;
//警告发票额度
this.WARNING_AMOUNT = 400000000;
this.PER_TAX = 1; //个税
this.VAL_TAX = 2; //增值税
this.INVOICE_MAX = 10; //一次性插入最大值
}
/**
* 保存发票信息
*/
async apiSaveInvoice(params) {
try {
let res = await this.saveInvoice(params);
return res;
} catch (error) {
return system.getResult(null, `系统错误 错误信息:${error}`);
}
}
/**
* 查询申请列表(平台)
* @param {*} params
*/
async apiQueryApplyInvoices(params) {
try {
return await this.queryApplyInvoices(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 查询发票明细(平台)
* @param {*} params
*/
async apiQueryInvoice(params) {
try {
var merchantId = params.merchantId || params.merchant_id;
if ((params.merchantId && params.applyNo) || params.id) {
let res = await this.queryInvoice(params.applyNo, merchantId, params.id);
return res;
} else {
return system.getResultSuccess();
}
} catch (error) {
return system.getResult(null, `系统错误 错误信息:${error}`);
}
}
/**
* 发票撤回
* @param params
* {
* applyNo:"", //发票申请编号
* merchantId:"", //商户id
* }
*/
async apiCancelInvoice(params) {
try {
var merchantId = params.merchantId || params.merchant_id;
if (!params.applyNo || !merchantId) {
return system.getResult(null, "发票申请编号不合法。");
}
return await this.cancelInvoice(params.applyNo, merchantId);
} catch (error) {
return system.getResult(null, `系统错误:错误信息 ${error}`);
}
}
/**
* 平台业务分配
* @param {*} params
* {
* id:"xxx" //发票id
* nextStatus:"xxx", //发票状态
*
* }
*/
async apiAssignment(params) {
try {
if (!params.id) {
return system.getResult(null, `参数错误`);
}
return await this.assignment(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 平台业务分配
* @param {*} params
* {
* id:"xxx" //发票id
* nextStatus:"xxx", //发票状态
*
* }
*/
async apiVerificationByBusinessmenCreditCode(params) {
try {
if (!params.businessmenCreditCode) {
return system.getResult(null, `参数错误`);
}
return await this.verificationByBusinessmenCreditCode(this.trim(params.businessmenCreditCode));
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 发票红冲
* @param {*} params
*/
async apiRedRushInvoice(params) {
if (!params.id) {
return system.getResult(null, `参数错误 发票ID不合法`);
}
try {
let res = await this.redRushInvoice(params);
return res;
} catch (error) {
return system.getResult(null, `参数错误 错误信息 ${error}`);
}
}
/**
* 交易数据(平台)
* @param {*} params
*/
async apiStatTransData(params) {
try {
return await this.statTransData(params);
} catch (error) {
return system.getResult(-1, `系统错误 错误信息 ${error}`);
}
}
/**
* 发票办理(平台)
* @param {*} params
*/
async apiStatBusinessData(params) {
try {
return await this.statBusinessData(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
//===========================================================================================
/**
* 插入发票
* @param {*} params
*/
async saveInvoice(params) {
try {
//试算
let val = await rule.dispatcher(params);
if(val.data==-1){
return system.getResult(-1,`系统错误 ${val.msg}`);
}
params.personalIncomeTax = this.trim(val.personalIncomeTax);
params.additionalTax = this.trim(val.additionalTax);
params.valueAddedTax = this.trim(val.valueAddedTax);
params.serviceCharge = this.trim(val.serviceCharge);
params.isPay = (params.isPay) ? 1 : 0;
params.status = "1000";
params.customerStatus = "1000";
params.ruleCode = this.trim(params.ruleCode);
params.ruleParams = JSON.stringify(params);
await this.db.transaction(async (t) => {
//插入发票申请单
let _apply = await this.dao.create(params, t);
//插入一条发票信息
await this.invoiceDao.model.create({
id: _apply.id,
applyNo: _apply.applyNo,
merchantId: _apply.merchantId,
businessmenId: params.businessmenId,
businessmenType: params.businessmenType,
ruleCode: params.ruleCode,
ruleParams: params.ruleParams
}, t);
});
return system.getResultSuccess();
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 发票办理(平台)
* @param {*} params
*/
async statBusinessData(params) {
var result = {};
var type = Number(params.type || 1);
// 查 已完成订单,待分配订单,待审核订单,办理中订单
var begin, end;
// 取开始时间
if (type == 1) {
begin = moment().format("YYYY-MM") + "-01 00:00:00";
end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
} else if (type == 2) {
begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
}
// 先按照订单状态查
var statMap = await this.dao.statByStatus(begin, end);
// 已开具 1050
result.completeCount = this.addStatCount(statMap, ['1050']);
// 待申请审核 1000
result.toApplyCount = this.addStatCount(statMap, ['1000']);
// 待交付审核 1130 1140
result.toAuditCount = this.addStatCount(statMap, ['1060']);
// 办理中 "1030", "1050", "1060", "1080", "1300"
result.handlingCount = this.addStatCount(statMap, ["1030", "1050", "1060", "1080", "1300"]);
return system.getResultSuccess(result);
}
/**
* 交易数据(平台)
* @param {*} params
*/
async statTransData(params) {
try {
var result = {
invoiceCount: 0,
serviceChange: 0,
};
var type = Number(params.type || 1);
var begin, end;
// 取开始时间
if (type == 1) {
begin = moment().format("YYYY-MM") + "-01 00:00:00";
} else if (type == 2) {
begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
}
// echart数据
var days = [];
var dayCounts = [];
var priceCounts = [];
// 处理查询业务
if (type == 1 || type == 2) { // 取结束时间
end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
days = this.getDays(end);
// 按天统计
var dayMap = await this.dao.statDayByTime(begin, end);
for (var day of days) {
var ditem = dayMap[day] || {};
dayCounts.push(ditem.invoiceCount || 0);
priceCounts.push(system.f2y(ditem.serviceChange || 0));
}
} else {
var monthMap = await this.dao.statMonthByTime(begin, end);
var bm = monthMap.begin || "";
var em = monthMap.end || "";
if (bm && em) {
// 开始月份-结束月份所有月份
var curMonth = bm;
while (true) {
days.push(curMonth);
if (curMonth == em) {
break;
}
curMonth = moment(curMonth + "-01").add(1, "month").format("YYYY-MM");
}
}
for (var day of days) {
var ditem = monthMap[day] || {};
dayCounts.push(ditem.invoiceCount || 0);
priceCounts.push(system.f2y(ditem.serviceChange || 0));
}
}
var invoiceApplyData = await this.dao.statInvoiceByTime(begin, end) || {};
result.invoiceCount = invoiceApplyData.invoiceCount;
result.serviceChange = system.f2y(invoiceApplyData.serviceChange);
result.days = days;
result.dayCounts = dayCounts;
result.priceCounts = priceCounts;
return system.getResultSuccess(result);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 红冲
* @param {*} params
*/
async redRushInvoice(params) {
try {
let _apply = await this.dao.findById(params.id) || {};
let invoice = await this.invoiceDao.findById(params.id) || {};
//判断红冲状态
if (invoice.redStatus == 2) {
return system.getResult(null, `发票红冲中`);
} else if (invoice.redStatus == 4) {
return system.getResult(null, `红冲已红冲`);
}
let nowObj = {};
nowObj.merchantId = this.trim(_apply.merchantId);
nowObj.merchantName = this.trim(_apply.merchantName);
nowObj.merchantCreditCode = this.trim(_apply.merchantCreditCode);
nowObj.merchantAddr = this.trim(_apply.merchantAddr);
nowObj.merchantMobile = this.trim(_apply.merchantMobile);
nowObj.merchantBank = this.trim(_apply.merchantBank);
nowObj.merchantAccount = this.trim(_apply.merchantAccount);
nowObj.businessmenCreditCode = this.trim(_apply.businessmenCreditCode);
nowObj.businessmenId = this.trim(_apply.businessmenId);
nowObj.businessmenName = this.trim(_apply.businessmenName);
nowObj.businessmenAddr = this.trim(_apply.businessmenAddr);
nowObj.businessmenMobile = this.trim(_apply.businessmenMobile);
nowObj.businessmenBank = this.trim(_apply.businessmenBank);
nowObj.businessmenAccount = this.trim(_apply.businessmenAccount);
nowObj.isBank = _apply.isBank ? 1 : 0;
nowObj.taxAuthorities = this.trim(_apply.taxAuthorities);
nowObj.type = this.trim(_apply.type);
nowObj.invoiceAmount = this.trim(_apply.invoiceAmount);
nowObj.statements = this.trim(_apply.statements);
nowObj.contract = this.trim(_apply.contract);
nowObj.invoiceTime = this.trim(_apply.invoiceTime);
nowObj.settleImg = this.trim(_apply.settleImg);
nowObj.applyNo = this.trim(_apply.applyNo);
nowObj.invoiceConten = this.trim(_apply.invoiceConten);
nowObj.personalIncomeTax = this.trim(_apply.personalIncomeTax);
nowObj.additionalTax = this.trim(_apply.additionalTax);
nowObj.valueAddedTax = this.trim(_apply.valueAddedTax);
nowObj.serviceCharge = this.trim(_apply.serviceCharge);
nowObj.applyMobile = this.trim(_apply.applyMobile);
nowObj.parentId = this.trim(_apply.id);
nowObj.status = this.trim("1000");
nowObj.customerStatus = this.trim("1000");
nowObj.payWay = this.trim(_apply.payWay);
nowObj.payAccount = this.trim(_apply.payAccount);
nowObj.mailAddr = this.trim(_apply.mailAddr);
nowObj.mailMobile = this.trim(_apply.mailMobile);
nowObj.mailTo = this.trim(_apply.mailTo);
nowObj.remark = this.trim("");
nowObj.delivererId = this.trim("");
nowObj.isPay = 0;
nowObj.businessmenType = this.trim(_apply.businessmenType);
nowObj.ruleCode = this.trim(_apply.ruleCode);
nowObj.ruleParams = this.trim(_apply.ruleParams);
let res = await this.db.transaction(async (t) => {
// 插入发票申请单
let _nowObj = await this.dao.create(nowObj, t);
// 插入一条发票信息
await this.invoiceDao.create({
id: _nowObj.id,
applyNo: _nowObj.applyNo,
merchantId: _nowObj.merchantId,
red_status: '1',
businessmenType : nowObj.businessmenType,
ruleCode : nowObj.ruleCode,
ruleParams : nowObj.ruleParams
}, t);
// 源发票改为红冲办理中
var updfields = {
redStatus: '2',
id: _apply.id,
}
await this.invoiceDao.update(updfields, t);
});
return system.getResultSuccess();
} catch (error) {
console.log(error);
return system.getResult(null, `参数错误 错误信息 ${error}`);
}
}
async getByApplyNo(params) {
var merchantId = params.merchantId || params.merchant_id;
var applyNo = params.applyNo;
var item = await this.dao.getByApplyNo(merchantId, applyNo);
if (item) {
this.handleDate(item, ["created_at", "updated_at"], null, -8);
}
return system.getResultSuccess(item);
}
/**
* 查询发票明细
* @param {*} applyNo
* @param {*} merchantId
*/
async queryInvoice(applyNo, merchantId, id) {
try {
let _apply;
if (merchantId && applyNo) {
_apply = await this.dao.model.findOne({
where: {
merchantId: merchantId,
applyNo: applyNo
},
raw: true
});
} else if (id) {
_apply = await this.dao.model.findOne({
where: {
id: this.trim(id)
},
raw: true
});
} else {
_apply = null;
}
if (!_apply) {
return system.getResult(null)
}
this.dao.setRowCodeName(_apply, "status");
this.dao.setRowCodeName(_apply, "customerStatus");
//查询平台审批内容
let deliverer = await this.delivererDao.model.findOne({
where: {
id: _apply.delivererId
},
raw: true
});
_apply.deliverer = deliverer;
//查询发票信息
let invoice = await this.invoiceDao.model.findOne({
where: {
id: _apply.id
},
raw: true
});
this.dao.setRowCodeName(invoice, "status");
//红冲关联
let parentInvoice = await this.dao.model.findOne({
where: {
id: _apply.parentId
},
raw: true
});
this.dao.setRowCodeName(parentInvoice, "status");
this.dao.setRowCodeName(parentInvoice, "customerStatus");
_apply.invoice = invoice;
_apply.deliverer = deliverer || {};
_apply.parentInvoice = parentInvoice;
this.handleDate(_apply.invoice, ["taxTime", "invoiceTime"], "YYYY-MM-DD");
return system.getResult(_apply);
} catch (error) {
return system.getResult(null, `系统错误 错误信息:${error}`);
}
}
/**
* 发票撤回
* @param {*} applyNo
* @param {*} merchantId
* @param
*/
async cancelInvoice(applyNo, merchantId) {
let _invoice = await this.dao.model.findOne({
where: {
applyNo: applyNo,
merchantId: merchantId
},
attributes: ['id', 'status']
});
if (_invoice.status != this.invoiceStatus.unpay) {
return system.getResult(null, `当前发票正在处理,不能撤回`);
} else {
_invoice.status = this.invoiceStatus.recall;
try {
let res = await _invoice.save();
return system.getResult(res);
} catch (error) {
return system.getResult(null, `系统错误: ${error}`);
}
}
}
/**
* 发票业务分配
* @param {*} params
* {
* id:"" //发票id
* nextStatus:"" //发票状态
* }
*/
async assignment(params) {
let _apply = await this.verification(params);
try {
let res;
switch (params.nextStatus) {
case "1010": //审核不通过
res = await this.examine1000(params, _apply);
break;
case "1020": //待分配
res = await this.examine1000(params, _apply);
break;
case "1030": //待处理
res = await this.examine1030(params, _apply);
break;
case "1070": //审核通过
res = await this.examine1070(params, _apply);
break;
case "1300": //审核失败
res = await this.examine1300(params, _apply);
break;
case "1090": //已完成
res = await this.examine1090(params, _apply);
break;
default:
res = system.getResult(null, "action_type参数错误");
break;
}
return res;
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 第一次审核
* @param {*} params
* {
* id: xxx, //发票id
* isPay:1, //时候付款
* nextStatus:1020,//发票状态
* remark:""//发票标注
* }
*/
async examine1000(params, _apply) {
if (Number(params.isPay) != 1) {
return system.getResult(null, `参数错误 请核对付款信息`);
}
params.nextStatus = this.trim(params.nextStatus);
params.remark = this.trim(params.remark);
_apply.status = params.nextStatus;
_apply.remark = params.remark;
_apply.isPay = Number(params.isPay);
if (params.nextStatus == "1010") {
_apply.customerStatus = "1010";
}
try {
let res = await _apply.save();
if (_apply.parentId && params.nextStatus == "1010") {
await this.invoiceDao.update({ id: _apply.parentId, redStatus: '3' });
}
return system.getResultSuccess();
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 待处理 (当前状态待分配或者是审核为通过)
* @param {*} params
* {
* id: xxx, //发票id
* delivererId:1, //交付商
* nextStatus:examine1020,//发票状态
* delivererName:""//交付商名称
* delivererAmount:"" //分成
* }
*/
async examine1030(params, _apply) {
if (!params.id || !params.delivererName) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
await this.db.transaction(async (t) => {
let _deliverer = await this.delivererDao.create({
invoiceId: _apply.id,
applyNo: _apply.applyNo,
merchantId: _apply.merchantId,
delivererId: this.trim(params.delivererId),
delivererName: this.trim(params.delivererName),
delivererAmount: Number(this.trim(params.delivererAmount))
}, t);
let applyData = {};
applyData.status = this.trim(params.nextStatus);
applyData.customerStatus = this.trim(params.nextStatus);
applyData.delivererId = this.trim(_deliverer.id);
applyData.id = this.trim(params.id);
//更新申请发票内容
await this.dao.update(applyData, t);
//更改发票状态
let invoiceData = {};
invoiceData.status = this.trim(params.nextStatus);
invoiceData.id = this.trim(params.id);
await this.invoiceDao.update(invoiceData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
/**
* 第二次审核
* @param {*} params
* {
* id: xxx, //发票id
* auditContent:1, //审核备注
* nextStatus:1070,//发票状态
* delivererContent:""//发票内容
* mailAddr:"", //邮寄地址
* mailMobile:"", //邮寄电话
* mailTo:"", //邮寄人
* }
*/
async examine1070(params, _apply) {
let delivererData = {},
applyData = {},
invoiceData = {};
let _deliverer = await this.delivererDao.findOne({
id: _apply.delivererId
});
delivererData.auditContent = this.trim(params.auditContent);
delivererData.delivererContent = this.trim(params.delivererContent);
delivererData.mailAddr = this.trim(params.mailAddr);
delivererData.mailMobile = this.trim(params.mailMobile);
delivererData.mailTo = this.trim(params.mailTo);
delivererData.mailEmail = this.trim(params.mailEmail);
delivererData.id = this.trim(_deliverer.id);
applyData.status = this.trim(params.nextStatus);
applyData.id = this.trim(params.id);
invoiceData.status = this.trim(params.nextStatus);
invoiceData.id = this.trim(params.id);
await this.db.transaction(async (t) => {
//更新deliverer信息
await this.delivererDao.update(delivererData, t);
//更新 申请单和发票单
await this.dao.update(applyData, t);
await this.invoiceDao.update(invoiceData, t);
if (_apply.parentId) {
await this.invoiceDao.update({ id: _apply.parentId, redStatus: '4' }, t);
}
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
/**
* 第二次审核失败
* @param {*} params
*/
async examine1300(params) {
let _apply = await this.dao.findOne({
id: this.trim(params.id)
});
if (!_apply) {
return system.getResult(null, `发票不存在,请核对发票ID`);
}
let _deliverer = await this.delivererDao.model.findOne({
where: {
id: _apply.delivererId
}
});
if (!_deliverer) {
return system.getResult(null, `交付商不存在,请联系管理员`);
}
await this.db.transaction(async (t) => {
//更新 申请单和发票单
await this.dao.update({
status: "1300",
id: _apply.id
}, t);
await this.invoiceDao.update({
status: "1300",
id: _apply.id
}, t);
if (_deliverer.id) {
//提交审核信息
await this.delivererDao.update({
auditContent: this.trim(auditContent),
id: _deliverer.id
});
}
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
/**
* 平台更新 已完成状态
* @param {*} params
* @param {*} _apply
*/
async examine1090(params, _apply) {
let applyData = {};
applyData.status = this.trim(params.nextStatus);
applyData.customerStatus = this.trim(params.nextStatus);
applyData.id = this.trim(params.id);
// invoiceData.status = this.trim(params.nextStatus);
// invoiceData.id=this.trim(params.id);
await this.db.transaction(async (t) => {
//更新 申请单和发票单
await this.dao.update(applyData, t);
// await this.invoiceDao.update(invoiceData,t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
/**
* 检查状态是否正确
* @param {*} params
* {
* id:xxx //发票id
* nextStatus:xxx //发票状态
* }
*/
async verification(params) {
let _apply = await this.dao.findOne({
id: this.trim(params.id)
});
if (!_apply) {
return system.getResult(null, `此发票不存在`);
}
//获取当前状态 的对象
let _status = this.invoiceStatus[_apply.status];
//如果不符合状态则退出
if (params.nextStatus == "1300" || params.nextStatus == "1040" || params.nextStatus == "1010") {
return _apply;
}
if (!_status && _status.next != params.nextStatus) {
let name = this.invoiceStatus[this.invoiceStatus[_apply.status].next].name;
return system.getResult(null, `更新状态错误,提示:当前状态的下一个状态是 ${name}`);
}
return _apply;
}
/**
* 发票申请列表查询(平台)
* @param {*} params
* @param applyNo 发票的申请编号
* @param invoiceTime 发票的申请时间
* @param type 发票的类型
* @param status 业务进度
*/
async queryApplyInvoices(params) {
let where = {};
if (this.trim(params.applyNo)) {
where.applyNo = this.trim(params.applyNo);
}
if (this.trim(params.businessmenCreditCode)) {
where.businessmenCreditCode = this.trim(params.businessmenCreditCode);
}
if (this.trim(params.invoiceTime)) {
where.invoiceTime = {
[this.db.Op.gte]: this.trim(params.invoiceTime)
}
}
if (this.trim(params.type)) {
where.type = this.trim(params.type);
}
if (this.trim(params.status)) {
where.status = this.trim(params.status);
}
let pageIndex = params.pageIndex || 1;
let pageSize = params.pageSize || 10;
let orderObj = [
// ['updatedAt', 'desc'],
['id', 'desc']
];
try {
let _apply = await this.dao.getPageList(pageIndex, pageSize, where, orderObj, null, null);
for (let item of _apply.rows) {
let _deliverer = await this.delivererDao.model.findOne({
// where: {
// delivererId: item.delivererId
// },
attributes: ['delivererName']
});
if (_deliverer) {
item.delivererName = _deliverer.delivererName;
} else {
item.delivererName = "";
}
if (item.type == "10") {
item.type = "普通发票";
} else if (item.type == "20") {
item.type = "增值税专用发票";
} else if (item.type == "30") {
item.type = "电子发票";
} else {
item.type = "";
}
let _invoice = await this.invoiceDao.model.findOne({
where: {
id: item.id
},
attributes: ['status', 'invoiceImg']
});
if (_invoice.status) {
this.dao.setRowCodeName(_invoice, "status");
} else {
_invoice.status = "";
}
item.invoiceImg = this.trim(_invoice.invoiceImg);
item.delivererStatus = _invoice.statusName;
//处理时间
this.handleDate(item, ["invoiceTime"], null, -8);
this.dao.setRowCodeName(item, "status");
item.isPay = item.isPay == 1 ? '已付款' : '未付款';
}
return system.getResult(_apply);
} catch (error) {
return system.getResult(`系统错误 错误信息 ${error}`);
}
}
/**
* 列举所有日期
* @param {*} end
*/
getDays(end) {
var days = [];
var month = moment(end).format("YYYY-MM");
var endDay = Number(moment(end).format("DD"));
for (var i = 1; i <= endDay; i++) {
if (i < 10) {
days.push(month + "-0" + i);
} else {
days.push(month + "-" + i);
}
}
return days;
}
addStatCount(statusMap, statuses) {
var count = 0;
if (!statuses) {
return count;
}
for (var status of statuses) {
count = count + Number(statusMap[status] || 0);
}
return count;
}
//查询发票状态 只有在状态为 '1000','0090' 或者信息不存在的情况下 验证成功 参考 applySve.verificationByBusinessmenCreditCode接口
async verificationInvoiceStatus(businessmenType, businessmenId, businessmenCreditCode) {
try {
let condition = {
businessmenType: businessmenType,
businessmenId: businessmenId,
status: {
[this.db.Op.in]: ['1000', '0090']
}
};
if (businessmenCreditCode) {
condition.businessmenCreditCode = businessmenCreditCode;
}
let invoices = await this.dao.model.findAll({
where: condition,
attributes: ["id", "status"]
});
if (!invoices) { return false; }
for (let item of invoices) {
if (!item) { continue; }
if (item['status'] != "1000" || item['status'] != "0090") {
return false;
}
}
return true;
} catch (error) {
return false;
}
}
/**
* 累计不含税价
* @param {*} businessmenId 商户id
* @param {*} taxIncPriRat 不含税价百分比
* @param {*} invoiceAmount 发票总额
* @param {*} type 计算类型 1:个税 2:增值税
* @param {*} valCalWay 增值税计算类型 1:月 2:季度 3:年
* @param {*} perCalWay 增值税计算类型 1:月 2:季度 3:年
* @param {*} invoiceTime 格式 YYYY-MM-DD hh:mm:ss
*/
async calAccumulatedPriceExcludingTax(businessmenId,businessmenType, businessmenCreditCode, taxIncPriRat, invoiceAmount, type, valCalWay, perCalWay, invoiceTime) {
try {
let now = moment(invoiceTime),startTime, attribute;
if (type === 1) { //个税
attribute = `invoiceAmount`;
if (perCalWay === 3) { //按照年
startTime = `${now.get('year')}-01-01 00:00:00`;
} else if (perCalWay === 2) { //按照季度
let quarter = now.quarter();
if (1 == quarter) { //第一季度
startTime = `${now.get('year')}-01-01 00:00:00`;
} else if (2 == quarter) {
startTime = `${now.get('year')}-04-01 00:00:00`;
} else if (3 == quarter) {
startTime = `${now.get('year')}-07-01 00:00:00`;
} else {
startTime = `${now.get('year')}-10-01 00:00:00`;
}
} else { //按照月
let _month = now.month() < 10 ? "0" + now.month() : now.month();
startTime = `${now.get('year')}-${_month}-01 00:00:00`;
}
} else {
attribute = `valueAddedTax`;
if (valCalWay === 1) { //月
startTime = `${now.get('year')}-${now.month()}-01 00:00:00`;
} else if (valCalWay === 2) { //季度
let quarter = now.quarter();
if (1 == quarter) { //第一季度
startTime = `${now.get('year')}-01-01 00:00:00`;
} else if (2 == quarter) {
startTime = `${now.get('year')}-04-01 00:00:00`;
} else if (3 == quarter) {
startTime = `${now.get('year')}-07-01 00:00:00`;
} else {
startTime = `${now.get('year')}-10-01 00:00:00`;
}
} else { //年
startTime = `${now.get('year')}-01-01 00:00:00`;
}
}
console.log("本年度开始的时间:" + startTime + " 至今:" + now.format("YYYY-MM-DD hh:mm:ss"));
let condition = {
businessmenId: businessmenId,
businessmenType:businessmenType,
status: {
[this.db.Op.in]: ['1020', '1030', '1040', '1050', '1060', '1070', '1080', '1090', '1100', '1200', '1300']
},
invoiceTime: {
[this.db.Op.between]: [startTime, now.format("YYYY-MM-DD hh:mm:ss")],
}
};
if(businessmenCreditCode){
condition.businessmenCreditCode=businessmenCreditCode;
}
let beforeAmount = await this.dao.model.sum(attribute, {
where: condition
});
beforeAmount = isNaN(beforeAmount) ? 0 : beforeAmount;
let res = new Decimal(invoiceAmount).plus(beforeAmount).div(Decimal.add(1, taxIncPriRat)).toFixed(2);
console.log("当前累计金额 :" + res);
return res;
} catch (error) {
console.log(error);
return system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
/**
* 计算累计税值
* @param {*} businessmenId
* @param {*} type 计算类型 1:个税 2:增值税
* @param {*} valCalWay 增值税计算类型 1:月 2:季度
*
*/
async calCumulativeProfit(businessmenId,businessmenType, type, valCalWay) {
let now = moment(),
startTime, attribute;
if (type == 1) {
attribute = `personalIncomeTax`;
startTime = `${now.get('year')}-01-01 00:00:00`;
} else {
attribute = `valueAddedTax`;
if (valCalWay === 1) { //月
startTime = `${now.get('year')}-${now.month()}-01 00:00:00`;
} else { //季度
let quarter = now.quarter();
if (1 == quarter) { //第一季度
startTime = `${now.get('year')}-01-01 00:00:00`;
} else if (2 == quarter) {
startTime = `${now.get('year')}-04-01 00:00:00`;
} else if (3 == quarter) {
startTime = `${now.get('year')}-07-01 00:00:00`;
} else {
startTime = `${now.get('year')}-10-01 00:00:00`;
}
}
}
console.log("本年度开始的时间:" + startTime + " 至今:" + now.format("YYYY-MM-DD hh:mm:ss"));
let cumulativeProfit = await this.dao.model.sum(attribute, {
where: {
businessmenId: businessmenId,
businessmenType: businessmenType,
status: this.invoiceStatus.auditPass,
invoiceTime: {
[this.db.Op.between]: [startTime, now.format("YYYY-MM-DD hh:mm:ss")],
}
}
});
return cumulativeProfit || 0;
}
}
module.exports = ApplyService;
\ No newline at end of file
// const system = require("../../../system");
// const ServiceBase = require("../../sve.base")
// const moment = require('moment');
// var rule =require("../../../utils/invoiceRule/rule");
// const Decimal = require('decimal.js');
// class ApplyService extends ServiceBase {
// constructor() {
// super("invoice", ServiceBase.getDaoName(ApplyService));
// let is = system.getObject("util.invoiceStatus");
// this.invoiceStatus = is.status;
// this.delivererDao = system.getObject("db.invoice.delivererDao");
// this.invoiceDao = system.getObject("db.invoice.invoiceDao");
// //最大的发票总额度
// this.MAX_TOTAL_AMOUNT = 500000000;
// //警告发票额度
// this.WARNING_AMOUNT = 400000000;
// this.PER_TAX = 1; //个税
// this.VAL_TAX = 2; //增值税
// this.INVOICE_MAX = 10; //一次性插入最大值
// }
// /**
// * 保存发票信息
// */
// async apiSaveInvoice(params) {
// try {
// let res = await this.saveInvoice(params);
// return res;
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息:${error}`);
// }
// }
// /**
// * 查询申请列表(平台)
// * @param {*} params
// */
// async apiQueryApplyInvoices(params) {
// try {
// return await this.queryApplyInvoices(params);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 查询发票明细(平台)
// * @param {*} params
// */
// async apiQueryInvoice(params) {
// try {
// var merchantId = params.merchantId || params.merchant_id;
// if ((params.merchantId && params.applyNo) || params.id) {
// let res = await this.queryInvoice(params.applyNo, merchantId, params.id);
// return res;
// } else {
// return system.getResultSuccess();
// }
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息:${error}`);
// }
// }
// /**
// * 发票撤回
// * @param params
// * {
// * applyNo:"", //发票申请编号
// * merchantId:"", //商户id
// * }
// */
// async apiCancelInvoice(params) {
// try {
// var merchantId = params.merchantId || params.merchant_id;
// if (!params.applyNo || !merchantId) {
// return system.getResult(null, "发票申请编号不合法。");
// }
// return await this.cancelInvoice(params.applyNo, merchantId);
// } catch (error) {
// return system.getResult(null, `系统错误:错误信息 ${error}`);
// }
// }
// /**
// * 平台业务分配
// * @param {*} params
// * {
// * id:"xxx" //发票id
// * nextStatus:"xxx", //发票状态
// *
// * }
// */
// async apiAssignment(params) {
// try {
// if (!params.id) {
// return system.getResult(null, `参数错误`);
// }
// return await this.assignment(params);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 平台业务分配
// * @param {*} params
// * {
// * id:"xxx" //发票id
// * nextStatus:"xxx", //发票状态
// *
// * }
// */
// async apiVerificationByBusinessmenCreditCode(params) {
// try {
// if (!params.businessmenCreditCode) {
// return system.getResult(null, `参数错误`);
// }
// return await this.verificationByBusinessmenCreditCode(this.trim(params.businessmenCreditCode));
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 发票红冲
// * @param {*} params
// */
// async apiRedRushInvoice(params) {
// if (!params.id) {
// return system.getResult(null, `参数错误 发票ID不合法`);
// }
// try {
// let res = await this.redRushInvoice(params);
// return res;
// } catch (error) {
// return system.getResult(null, `参数错误 错误信息 ${error}`);
// }
// }
// /**
// * 交易数据(平台)
// * @param {*} params
// */
// async apiStatTransData(params) {
// try {
// return await this.statTransData(params);
// } catch (error) {
// return system.getResult(-1, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 发票办理(平台)
// * @param {*} params
// */
// async apiStatBusinessData(params) {
// try {
// return await this.statBusinessData(params);
// } catch (error) {
// console.log(error);
// return system.getResult(null, "接口异常");
// }
// }
// //===========================================================================================
// /**
// * 插入发票
// * @param {*} params
// */
// async saveInvoice(params) {
// try {
// //试算
// let val = await rule.dispatcher(params);
// if(val.data==-1){
// return system.getResult(-1,`系统错误 ${val.msg}`);
// }
// params.personalIncomeTax = this.trim(val.personalIncomeTax);
// params.additionalTax = this.trim(val.additionalTax);
// params.valueAddedTax = this.trim(val.valueAddedTax);
// params.serviceCharge = this.trim(val.serviceCharge);
// params.isPay = (params.isPay) ? 1 : 0;
// params.status = "1000";
// params.customerStatus = "1000";
// params.ruleCode = this.trim(params.ruleCode);
// params.ruleParams = JSON.stringify(params);
// await this.db.transaction(async (t) => {
// //插入发票申请单
// let _apply = await this.dao.create(params, t);
// //插入一条发票信息
// await this.invoiceDao.model.create({
// id: _apply.id,
// applyNo: _apply.applyNo,
// merchantId: _apply.merchantId,
// businessmenId: params.businessmenId,
// businessmenType: params.businessmenType,
// ruleCode: params.ruleCode,
// ruleParams: params.ruleParams
// }, t);
// });
// return system.getResultSuccess();
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 发票办理(平台)
// * @param {*} params
// */
// async statBusinessData(params) {
// var result = {};
// var type = Number(params.type || 1);
// // 查 已完成订单,待分配订单,待审核订单,办理中订单
// var begin, end;
// // 取开始时间
// if (type == 1) {
// begin = moment().format("YYYY-MM") + "-01 00:00:00";
// end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
// } else if (type == 2) {
// begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
// end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
// }
// // 先按照订单状态查
// var statMap = await this.dao.statByStatus(begin, end);
// // 已开具 1050
// result.completeCount = this.addStatCount(statMap, ['1050']);
// // 待申请审核 1000
// result.toApplyCount = this.addStatCount(statMap, ['1000']);
// // 待交付审核 1130 1140
// result.toAuditCount = this.addStatCount(statMap, ['1060']);
// // 办理中 "1030", "1050", "1060", "1080", "1300"
// result.handlingCount = this.addStatCount(statMap, ["1030", "1050", "1060", "1080", "1300"]);
// return system.getResultSuccess(result);
// }
// /**
// * 交易数据(平台)
// * @param {*} params
// */
// async statTransData(params) {
// try {
// var result = {
// invoiceCount: 0,
// serviceChange: 0,
// };
// var type = Number(params.type || 1);
// var begin, end;
// // 取开始时间
// if (type == 1) {
// begin = moment().format("YYYY-MM") + "-01 00:00:00";
// } else if (type == 2) {
// begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
// }
// // echart数据
// var days = [];
// var dayCounts = [];
// var priceCounts = [];
// // 处理查询业务
// if (type == 1 || type == 2) { // 取结束时间
// end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
// days = this.getDays(end);
// // 按天统计
// var dayMap = await this.dao.statDayByTime(begin, end);
// for (var day of days) {
// var ditem = dayMap[day] || {};
// dayCounts.push(ditem.invoiceCount || 0);
// priceCounts.push(system.f2y(ditem.serviceChange || 0));
// }
// } else {
// var monthMap = await this.dao.statMonthByTime(begin, end);
// var bm = monthMap.begin || "";
// var em = monthMap.end || "";
// if (bm && em) {
// // 开始月份-结束月份所有月份
// var curMonth = bm;
// while (true) {
// days.push(curMonth);
// if (curMonth == em) {
// break;
// }
// curMonth = moment(curMonth + "-01").add(1, "month").format("YYYY-MM");
// }
// }
// for (var day of days) {
// var ditem = monthMap[day] || {};
// dayCounts.push(ditem.invoiceCount || 0);
// priceCounts.push(system.f2y(ditem.serviceChange || 0));
// }
// }
// var invoiceApplyData = await this.dao.statInvoiceByTime(begin, end) || {};
// result.invoiceCount = invoiceApplyData.invoiceCount;
// result.serviceChange = system.f2y(invoiceApplyData.serviceChange);
// result.days = days;
// result.dayCounts = dayCounts;
// result.priceCounts = priceCounts;
// return system.getResultSuccess(result);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 红冲
// * @param {*} params
// */
// async redRushInvoice(params) {
// try {
// let _apply = await this.dao.findById(params.id) || {};
// let invoice = await this.invoiceDao.findById(params.id) || {};
// //判断红冲状态
// if (invoice.redStatus == 2) {
// return system.getResult(null, `发票红冲中`);
// } else if (invoice.redStatus == 4) {
// return system.getResult(null, `红冲已红冲`);
// }
// let nowObj = {};
// nowObj.merchantId = this.trim(_apply.merchantId);
// nowObj.merchantName = this.trim(_apply.merchantName);
// nowObj.merchantCreditCode = this.trim(_apply.merchantCreditCode);
// nowObj.merchantAddr = this.trim(_apply.merchantAddr);
// nowObj.merchantMobile = this.trim(_apply.merchantMobile);
// nowObj.merchantBank = this.trim(_apply.merchantBank);
// nowObj.merchantAccount = this.trim(_apply.merchantAccount);
// nowObj.businessmenCreditCode = this.trim(_apply.businessmenCreditCode);
// nowObj.businessmenId = this.trim(_apply.businessmenId);
// nowObj.businessmenName = this.trim(_apply.businessmenName);
// nowObj.businessmenAddr = this.trim(_apply.businessmenAddr);
// nowObj.businessmenMobile = this.trim(_apply.businessmenMobile);
// nowObj.businessmenBank = this.trim(_apply.businessmenBank);
// nowObj.businessmenAccount = this.trim(_apply.businessmenAccount);
// nowObj.isBank = _apply.isBank ? 1 : 0;
// nowObj.taxAuthorities = this.trim(_apply.taxAuthorities);
// nowObj.type = this.trim(_apply.type);
// nowObj.invoiceAmount = this.trim(_apply.invoiceAmount);
// nowObj.statements = this.trim(_apply.statements);
// nowObj.contract = this.trim(_apply.contract);
// nowObj.invoiceTime = this.trim(_apply.invoiceTime);
// nowObj.settleImg = this.trim(_apply.settleImg);
// nowObj.applyNo = this.trim(_apply.applyNo);
// nowObj.invoiceConten = this.trim(_apply.invoiceConten);
// nowObj.personalIncomeTax = this.trim(_apply.personalIncomeTax);
// nowObj.additionalTax = this.trim(_apply.additionalTax);
// nowObj.valueAddedTax = this.trim(_apply.valueAddedTax);
// nowObj.serviceCharge = this.trim(_apply.serviceCharge);
// nowObj.applyMobile = this.trim(_apply.applyMobile);
// nowObj.parentId = this.trim(_apply.id);
// nowObj.status = this.trim("1000");
// nowObj.customerStatus = this.trim("1000");
// nowObj.payWay = this.trim(_apply.payWay);
// nowObj.payAccount = this.trim(_apply.payAccount);
// nowObj.mailAddr = this.trim(_apply.mailAddr);
// nowObj.mailMobile = this.trim(_apply.mailMobile);
// nowObj.mailTo = this.trim(_apply.mailTo);
// nowObj.remark = this.trim("");
// nowObj.delivererId = this.trim("");
// nowObj.isPay = 0;
// nowObj.businessmenType = this.trim(_apply.businessmenType);
// nowObj.ruleCode = this.trim(_apply.ruleCode);
// nowObj.ruleParams = this.trim(_apply.ruleParams);
// let res = await this.db.transaction(async (t) => {
// // 插入发票申请单
// let _nowObj = await this.dao.create(nowObj, t);
// // 插入一条发票信息
// await this.invoiceDao.create({
// id: _nowObj.id,
// applyNo: _nowObj.applyNo,
// merchantId: _nowObj.merchantId,
// red_status: '1',
// businessmenType : nowObj.businessmenType,
// ruleCode : nowObj.ruleCode,
// ruleParams : nowObj.ruleParams
// }, t);
// // 源发票改为红冲办理中
// var updfields = {
// redStatus: '2',
// id: _apply.id,
// }
// await this.invoiceDao.update(updfields, t);
// });
// return system.getResultSuccess();
// } catch (error) {
// console.log(error);
// return system.getResult(null, `参数错误 错误信息 ${error}`);
// }
// }
// async getByApplyNo(params) {
// var merchantId = params.merchantId || params.merchant_id;
// var applyNo = params.applyNo;
// var item = await this.dao.getByApplyNo(merchantId, applyNo);
// if (item) {
// this.handleDate(item, ["created_at", "updated_at"], null, -8);
// }
// return system.getResultSuccess(item);
// }
// /**
// * 查询发票明细
// * @param {*} applyNo
// * @param {*} merchantId
// */
// async queryInvoice(applyNo, merchantId, id) {
// try {
// let _apply;
// if (merchantId && applyNo) {
// _apply = await this.dao.model.findOne({
// where: {
// merchantId: merchantId,
// applyNo: applyNo
// },
// raw: true
// });
// } else if (id) {
// _apply = await this.dao.model.findOne({
// where: {
// id: this.trim(id)
// },
// raw: true
// });
// } else {
// _apply = null;
// }
// if (!_apply) {
// return system.getResult(null)
// }
// this.dao.setRowCodeName(_apply, "status");
// this.dao.setRowCodeName(_apply, "customerStatus");
// //查询平台审批内容
// let deliverer = await this.delivererDao.model.findOne({
// where: {
// id: _apply.delivererId
// },
// raw: true
// });
// _apply.deliverer = deliverer;
// //查询发票信息
// let invoice = await this.invoiceDao.model.findOne({
// where: {
// id: _apply.id
// },
// raw: true
// });
// this.dao.setRowCodeName(invoice, "status");
// //红冲关联
// let parentInvoice = await this.dao.model.findOne({
// where: {
// id: _apply.parentId
// },
// raw: true
// });
// this.dao.setRowCodeName(parentInvoice, "status");
// this.dao.setRowCodeName(parentInvoice, "customerStatus");
// _apply.invoice = invoice;
// _apply.deliverer = deliverer || {};
// _apply.parentInvoice = parentInvoice;
// this.handleDate(_apply.invoice, ["taxTime", "invoiceTime"], "YYYY-MM-DD");
// return system.getResult(_apply);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息:${error}`);
// }
// }
// /**
// * 发票撤回
// * @param {*} applyNo
// * @param {*} merchantId
// * @param
// */
// async cancelInvoice(applyNo, merchantId) {
// let _invoice = await this.dao.model.findOne({
// where: {
// applyNo: applyNo,
// merchantId: merchantId
// },
// attributes: ['id', 'status']
// });
// if (_invoice.status != this.invoiceStatus.unpay) {
// return system.getResult(null, `当前发票正在处理,不能撤回`);
// } else {
// _invoice.status = this.invoiceStatus.recall;
// try {
// let res = await _invoice.save();
// return system.getResult(res);
// } catch (error) {
// return system.getResult(null, `系统错误: ${error}`);
// }
// }
// }
// /**
// * 发票业务分配
// * @param {*} params
// * {
// * id:"" //发票id
// * nextStatus:"" //发票状态
// * }
// */
// async assignment(params) {
// let _apply = await this.verification(params);
// try {
// let res;
// switch (params.nextStatus) {
// case "1010": //审核不通过
// res = await this.examine1000(params, _apply);
// break;
// case "1020": //待分配
// res = await this.examine1000(params, _apply);
// break;
// case "1030": //待处理
// res = await this.examine1030(params, _apply);
// break;
// case "1070": //审核通过
// res = await this.examine1070(params, _apply);
// break;
// case "1300": //审核失败
// res = await this.examine1300(params, _apply);
// break;
// case "1090": //已完成
// res = await this.examine1090(params, _apply);
// break;
// default:
// res = system.getResult(null, "action_type参数错误");
// break;
// }
// return res;
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 第一次审核
// * @param {*} params
// * {
// * id: xxx, //发票id
// * isPay:1, //时候付款
// * nextStatus:1020,//发票状态
// * remark:""//发票标注
// * }
// */
// async examine1000(params, _apply) {
// if (Number(params.isPay) != 1) {
// return system.getResult(null, `参数错误 请核对付款信息`);
// }
// params.nextStatus = this.trim(params.nextStatus);
// params.remark = this.trim(params.remark);
// _apply.status = params.nextStatus;
// _apply.remark = params.remark;
// _apply.isPay = Number(params.isPay);
// if (params.nextStatus == "1010") {
// _apply.customerStatus = "1010";
// }
// try {
// let res = await _apply.save();
// if (_apply.parentId && params.nextStatus == "1010") {
// await this.invoiceDao.update({ id: _apply.parentId, redStatus: '3' });
// }
// return system.getResultSuccess();
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 待处理 (当前状态待分配或者是审核为通过)
// * @param {*} params
// * {
// * id: xxx, //发票id
// * delivererId:1, //交付商
// * nextStatus:examine1020,//发票状态
// * delivererName:""//交付商名称
// * delivererAmount:"" //分成
// * }
// */
// async examine1030(params, _apply) {
// if (!params.id || !params.delivererName) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// await this.db.transaction(async (t) => {
// let _deliverer = await this.delivererDao.create({
// invoiceId: _apply.id,
// applyNo: _apply.applyNo,
// merchantId: _apply.merchantId,
// delivererId: this.trim(params.delivererId),
// delivererName: this.trim(params.delivererName),
// delivererAmount: Number(this.trim(params.delivererAmount))
// }, t);
// let applyData = {};
// applyData.status = this.trim(params.nextStatus);
// applyData.customerStatus = this.trim(params.nextStatus);
// applyData.delivererId = this.trim(_deliverer.id);
// applyData.id = this.trim(params.id);
// //更新申请发票内容
// await this.dao.update(applyData, t);
// //更改发票状态
// let invoiceData = {};
// invoiceData.status = this.trim(params.nextStatus);
// invoiceData.id = this.trim(params.id);
// await this.invoiceDao.update(invoiceData, t);
// }).catch(error => {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// });
// return system.getResultSuccess();
// }
// /**
// * 第二次审核
// * @param {*} params
// * {
// * id: xxx, //发票id
// * auditContent:1, //审核备注
// * nextStatus:1070,//发票状态
// * delivererContent:""//发票内容
// * mailAddr:"", //邮寄地址
// * mailMobile:"", //邮寄电话
// * mailTo:"", //邮寄人
// * }
// */
// async examine1070(params, _apply) {
// let delivererData = {},
// applyData = {},
// invoiceData = {};
// let _deliverer = await this.delivererDao.findOne({
// id: _apply.delivererId
// });
// delivererData.auditContent = this.trim(params.auditContent);
// delivererData.delivererContent = this.trim(params.delivererContent);
// delivererData.mailAddr = this.trim(params.mailAddr);
// delivererData.mailMobile = this.trim(params.mailMobile);
// delivererData.mailTo = this.trim(params.mailTo);
// delivererData.mailEmail = this.trim(params.mailEmail);
// delivererData.id = this.trim(_deliverer.id);
// applyData.status = this.trim(params.nextStatus);
// applyData.id = this.trim(params.id);
// invoiceData.status = this.trim(params.nextStatus);
// invoiceData.id = this.trim(params.id);
// await this.db.transaction(async (t) => {
// //更新deliverer信息
// await this.delivererDao.update(delivererData, t);
// //更新 申请单和发票单
// await this.dao.update(applyData, t);
// await this.invoiceDao.update(invoiceData, t);
// if (_apply.parentId) {
// await this.invoiceDao.update({ id: _apply.parentId, redStatus: '4' }, t);
// }
// }).catch(error => {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// });
// return system.getResultSuccess();
// }
// /**
// * 第二次审核失败
// * @param {*} params
// */
// async examine1300(params) {
// let _apply = await this.dao.findOne({
// id: this.trim(params.id)
// });
// if (!_apply) {
// return system.getResult(null, `发票不存在,请核对发票ID`);
// }
// let _deliverer = await this.delivererDao.model.findOne({
// where: {
// id: _apply.delivererId
// }
// });
// if (!_deliverer) {
// return system.getResult(null, `交付商不存在,请联系管理员`);
// }
// await this.db.transaction(async (t) => {
// //更新 申请单和发票单
// await this.dao.update({
// status: "1300",
// id: _apply.id
// }, t);
// await this.invoiceDao.update({
// status: "1300",
// id: _apply.id
// }, t);
// if (_deliverer.id) {
// //提交审核信息
// await this.delivererDao.update({
// auditContent: this.trim(auditContent),
// id: _deliverer.id
// });
// }
// }).catch(error => {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// });
// return system.getResultSuccess();
// }
// /**
// * 平台更新 已完成状态
// * @param {*} params
// * @param {*} _apply
// */
// async examine1090(params, _apply) {
// let applyData = {};
// applyData.status = this.trim(params.nextStatus);
// applyData.customerStatus = this.trim(params.nextStatus);
// applyData.id = this.trim(params.id);
// // invoiceData.status = this.trim(params.nextStatus);
// // invoiceData.id=this.trim(params.id);
// await this.db.transaction(async (t) => {
// //更新 申请单和发票单
// await this.dao.update(applyData, t);
// // await this.invoiceDao.update(invoiceData,t);
// }).catch(error => {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// });
// return system.getResultSuccess();
// }
// /**
// * 检查状态是否正确
// * @param {*} params
// * {
// * id:xxx //发票id
// * nextStatus:xxx //发票状态
// * }
// */
// async verification(params) {
// let _apply = await this.dao.findOne({
// id: this.trim(params.id)
// });
// if (!_apply) {
// return system.getResult(null, `此发票不存在`);
// }
// //获取当前状态 的对象
// let _status = this.invoiceStatus[_apply.status];
// //如果不符合状态则退出
// if (params.nextStatus == "1300" || params.nextStatus == "1040" || params.nextStatus == "1010") {
// return _apply;
// }
// if (!_status && _status.next != params.nextStatus) {
// let name = this.invoiceStatus[this.invoiceStatus[_apply.status].next].name;
// return system.getResult(null, `更新状态错误,提示:当前状态的下一个状态是 ${name}`);
// }
// return _apply;
// }
// /**
// * 发票申请列表查询(平台)
// * @param {*} params
// * @param applyNo 发票的申请编号
// * @param invoiceTime 发票的申请时间
// * @param type 发票的类型
// * @param status 业务进度
// */
// async queryApplyInvoices(params) {
// let where = {};
// if (this.trim(params.applyNo)) {
// where.applyNo = this.trim(params.applyNo);
// }
// if (this.trim(params.businessmenCreditCode)) {
// where.businessmenCreditCode = this.trim(params.businessmenCreditCode);
// }
// if (this.trim(params.invoiceTime)) {
// where.invoiceTime = {
// [this.db.Op.gte]: this.trim(params.invoiceTime)
// }
// }
// if (this.trim(params.type)) {
// where.type = this.trim(params.type);
// }
// if (this.trim(params.status)) {
// where.status = this.trim(params.status);
// }
// let pageIndex = params.pageIndex || 1;
// let pageSize = params.pageSize || 10;
// let orderObj = [
// // ['updatedAt', 'desc'],
// ['id', 'desc']
// ];
// try {
// let _apply = await this.dao.getPageList(pageIndex, pageSize, where, orderObj, null, null);
// for (let item of _apply.rows) {
// let _deliverer = await this.delivererDao.model.findOne({
// // where: {
// // delivererId: item.delivererId
// // },
// attributes: ['delivererName']
// });
// if (_deliverer) {
// item.delivererName = _deliverer.delivererName;
// } else {
// item.delivererName = "";
// }
// if (item.type == "10") {
// item.type = "普通发票";
// } else if (item.type == "20") {
// item.type = "增值税专用发票";
// } else if (item.type == "30") {
// item.type = "电子发票";
// } else {
// item.type = "";
// }
// let _invoice = await this.invoiceDao.model.findOne({
// where: {
// id: item.id
// },
// attributes: ['status', 'invoiceImg']
// });
// if (_invoice.status) {
// this.dao.setRowCodeName(_invoice, "status");
// } else {
// _invoice.status = "";
// }
// item.invoiceImg = this.trim(_invoice.invoiceImg);
// item.delivererStatus = _invoice.statusName;
// //处理时间
// this.handleDate(item, ["invoiceTime"], null, -8);
// this.dao.setRowCodeName(item, "status");
// item.isPay = item.isPay == 1 ? '已付款' : '未付款';
// }
// return system.getResult(_apply);
// } catch (error) {
// return system.getResult(`系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 列举所有日期
// * @param {*} end
// */
// getDays(end) {
// var days = [];
// var month = moment(end).format("YYYY-MM");
// var endDay = Number(moment(end).format("DD"));
// for (var i = 1; i <= endDay; i++) {
// if (i < 10) {
// days.push(month + "-0" + i);
// } else {
// days.push(month + "-" + i);
// }
// }
// return days;
// }
// addStatCount(statusMap, statuses) {
// var count = 0;
// if (!statuses) {
// return count;
// }
// for (var status of statuses) {
// count = count + Number(statusMap[status] || 0);
// }
// return count;
// }
// //查询发票状态 只有在状态为 '1000','0090' 或者信息不存在的情况下 验证成功 参考 applySve.verificationByBusinessmenCreditCode接口
// async verificationInvoiceStatus(businessmenType, businessmenId, businessmenCreditCode) {
// try {
// let condition = {
// businessmenType: businessmenType,
// businessmenId: businessmenId,
// status: {
// [this.db.Op.in]: ['1000', '0090']
// }
// };
// if (businessmenCreditCode) {
// condition.businessmenCreditCode = businessmenCreditCode;
// }
// let invoices = await this.dao.model.findAll({
// where: condition,
// attributes: ["id", "status"]
// });
// if (!invoices) { return false; }
// for (let item of invoices) {
// if (!item) { continue; }
// if (item['status'] != "1000" || item['status'] != "0090") {
// return false;
// }
// }
// return true;
// } catch (error) {
// return false;
// }
// }
// /**
// * 累计不含税价
// * @param {*} businessmenId 商户id
// * @param {*} taxIncPriRat 不含税价百分比
// * @param {*} invoiceAmount 发票总额
// * @param {*} type 计算类型 1:个税 2:增值税
// * @param {*} valCalWay 增值税计算类型 1:月 2:季度 3:年
// * @param {*} perCalWay 增值税计算类型 1:月 2:季度 3:年
// * @param {*} invoiceTime 格式 YYYY-MM-DD hh:mm:ss
// */
// async calAccumulatedPriceExcludingTax(businessmenId,businessmenType, businessmenCreditCode, taxIncPriRat, invoiceAmount, type, valCalWay, perCalWay, invoiceTime) {
// try {
// let now = moment(invoiceTime),startTime, attribute;
// if (type === 1) { //个税
// attribute = `invoiceAmount`;
// if (perCalWay === 3) { //按照年
// startTime = `${now.get('year')}-01-01 00:00:00`;
// } else if (perCalWay === 2) { //按照季度
// let quarter = now.quarter();
// if (1 == quarter) { //第一季度
// startTime = `${now.get('year')}-01-01 00:00:00`;
// } else if (2 == quarter) {
// startTime = `${now.get('year')}-04-01 00:00:00`;
// } else if (3 == quarter) {
// startTime = `${now.get('year')}-07-01 00:00:00`;
// } else {
// startTime = `${now.get('year')}-10-01 00:00:00`;
// }
// } else { //按照月
// let _month = now.month() < 10 ? "0" + now.month() : now.month();
// startTime = `${now.get('year')}-${_month}-01 00:00:00`;
// }
// } else {
// attribute = `valueAddedTax`;
// if (valCalWay === 1) { //月
// startTime = `${now.get('year')}-${now.month()}-01 00:00:00`;
// } else if (valCalWay === 2) { //季度
// let quarter = now.quarter();
// if (1 == quarter) { //第一季度
// startTime = `${now.get('year')}-01-01 00:00:00`;
// } else if (2 == quarter) {
// startTime = `${now.get('year')}-04-01 00:00:00`;
// } else if (3 == quarter) {
// startTime = `${now.get('year')}-07-01 00:00:00`;
// } else {
// startTime = `${now.get('year')}-10-01 00:00:00`;
// }
// } else { //年
// startTime = `${now.get('year')}-01-01 00:00:00`;
// }
// }
// console.log("本年度开始的时间:" + startTime + " 至今:" + now.format("YYYY-MM-DD hh:mm:ss"));
// let condition = {
// businessmenId: businessmenId,
// businessmenType:businessmenType,
// status: {
// [this.db.Op.in]: ['1020', '1030', '1040', '1050', '1060', '1070', '1080', '1090', '1100', '1200', '1300']
// },
// invoiceTime: {
// [this.db.Op.between]: [startTime, now.format("YYYY-MM-DD hh:mm:ss")],
// }
// };
// if(businessmenCreditCode){
// condition.businessmenCreditCode=businessmenCreditCode;
// }
// let beforeAmount = await this.dao.model.sum(attribute, {
// where: condition
// });
// beforeAmount = isNaN(beforeAmount) ? 0 : beforeAmount;
// let res = new Decimal(invoiceAmount).plus(beforeAmount).div(Decimal.add(1, taxIncPriRat)).toFixed(2);
// console.log("当前累计金额 :" + res);
// return res;
// } catch (error) {
// console.log(error);
// return system.getResult(-1,`系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 计算累计税值
// * @param {*} businessmenId
// * @param {*} type 计算类型 1:个税 2:增值税
// * @param {*} valCalWay 增值税计算类型 1:月 2:季度
// *
// */
// async calCumulativeProfit(businessmenId,businessmenType, type, valCalWay) {
// let now = moment(),
// startTime, attribute;
// if (type == 1) {
// attribute = `personalIncomeTax`;
// startTime = `${now.get('year')}-01-01 00:00:00`;
// } else {
// attribute = `valueAddedTax`;
// if (valCalWay === 1) { //月
// startTime = `${now.get('year')}-${now.month()}-01 00:00:00`;
// } else { //季度
// let quarter = now.quarter();
// if (1 == quarter) { //第一季度
// startTime = `${now.get('year')}-01-01 00:00:00`;
// } else if (2 == quarter) {
// startTime = `${now.get('year')}-04-01 00:00:00`;
// } else if (3 == quarter) {
// startTime = `${now.get('year')}-07-01 00:00:00`;
// } else {
// startTime = `${now.get('year')}-10-01 00:00:00`;
// }
// }
// }
// console.log("本年度开始的时间:" + startTime + " 至今:" + now.format("YYYY-MM-DD hh:mm:ss"));
// let cumulativeProfit = await this.dao.model.sum(attribute, {
// where: {
// businessmenId: businessmenId,
// businessmenType: businessmenType,
// status: this.invoiceStatus.auditPass,
// invoiceTime: {
// [this.db.Op.between]: [startTime, now.format("YYYY-MM-DD hh:mm:ss")],
// }
// }
// });
// return cumulativeProfit || 0;
// }
// }
// module.exports = ApplyService;
\ No newline at end of file
const ServiceBase = require("../../sve.base");
const system = require("../../../system");
const moment = require('moment')
/**
* 交付商 提交的信息
*/
class InvoiceService extends ServiceBase {
constructor() {
super("invoice", ServiceBase.getDaoName(InvoiceService));
let is = system.getObject("util.invoiceStatus");
this.invoiceStatus = is.status;
// const ServiceBase = require("../../sve.base");
// const system = require("../../../system");
// const moment = require('moment')
// /**
// * 交付商 提交的信息
// */
// class InvoiceService extends ServiceBase {
// constructor() {
// super("invoice", ServiceBase.getDaoName(InvoiceService));
// let is = system.getObject("util.invoiceStatus");
// this.invoiceStatus = is.status;
this.applyDao = system.getObject("db.invoice.applyDao");
this.delivererDao = system.getObject("db.invoice.delivererDao");
}
// this.applyDao = system.getObject("db.invoice.applyDao");
// this.delivererDao = system.getObject("db.invoice.delivererDao");
// }
/**
* 完税证明
* @param {*} params
*/
async apiTxPayment(params) {
if (!params.id) {
return system.getResult(null, `参数错误 发票ID不合法`);
}
try {
let res = await this.txPayment(params);
return res;
} catch (error) {
return system.getResult(null, `参数错误 错误信息 ${error}`);
}
}
// /**
// * 完税证明
// * @param {*} params
// */
// async apiTxPayment(params) {
// if (!params.id) {
// return system.getResult(null, `参数错误 发票ID不合法`);
// }
// try {
// let res = await this.txPayment(params);
// return res;
// } catch (error) {
// return system.getResult(null, `参数错误 错误信息 ${error}`);
// }
// }
/**
* 查看完税证明
* @param {*} params
*/
async apiQueryTxPayment(params) {
if (!params.id) {
return system.getResult(null, `参数错误 发票ID不合法`);
}
try {
return await this.queryTxPayment(params);
} catch (error) {
return system.getResult(null, `参数错误 错误信息 ${error}`);
}
}
// /**
// * 查看完税证明
// * @param {*} params
// */
// async apiQueryTxPayment(params) {
// if (!params.id) {
// return system.getResult(null, `参数错误 发票ID不合法`);
// }
// try {
// return await this.queryTxPayment(params);
// } catch (error) {
// return system.getResult(null, `参数错误 错误信息 ${error}`);
// }
// }
/**
* 发票列表(平台)
* @param {*} params
*/
async apiQueryInvoices(params) {
try {
if(params.applyNo){params.applyNo=this.trim(params.applyNo)}
if(params.type){params.type=this.trim(params.type);}
if(params.invoiceTime){params.invoiceTime=this.trim(params.invoiceTime);}
return await this.queryInvoices(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
// /**
// * 发票列表(平台)
// * @param {*} params
// */
// async apiQueryInvoices(params) {
// try {
// if(params.applyNo){params.applyNo=this.trim(params.applyNo)}
// if(params.type){params.type=this.trim(params.type);}
// if(params.invoiceTime){params.invoiceTime=this.trim(params.invoiceTime);}
// return await this.queryInvoices(params);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
/**
* 发票红冲列表
* @param {*} params
*/
async apiRedRushList(params) {
try {
if(params){}
let res = await this.redRushList(params);
return res;
} catch (error) {
return system.getResult(null, `参数错误 错误信息 ${error}`);
}
}
// /**
// * 发票红冲列表
// * @param {*} params
// */
// async apiRedRushList(params) {
// try {
// if(params){}
// let res = await this.redRushList(params);
// return res;
// } catch (error) {
// return system.getResult(null, `参数错误 错误信息 ${error}`);
// }
// }
//==============================================================
// //==============================================================
/**
* 红冲列表
* @param {*} params
*/
async redRushList(params){
try {
if (params.delivererId) {
params.delivererId=this.trim(params.delivererId);
}
if (this.trim(params.applyNo)) {
params.applyNo=this.trim(params.applyNo);
}
if (this.trim(params.invoiceNo)) {
params.invoiceNo=this.trim(params.invoiceNo);
}
if (this.trim(params.invoiceTime)) {
params.invoiceTime=this.trim(params.invoiceTime);
}
if (this.trim(params.startTime)) {
params.startTime=this.trim(params.startTime);
}
if (this.trim(params.endTime)) {
params.endTime=this.trim(params.endTime);
}
if (this.trim(params.type)) {
params.type=this.trim(params.type);
}
if (this.trim(params.status)) {
params.status=this.trim(params.status);
}
if (this.trim(params.redStatus)) {
params.redStatus=this.trim(params.redStatus);
}
// /**
// * 红冲列表
// * @param {*} params
// */
// async redRushList(params){
// try {
// if (params.delivererId) {
// params.delivererId=this.trim(params.delivererId);
// }
// if (this.trim(params.applyNo)) {
// params.applyNo=this.trim(params.applyNo);
// }
// if (this.trim(params.invoiceNo)) {
// params.invoiceNo=this.trim(params.invoiceNo);
// }
// if (this.trim(params.invoiceTime)) {
// params.invoiceTime=this.trim(params.invoiceTime);
// }
// if (this.trim(params.startTime)) {
// params.startTime=this.trim(params.startTime);
// }
// if (this.trim(params.endTime)) {
// params.endTime=this.trim(params.endTime);
// }
// if (this.trim(params.type)) {
// params.type=this.trim(params.type);
// }
// if (this.trim(params.status)) {
// params.status=this.trim(params.status);
// }
// if (this.trim(params.redStatus)) {
// params.redStatus=this.trim(params.redStatus);
// }
params.statRow = (Number(this.trim(params.pageIndex)) - 1) * Number(this.trim(params.pageSize));
if (params.statRow <= 0) { params.statRow = 0; }
params.pageSize = Number(this.trim(params.pageSize)) <= 0 ? 10 : Number(this.trim(params.pageSize));
// params.statRow = (Number(this.trim(params.pageIndex)) - 1) * Number(this.trim(params.pageSize));
// if (params.statRow <= 0) { params.statRow = 0; }
// params.pageSize = Number(this.trim(params.pageSize)) <= 0 ? 10 : Number(this.trim(params.pageSize));
let total = await this.dao.countRedRushListByParams(params);
if (total == 0 || total[0].count == 0) {
let res = { rows: [], count: 0 };
return system.getResult(res);
}
// let total = await this.dao.countRedRushListByParams(params);
// if (total == 0 || total[0].count == 0) {
// let res = { rows: [], count: 0 };
// return system.getResult(res);
// }
let rows = await this.dao.redRushListByParams(params);
for (let item of rows) {
if (item.type == "10") {
item.type = "普通发票";
} else if (item.type == "20") {
item.type = "增值税专用发票";
} else if (item.type == "30") {
item.type = "电子发票";
} else {
item.type = "";
}
this.handleDate(item, ["invoice_time"], "YYYY-MM-DD HH:mm:ss", -8);
this.dao.setRowCodeName(item, "status");
}
// let rows = await this.dao.redRushListByParams(params);
// for (let item of rows) {
// if (item.type == "10") {
// item.type = "普通发票";
// } else if (item.type == "20") {
// item.type = "增值税专用发票";
// } else if (item.type == "30") {
// item.type = "电子发票";
// } else {
// item.type = "";
// }
// this.handleDate(item, ["invoice_time"], "YYYY-MM-DD HH:mm:ss", -8);
// this.dao.setRowCodeName(item, "status");
// }
let res = { count: total[0].count, rows: rows };
return system.getResult(res);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
// let res = { count: total[0].count, rows: rows };
// return system.getResult(res);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
/**
* 完税证明
* @param {*} params
* {
* id:xxx //完税证明
* }
*/
async txPayment(params) {
try {
let _invoice = await this.dao.findOne({
id: this.trim(params.id)
});
if (!_invoice) {
return system.getResult(null, `发票不存在`);
}
let res = await this.dao.update({
id: this.trim(params.id),
taxNo: this.trim(params.taxNo),
complateTax: 1,
taxTime: this.trim(params.taxTime),
taxVoucher: this.trim(params.taxVoucher)
});
return system.getResult(res);
} catch (error) {
return system.getResult(null, `参数错误 错误信息 ${error}`);
}
}
// /**
// * 完税证明
// * @param {*} params
// * {
// * id:xxx //完税证明
// * }
// */
// async txPayment(params) {
// try {
// let _invoice = await this.dao.findOne({
// id: this.trim(params.id)
// });
// if (!_invoice) {
// return system.getResult(null, `发票不存在`);
// }
// let res = await this.dao.update({
// id: this.trim(params.id),
// taxNo: this.trim(params.taxNo),
// complateTax: 1,
// taxTime: this.trim(params.taxTime),
// taxVoucher: this.trim(params.taxVoucher)
// });
// return system.getResult(res);
// } catch (error) {
// return system.getResult(null, `参数错误 错误信息 ${error}`);
// }
// }
/**
* 查看完税证明
* @param {*} params
* {
* id:xxx //完税证明
* }
*/
async queryTxPayment(params) {
try {
let _invoice = await this.dao.model.findOne({
where: {
id: this.trim(params.id),
complateTax: 1
},
attributes: ['id', 'taxNo', 'complateTax', 'taxTime', 'taxVoucher']
});
if (!_invoice) {
return system.getResult(null, `完税证明不存在`);
}
return system.getResult(_invoice);
} catch (error) {
return system.getResult(null, `参数错误 错误信息 ${error}`);
}
}
// /**
// * 查看完税证明
// * @param {*} params
// * {
// * id:xxx //完税证明
// * }
// */
// async queryTxPayment(params) {
// try {
// let _invoice = await this.dao.model.findOne({
// where: {
// id: this.trim(params.id),
// complateTax: 1
// },
// attributes: ['id', 'taxNo', 'complateTax', 'taxTime', 'taxVoucher']
// });
// if (!_invoice) {
// return system.getResult(null, `完税证明不存在`);
// }
// return system.getResult(_invoice);
// } catch (error) {
// return system.getResult(null, `参数错误 错误信息 ${error}`);
// }
// }
/**
* 发票列表查询(平台)
* @param {*} params
* @param applyNo 发票的申请编号
* @param invoiceTime 发票的申请时间
* @param type 发票的类型
* @param status 业务进度
*/
async queryInvoices(params) {
try {
// /**
// * 发票列表查询(平台)
// * @param {*} params
// * @param applyNo 发票的申请编号
// * @param invoiceTime 发票的申请时间
// * @param type 发票的类型
// * @param status 业务进度
// */
// async queryInvoices(params) {
// try {
var pageIndex = Number(params.pageIndex || 1);
var pageSize = Number(params.pageSize || 10);
// var pageIndex = Number(params.pageIndex || 1);
// var pageSize = Number(params.pageSize || 10);
var total = await this.dao.countByParams(params);
if (total == 0) {
return system.getResultSuccess({
count: 0,
rows: []
});
}
// var total = await this.dao.countByParams(params);
// if (total == 0) {
// return system.getResultSuccess({
// count: 0,
// rows: []
// });
// }
var startRow = (pageIndex - 1) * pageSize;
// var startRow = (pageIndex - 1) * pageSize;
var list = await this.dao.pageByParams(params, startRow, pageSize);
// var list = await this.dao.pageByParams(params, startRow, pageSize);
await this.setApply(list);
for (var item of list) {
// item.redStatusName = this.dao.getRowCodeName(item, "red_status");
// await this.setApply(list);
// for (var item of list) {
// // item.redStatusName = this.dao.getRowCodeName(item, "red_status");
if (item.red_status == 1) {
item.red_status = '未红冲';
} else if (item.red_status == 2) {
item.red_status = '红冲中';
} else if (item.red_status == 3) {
item.red_status = '红冲失败'
} else if (item.red_status == 4) {
item.red_status = '红冲成功';
} else {
item.red_status = '';
}
this.dao.getRowCodeName(item.apply,"status");
item.complate_tax = item.complate_tax == 1 ? '已完税' : '未完税';
item.month = moment(item.invoice_time).month() + 1;
this.handleDate(item,['invoice_time'],null,-8);
if (item.apply['type'] == '10') {
item.apply['type'] = "普通发票";
} else if (item.apply['type'] == '20') {
item.apply['type'] = "增值税专用发票";
} else {
item.apply['type'] = "电子发票";
}
}
var page = {
count: total,
rows: list
};
return system.getResultSuccess(page);
} catch (error) {
console.log(error);
return system.getResult(`系统错误 错误信息 ${error}`);
}
}
// if (item.red_status == 1) {
// item.red_status = '未红冲';
// } else if (item.red_status == 2) {
// item.red_status = '红冲中';
// } else if (item.red_status == 3) {
// item.red_status = '红冲失败'
// } else if (item.red_status == 4) {
// item.red_status = '红冲成功';
// } else {
// item.red_status = '';
// }
// this.dao.getRowCodeName(item.apply,"status");
// item.complate_tax = item.complate_tax == 1 ? '已完税' : '未完税';
// item.month = moment(item.invoice_time).month() + 1;
// this.handleDate(item,['invoice_time'],null,-8);
// if (item.apply['type'] == '10') {
// item.apply['type'] = "普通发票";
// } else if (item.apply['type'] == '20') {
// item.apply['type'] = "增值税专用发票";
// } else {
// item.apply['type'] = "电子发票";
// }
// }
// var page = {
// count: total,
// rows: list
// };
// return system.getResultSuccess(page);
// } catch (error) {
// console.log(error);
// return system.getResult(`系统错误 错误信息 ${error}`);
// }
// }
async setApply(list) {
if (!list || list.length == 0) {
return;
}
// async setApply(list) {
// if (!list || list.length == 0) {
// return;
// }
var ids = [];
for (var item of list) {
ids.push(item.id);
}
// var ids = [];
// for (var item of list) {
// ids.push(item.id);
// }
var applyMap = await this.applyDao.findMapByIds(ids) || {};
for (var item of list) {
item.apply = applyMap[item.id] || {};
}
}
// var applyMap = await this.applyDao.findMapByIds(ids) || {};
// for (var item of list) {
// item.apply = applyMap[item.id] || {};
// }
// }
}
module.exports = InvoiceService;
\ No newline at end of file
// }
// module.exports = InvoiceService;
\ No newline at end of file
......@@ -7,844 +7,6 @@ const moment = require('moment');
class IinvoicedelivererService extends ServiceBase {
constructor() {
super("invoice", ServiceBase.getDaoName(DelivererService));
this.invoiceDao = system.getObject("db.invoice.invoiceDao");
let is = system.getObject("util.invoiceStatus");
this.invoiceStatus = is.status;
}
/**
* 平台业务分配
* @param {*} params
*/
async apiAssignment(params) {
try {
return await this.assignment(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 产看业务办理
* @param {*} params
* {
* id:xxx 发票id
* }
*/
async apiQueryProcess(params) {
try {
return await this.queryProcess(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 平台更新地址
* @param {*} params
*/
async apiUpEmNo(params) {
try {
if (!params.id) { return system.getResult(null, `参数错误 ID不能为空`); }
if (!params.platformMailNo) { return system.getResult(null, `参数错误 邮寄单号不能为空`); }
return await this.updateEmailNo(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 申请列表(交付商)
* 注意:当前只有一个交付商,如果有多个交付商,则需要传入id 并且修改当前接口sql
* @param {*} params
*/
async apiDelivererApplyInvoices(params) {
try {
if (!params.delivererId) { return system.getResult(null, `参数错误 ID不能为空`); }
return await this.delivererApplyInvoices(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 发票明细(交付商)
* @param {*} params
*/
async apiQueryInvoiceDeliverer(params) {
try {
var merchantId = params.merchantId || params.merchant_id;
if ((params.merchantId && params.applyNo) || params.id) {
let res = await this.queryInvoiceDeliverer(params.applyNo, merchantId, params.id);
return res;
} else {
return system.getResultSuccess();
}
} catch (error) {
return system.getResult(null, `系统错误 错误信息:${error}`);
}
}
/**
* 交付商审批列表
* @param {*} params
*/
async apiDelInvs(params) {
try {
return await this.delInvs(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 交付商业务概览
* @param {*} params
*/
async apiStatDeliverData(params) {
try {
return await this.statDeliverData(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
/**
* 交易数据(交付商)
* @param {*} params
*/
async apiDelStatTransData(params) {
try {
if(!params.delivererId){
return system.getResult(-1,`交付商ID不能为空`);
}
return await this.delStatTransData(params);
} catch (error) {
return system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
/**
* 发票办理(交付商)
* @param {*} params
*/
async apiDelStatBusinessData(params) {
try {
if(!params.delivererId){
return system.getResult(-1,`交付商ID不能为空`);
}
return await this.delStatBusinessData(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
//=========================================================================================//
/**
* 发票办理(交付商)
* @param {*} params
*/
async delStatBusinessData(params) {
try {
var result = {};
var type = Number(params.type || 1);
// 查 已完成订单,待分配订单,待审核订单,办理中订单
var begin, end,delivererId=params.delivererId;
// 取开始时间
if (type == 1) {//本月
begin = moment().format("YYYY-MM") + "-01 00:00:00";
end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
} else if (type == 2) {//上个月
begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
}
// 先按照订单状态查
let list = await this.dao.model.findAll({
include:[
{
association:this.dao.model.belongsTo(this.applyDao.model,{
foreignKey:"invoiceId",targetKey:"id"
}),
required:true,
attributes:['status'],
where:{
status:{
[this.db.Op.in]:['1030','1040','1050','1060','1300']
}
}
}
],
where:{
delivererId:delivererId,
createdAt:{
[this.db.Op.between]:[begin,end]
}
},
attributes:['id','delivererName','delivererId']
});
// 已开具 1050
let count = 0;
for(let item of list){
if(item.apply.status=="1050"){
count+=1;
}
}
result.completeCount = count || 0;
result.handlingCount = list.length-count<=0?0:list.length-count;
return system.getResultSuccess(result);
} catch (error) {
return system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
/**
* 交易数据(交付商)
* @param {*} params
*/
async delStatTransData(params) {
try {
var result = {
invoiceCount: 0,
delivererAmount: 0,
};
var type = Number(params.type || 1);
var begin, end,delivererId=params.delivererId;
// 取开始时间
if (type == 1) {
begin = moment().format("YYYY-MM") + "-01 00:00:00";
} else if (type == 2) {
begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
}
// echart数据
var days = [];
var dayCounts = [];
var priceCounts = [];
// 处理查询业务
if (type == 1 || type == 2) { // 取结束时间
end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
days = this.getDays(end);
// 按天统计
var dayMap = await this.dao.delStatDayByTime(begin, end,delivererId);
for (var day of days) {
var ditem = dayMap[day] || {};
dayCounts.push(ditem.invoiceCount || 0);
priceCounts.push(system.f2y(ditem.delivererAmount || 0));
}
} else {
var monthMap = await this.dao.delStatMonthByTime(begin, end, delivererId);
var bm = monthMap.begin || "";
var em = monthMap.end || "";
if (bm && em) {
// 开始月份-结束月份所有月份
var curMonth = bm;
while (true) {
days.push(curMonth);
if (curMonth == em) {
break;
}
curMonth = moment(curMonth + "-01").add(1, "month").format("YYYY-MM");
}
}
for (var day of days) {
var ditem = monthMap[day] || {};
dayCounts.push(ditem.invoiceCount || 0);
priceCounts.push(system.f2y(ditem.delivererAmount || 0));
}
}
var invoiceApplyData = await this.dao.delStatInvoiceByTime(begin, end ,delivererId) || {};
result.invoiceCount = invoiceApplyData.invoiceCount;
result.delivererAmount = system.f2y(invoiceApplyData.delivererAmount);
result.days = days;
result.dayCounts = dayCounts;
result.priceCounts = priceCounts;
return system.getResultSuccess(result);
} catch (error) {
return system.getResult(null,`系统错误 错误信息 ${error}`);
}
}
/**
* 交付商业务概览
* @param {*} params
*/
async statDeliverData(params) {
try {
var currentPage = Number(params.currentPage || 1);
var pageSize = Number(params.pageSize || 10);
// 处理时间
var type = Number(params.type || 1);
var begin, end;
// 取开始时间
if (type == 1) {
begin = moment().format("YYYY-MM") + "-01 00:00:00";
end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
} else if (type == 2) {
begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
}
var condition = {
begin: begin,
end: end,
}
// 查总数
var _res = await this.dao.countStat(condition);
if (_res.total == 0) {
return system.getResultSuccess({
count: 0,
rows: []
});
}else{
let _str=[];
//这个id是交付商的id
for (let item of _res.list) {
_str.push(`'${item.deliverer_id}'`);
}
condition.list=_str.join(",");
}
// 查条数
var startRow = (currentPage - 1) * pageSize;
var list = await this.dao.queryStat(condition, startRow, pageSize);
for (let item of list) {
item.totalAmount=system.f2y(item.totalAmount || 0)
}
//计算每个
// 设置已完成数量、办理中数量
var delivererIds = [];
for (var item of list) {
//这个是交付商表的主键
delivererIds.push(item.id);
}
var dstatusMap = await this.dao.statDeliverByStatus({
begin: begin,
end: end,
delivererIds: delivererIds
});
for (var item of list) {
item.completeCount = this.addStatCount(dstatusMap, item.id, ['1080',"1090"]);
item.handlingCount = this.addStatCount(dstatusMap, item.id, ['1030','1040','1050','1060','1300']);
}
return system.getResultSuccess({
count: _res.total,
rows: list
});
} catch (error) {
system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
addStatCount(statusMap, deliverer_id, statuses) {
var count = 0;
if (!statuses || statuses.length == 0) {
return count;
}
for (var status of statuses) {
count = count + Number(statusMap[deliverer_id + "_" + status] || 0);
}
return count;
}
/**
* 发票业务分配
* @param {*} params
* {
* applyNo:"" //发票编号
* nextStatus:"" //发票状态
* }
*/
async assignment(params) {
let obj = await this.verification(params);
let _apply = obj._apply;
let _invoice = obj._invoice;
try {
let res;
switch (params.nextStatus) {
case "1040": //交付商以关闭
res = await this.examine1040(params, _apply, _invoice);
break;
case "1050": //已开具
res = await this.examine1050(params, _apply, _invoice);
break;
case "1060": //待审核
res = await this.examine1060(params, _apply, _invoice);
break;
case "1080": //邮寄
res = await this.examine1080(params, _apply, _invoice);
break;
case "1090": //已邮寄
res = await this.examine1090(params, _apply, _invoice);
break;
default:
res = system.getResult(null, "action_type参数错误");
break;
}
return res;
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 交付商拒绝
* @param {*} params
* {
* "id":"xxx",
* "nextStatus":"1040",
* ""
* }
* @param {*} _apply
* //将申请表中的delivererId 变成null,
* //将invoice和apply 中的状态待分配 1020
* //添加拒绝原因
*/
async examine1040(params, _apply, _invoice) {
//更改发票表信息
_invoice.status = this.trim(params.nextStatus);
//添加拒绝原因
let delivererData = {
breakReason: this.trim(params.breakReason),
id: _apply.delivererId
};
//更改申请表信息
_apply.status = "1020";
_apply.delivererId = null;
let applyData = {};
applyData.id = _apply.id;
applyData.status = "1020";
applyData.delivererId = '';
let invoiceData = {};
invoiceData.status = "1020";
await this.db.transaction(async (t) => {
//更新申请表状态
await this.applyDao.update(applyData, t);
//更新发票表状态
await this.invoiceDao.update(invoiceData, t);
//更新拒绝原因
await this.dao.update(delivererData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
/**
* 交付商开具
* @param {*} params
* @param {*} _apply
*/
async examine1050(params, _apply, _invoice) {
//更改发票表信息
let invoiceData = {};
invoiceData.id = params.id;
invoiceData.invoiceNo = this.trim(params.invoiceNo);
invoiceData.invoiceTime = this.trim(params.invoiceTime);
invoiceData.invoiceImg = this.trim(params.invoiceImg);
invoiceData.status = this.trim(params.nextStatus);
//更改申请表信息
let applyData = {};
applyData.id = params.id;
applyData.status = this.trim(params.nextStatus);
applyData.customerStatus = this.trim(params.nextStatus);
await this.db.transaction(async (t) => {
//更新申请表状态
await this.applyDao.update(applyData, t);
//更新发票表状态
await this.invoiceDao.update(invoiceData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
/**
* 交付商提交审核
* @param {*} params
* {
* nextStatus:xxx, //发票状态
* id:xxx //发票id
* }
* @param {*} _apply
*/
async examine1060(params, _apply, _invoice) {
let invoiceData = {}, applyData = {};
invoiceData.status = params.nextStatus;
invoiceData.id = params.id;
if (params.invoiceNo) {
invoiceData.invoiceNo = this.trim(params.invoiceNo);
}
if (params.invoiceTime) {
invoiceData.invoiceTime = this.trim(params.invoiceTime);
}
if (params.invoiceImg) {
invoiceData.invoiceImg = this.trim(params.invoiceImg);
}
applyData.status = params.nextStatus;
applyData.id = params.id;
await this.db.transaction(async (t) => {
//更新申请表状态
await this.applyDao.update(applyData, t);
//更新发票表状态
await this.invoiceDao.update(invoiceData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
/**
* 交付商已邮寄
* @param {*} params
* {
* nextStatus:xxx, //发票状态
* id:xxx //发票id
* }
* @param {*} _apply
*/
async examine1080(params, _apply, _invoice) {
let invoiceData = {}, applyData = {}, delivererData = {};
//更改发票表信息
invoiceData.status = this.trim(params.nextStatus);
invoiceData.mailNo = this.trim(params.mailNo);
invoiceData.id = this.trim(params.id);
//更改申请表信息
applyData.status = this.trim(params.nextStatus);
applyData.id = this.trim(params.id);
//交付商
let _deliverer = await this.dao.findOne({ id: _apply.delivererId });
delivererData.delivererMailNo = params.mailNo;
delivererData.id = _deliverer.id;
await this.db.transaction(async (t) => {
//更新申请表状态
await this.applyDao.update(applyData, t);
//更新发票表状态
await this.invoiceDao.update(invoiceData, t);
//更新交付商信息
await this.dao.update(delivererData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
/**
* 检查状态是否正确
* @param {*} params
* {
* id:xxx //发票id
* nextStatus:xxx //发票状态
* }
*/
async verification(params) {
let _apply = await this.applyDao.findOne({ id: params.id });
let _invoice = await this.invoiceDao.findOne({ id: params.id });
if (!_invoice) { return system.getResult(null, `此发票不存在`); }
//获取当前状态 的对象
let _status = this.invoiceStatus[_invoice.status];
//如果不符合状态则退出
if (params.nextStatus == "1300" || params.nextStatus == "1040" || params.nextStatus == "1010") {
let obj = {
_apply: _apply,
_invoice: _invoice
};
return obj;
} else if (!_status && _status.dstatus != params.nextStatus) {
let name = this.invoiceStatus[this.invoiceStatus[_invoice.status].dstatus].name;
return system.getResult(null, `更新状态错误,提示:当前状态的下一个状态是 ${name}`);
}
let obj = {
_apply: _apply,
_invoice: _invoice
};
return obj;
}
/**
* 查看业务办理
*/
async queryProcess(params) {
let _apply = await this.applyDao.model.findOne({ where: { id: this.trim(params.id) }, attributes: ['delivererId'] });
if (!_apply) {
return system.getResult(null, `发票不存在`);
}
let _deliverer = await this.dao.findOne({ id: _apply.delivererId });
return system.getResult(_deliverer);
}
/**
* 平台更新邮寄地址
* @param {*} params
*/
async updateEmailNo(params) {
try {
let _apply = await this.applyDao.model.findOne({ where: { id: this.trim(params.id) }, attributes: ['delivererId'] });
if (!_apply) { return system.getResult(null, `发票不存在,请确认发票ID`); }
let _deliverer = await this.dao.model.findOne({ where: { id: _apply.delivererId } });
if (!_deliverer) { return system.getResult(null, `交付商办理信息不存在,请联系管理员`); }
_deliverer.platformMailNo = this.trim(params.platformMailNo);
let res = await _deliverer.save();
return system.getResult(res);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 交付商申请列表
* @param {*} params
*/
async delivererApplyInvoices(params) {
try {
if (params.delivererId) {
params.delivererId=this.trim(params.delivererId);
}
if (this.trim(params.applyNo)) {
params.applyNo=this.trim(params.applyNo);
}
if (this.trim(params.invoiceTime)) {
params.invoiceTime=this.trim(params.invoiceTime);
}
if (this.trim(params.startTime)) {
params.startTime=this.trim(params.startTime);
}
if (this.trim(params.endTime)) {
params.endTime=this.trim(params.endTime);
}
if (this.trim(params.type)) {
params.type=this.trim(params.type);
}
if (this.trim(params.status)) {
params.status=this.trim(params.status);
}
params.statRow = (Number(this.trim(params.pageIndex)) - 1) * Number(this.trim(params.pageSize));
if (params.statRow <= 0) { params.statRow = 0; }
params.pageSize = Number(this.trim(params.pageSize)) <= 0 ? 10 : Number(this.trim(params.pageSize));
let total = await this.dao.countApplyByParams(params);
if (total[0].count == 0) {
let res = { rows: [], count: 0 };
return system.getResult(res);
}
let rows = await this.dao.delivererApplyInvoices(params);
for (let item of rows) {
if (item.type == "10") {
item.type = "普通发票";
} else if (item.type == "20") {
item.type = "增值税专用发票";
} else if (item.type == "30") {
item.type = "电子发票";
} else {
item.type = "";
}
this.handleDate(item, ["invoice_time"], "YYYY-MM-DD HH:mm:ss", -8);
this.dao.setRowCodeName(item, "status");
}
let res = { count: total[0].count, rows: rows };
return system.getResult(res);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 查询发票明细(交付商)
* @param {*} applyNo
* @param {*} merchantId
*/
async queryInvoiceDeliverer(applyNo, merchantId, id) {
try {
let _apply;
if (merchantId && applyNo) {
_apply = await this.applyDao.model.findOne({
where: {
merchantId: this.trim(merchantId),
applyNo: this.trim(applyNo)
},
attributes: this._applyAttribute,
raw: true
});
} else if (id) {
_apply = await this.applyDao.model.findOne({
where: { id: this.trim(id) },
attributes: this._applyAttribute,
raw: true
});
} else {
_apply = null;
}
if (!_apply) { return system.getResult(null) }
//格式化字典
_apply.isBank = this.isBank == 1 ? '开户' : '未开户';
if (_apply.type == 10) {
_apply.type = "普通发票";
} else if (_apply.type == 20) {
_apply.type = "增值税专用发票";
} else {
_apply.type = "电子发票"
}
//格式化日期
this.handleDate(_apply, ["invoiceTime"], "YYYY-MM-DD HH:mm:ss", -8);
this.handleDate(_apply, ["createdAt"], "YYYY-MM-DD HH:mm:ss", -8);
//查询平台审批内容
let deliverer = await this.dao.model.findOne({
where: { id: _apply.delivererId },
raw: true,
attributes: this._delivererAttribute
});
//查询发票信息
let invoice = await this.invoiceDao.model.findOne({
where: { id: _apply.id },
attributes: this._invoiceAttribute,
raw: true
});
this.handleDate(invoice, ["invoiceTime"], "YYYY-MM-DD HH:mm:ss", -8);
this.handleDate(invoice, ["taxTime"], "YYYY-MM-DD HH:mm:ss", -8);
invoice.complateTax = invoice.complateTax == 1 ? '已完税' : '未完税';
deliverer.status = invoice.status;
//格式化状态
this.dao.setRowCodeName(deliverer, "status");
_apply.deliverer = deliverer;
delete invoice["status"];
_apply.invoice = invoice;
_apply.deliverer = deliverer || null;
return system.getResult(_apply);
} catch (error) {
return system.getResult(null, `系统错误 错误信息:${error}`);
}
}
/**
* 发票列表(交付商)
* @param {*} params
*/
async delInvs(params) {
if (params.delivererId) {
params.delivererId=this.trim(params.delivererId);
}
if (this.trim(params.applyNo)) {
params.applyNo=this.trim(params.applyNo);
}
if (this.trim(params.invoiceNo)) {
params.invoiceNo=this.trim(params.invoiceNo);
}
if (this.trim(params.invoiceTime)) {
params.invoiceTime=this.trim(params.invoiceTime);
}
if (this.trim(params.startTime)) {
params.startTime=this.trim(params.startTime);
}
if (this.trim(params.endTime)) {
params.endTime=this.trim(params.endTime);
}
if (this.trim(params.type)) {
params.type=this.trim(params.type);
}
if (this.trim(params.status)) {
params.status=this.trim(params.status);
}
if (this.trim(params.complateTax) == "1" || this.trim(params.complateTax) == "0") {
params.complateTax=this.trim(params.complateTax);
}
if (this.trim(params.redStatus)) {
params.red_status=this.trim(params.red_status);
}
params.statRow = (Number(this.trim(params.pageIndex)) - 1) * Number(this.trim(params.pageSize));
if (params.statRow <= 0) { params.statRow = 0; }
params.pageSize = Number(this.trim(params.pageSize)) <= 0 ? 10 : Number(this.trim(params.pageSize));
try {
//查总数
let total = await this.dao.countInvoiceByParams(params);
//查列表信息
let rows = await this.dao.delivererInvoices(params);
for (let item of rows) {
if (item.type == 10) {
item.type = '普通发票';
} else if (item.type == 20) {
item.type = '增值税专用发票';
} else if (item.type == 30) {
item.type = '电子发票';
} else { }
if (item.red_status == 1) {
item.red_status = '未红冲';
} else if (item.red_status == 2) {
item.red_status = '红冲中';
} else if (item.red_status == 3) {
item.red_status = '红冲失败';
} else if (item.red_status == 4) {
item.red_status = '红冲成功';
} else {
item.red_status = '';
}
item.month = moment(item.invoice_time).month() + 1;
item.complate_tax = item.complate_tax == 1 ? '已完成' : '未完成';
this.handleDate(item, ["invoice_time"], "YYYY-MM-DD HH:mm:ss", -8);
this.dao.setRowCodeName(item, "status");
}
let res = { count: total[0].count, rows: rows };
return system.getResult(res);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* 列举所有日期
* @param {*} end
*/
getDays(end) {
var days = [];
var month = moment(end).format("YYYY-MM");
var endDay = Number(moment(end).format("DD"));
for (var i = 1; i <= endDay; i++) {
if (i < 10) {
days.push(month + "-0" + i);
} else {
days.push(month + "-" + i);
}
}
return days;
}
// addStatCount(statusMap, statuses) {
// var count = 0;
// if(!statuses) {
// return count;
// }
// for(var status of statuses) {
// count = count + Number(statusMap[status] || 0);
// }
// return count;
// }
}
module.exports = IinvoicedelivererService;
\ No newline at end of file
// const ServiceBase = require("../../sve.base");
// const system = require("../../../system");
// const moment = require('moment');
// /**
// * 平台提交的信息
// */
// class IinvoicedelivererService extends ServiceBase {
// constructor() {
// super("invoice", ServiceBase.getDaoName(DelivererService));
// this.invoiceDao = system.getObject("db.invoice.invoiceDao");
// let is = system.getObject("util.invoiceStatus");
// this.invoiceStatus = is.status;
// }
// /**
// * 平台业务分配
// * @param {*} params
// */
// async apiAssignment(params) {
// try {
// return await this.assignment(params);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 产看业务办理
// * @param {*} params
// * {
// * id:xxx 发票id
// * }
// */
// async apiQueryProcess(params) {
// try {
// return await this.queryProcess(params);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 平台更新地址
// * @param {*} params
// */
// async apiUpEmNo(params) {
// try {
// if (!params.id) { return system.getResult(null, `参数错误 ID不能为空`); }
// if (!params.platformMailNo) { return system.getResult(null, `参数错误 邮寄单号不能为空`); }
// return await this.updateEmailNo(params);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 申请列表(交付商)
// * 注意:当前只有一个交付商,如果有多个交付商,则需要传入id 并且修改当前接口sql
// * @param {*} params
// */
// async apiDelivererApplyInvoices(params) {
// try {
// if (!params.delivererId) { return system.getResult(null, `参数错误 ID不能为空`); }
// return await this.delivererApplyInvoices(params);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 发票明细(交付商)
// * @param {*} params
// */
// async apiQueryInvoiceDeliverer(params) {
// try {
// var merchantId = params.merchantId || params.merchant_id;
// if ((params.merchantId && params.applyNo) || params.id) {
// let res = await this.queryInvoiceDeliverer(params.applyNo, merchantId, params.id);
// return res;
// } else {
// return system.getResultSuccess();
// }
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息:${error}`);
// }
// }
// /**
// * 交付商审批列表
// * @param {*} params
// */
// async apiDelInvs(params) {
// try {
// return await this.delInvs(params);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 交付商业务概览
// * @param {*} params
// */
// async apiStatDeliverData(params) {
// try {
// return await this.statDeliverData(params);
// } catch (error) {
// console.log(error);
// return system.getResult(null, "接口异常");
// }
// }
// /**
// * 交易数据(交付商)
// * @param {*} params
// */
// async apiDelStatTransData(params) {
// try {
// if(!params.delivererId){
// return system.getResult(-1,`交付商ID不能为空`);
// }
// return await this.delStatTransData(params);
// } catch (error) {
// return system.getResult(-1,`系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 发票办理(交付商)
// * @param {*} params
// */
// async apiDelStatBusinessData(params) {
// try {
// if(!params.delivererId){
// return system.getResult(-1,`交付商ID不能为空`);
// }
// return await this.delStatBusinessData(params);
// } catch (error) {
// console.log(error);
// return system.getResult(null, "接口异常");
// }
// }
// //=========================================================================================//
// /**
// * 发票办理(交付商)
// * @param {*} params
// */
// async delStatBusinessData(params) {
// try {
// var result = {};
// var type = Number(params.type || 1);
// // 查 已完成订单,待分配订单,待审核订单,办理中订单
// var begin, end,delivererId=params.delivererId;
// // 取开始时间
// if (type == 1) {//本月
// begin = moment().format("YYYY-MM") + "-01 00:00:00";
// end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
// } else if (type == 2) {//上个月
// begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
// end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
// }
// // 先按照订单状态查
// let list = await this.dao.model.findAll({
// include:[
// {
// association:this.dao.model.belongsTo(this.applyDao.model,{
// foreignKey:"invoiceId",targetKey:"id"
// }),
// required:true,
// attributes:['status'],
// where:{
// status:{
// [this.db.Op.in]:['1030','1040','1050','1060','1300']
// }
// }
// }
// ],
// where:{
// delivererId:delivererId,
// createdAt:{
// [this.db.Op.between]:[begin,end]
// }
// },
// attributes:['id','delivererName','delivererId']
// });
// // 已开具 1050
// let count = 0;
// for(let item of list){
// if(item.apply.status=="1050"){
// count+=1;
// }
// }
// result.completeCount = count || 0;
// result.handlingCount = list.length-count<=0?0:list.length-count;
// return system.getResultSuccess(result);
// } catch (error) {
// return system.getResult(-1,`系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 交易数据(交付商)
// * @param {*} params
// */
// async delStatTransData(params) {
// try {
// var result = {
// invoiceCount: 0,
// delivererAmount: 0,
// };
// var type = Number(params.type || 1);
// var begin, end,delivererId=params.delivererId;
// // 取开始时间
// if (type == 1) {
// begin = moment().format("YYYY-MM") + "-01 00:00:00";
// } else if (type == 2) {
// begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
// }
// // echart数据
// var days = [];
// var dayCounts = [];
// var priceCounts = [];
// // 处理查询业务
// if (type == 1 || type == 2) { // 取结束时间
// end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
// days = this.getDays(end);
// // 按天统计
// var dayMap = await this.dao.delStatDayByTime(begin, end,delivererId);
// for (var day of days) {
// var ditem = dayMap[day] || {};
// dayCounts.push(ditem.invoiceCount || 0);
// priceCounts.push(system.f2y(ditem.delivererAmount || 0));
// }
// } else {
// var monthMap = await this.dao.delStatMonthByTime(begin, end, delivererId);
// var bm = monthMap.begin || "";
// var em = monthMap.end || "";
// if (bm && em) {
// // 开始月份-结束月份所有月份
// var curMonth = bm;
// while (true) {
// days.push(curMonth);
// if (curMonth == em) {
// break;
// }
// curMonth = moment(curMonth + "-01").add(1, "month").format("YYYY-MM");
// }
// }
// for (var day of days) {
// var ditem = monthMap[day] || {};
// dayCounts.push(ditem.invoiceCount || 0);
// priceCounts.push(system.f2y(ditem.delivererAmount || 0));
// }
// }
// var invoiceApplyData = await this.dao.delStatInvoiceByTime(begin, end ,delivererId) || {};
// result.invoiceCount = invoiceApplyData.invoiceCount;
// result.delivererAmount = system.f2y(invoiceApplyData.delivererAmount);
// result.days = days;
// result.dayCounts = dayCounts;
// result.priceCounts = priceCounts;
// return system.getResultSuccess(result);
// } catch (error) {
// return system.getResult(null,`系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 交付商业务概览
// * @param {*} params
// */
// async statDeliverData(params) {
// try {
// var currentPage = Number(params.currentPage || 1);
// var pageSize = Number(params.pageSize || 10);
// // 处理时间
// var type = Number(params.type || 1);
// var begin, end;
// // 取开始时间
// if (type == 1) {
// begin = moment().format("YYYY-MM") + "-01 00:00:00";
// end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
// } else if (type == 2) {
// begin = moment().subtract(1, "months").format("YYYY-MM") + "-01 00:00:00";
// end = moment(begin).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
// }
// var condition = {
// begin: begin,
// end: end,
// }
// // 查总数
// var _res = await this.dao.countStat(condition);
// if (_res.total == 0) {
// return system.getResultSuccess({
// count: 0,
// rows: []
// });
// }else{
// let _str=[];
// //这个id是交付商的id
// for (let item of _res.list) {
// _str.push(`'${item.deliverer_id}'`);
// }
// condition.list=_str.join(",");
// }
// // 查条数
// var startRow = (currentPage - 1) * pageSize;
// var list = await this.dao.queryStat(condition, startRow, pageSize);
// for (let item of list) {
// item.totalAmount=system.f2y(item.totalAmount || 0)
// }
// //计算每个
// // 设置已完成数量、办理中数量
// var delivererIds = [];
// for (var item of list) {
// //这个是交付商表的主键
// delivererIds.push(item.id);
// }
// var dstatusMap = await this.dao.statDeliverByStatus({
// begin: begin,
// end: end,
// delivererIds: delivererIds
// });
// for (var item of list) {
// item.completeCount = this.addStatCount(dstatusMap, item.id, ['1080',"1090"]);
// item.handlingCount = this.addStatCount(dstatusMap, item.id, ['1030','1040','1050','1060','1300']);
// }
// return system.getResultSuccess({
// count: _res.total,
// rows: list
// });
// } catch (error) {
// system.getResult(-1,`系统错误 错误信息 ${error}`);
// }
// }
// addStatCount(statusMap, deliverer_id, statuses) {
// var count = 0;
// if (!statuses || statuses.length == 0) {
// return count;
// }
// for (var status of statuses) {
// count = count + Number(statusMap[deliverer_id + "_" + status] || 0);
// }
// return count;
// }
// /**
// * 发票业务分配
// * @param {*} params
// * {
// * applyNo:"" //发票编号
// * nextStatus:"" //发票状态
// * }
// */
// async assignment(params) {
// let obj = await this.verification(params);
// let _apply = obj._apply;
// let _invoice = obj._invoice;
// try {
// let res;
// switch (params.nextStatus) {
// case "1040": //交付商以关闭
// res = await this.examine1040(params, _apply, _invoice);
// break;
// case "1050": //已开具
// res = await this.examine1050(params, _apply, _invoice);
// break;
// case "1060": //待审核
// res = await this.examine1060(params, _apply, _invoice);
// break;
// case "1080": //邮寄
// res = await this.examine1080(params, _apply, _invoice);
// break;
// case "1090": //已邮寄
// res = await this.examine1090(params, _apply, _invoice);
// break;
// default:
// res = system.getResult(null, "action_type参数错误");
// break;
// }
// return res;
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 交付商拒绝
// * @param {*} params
// * {
// * "id":"xxx",
// * "nextStatus":"1040",
// * ""
// * }
// * @param {*} _apply
// * //将申请表中的delivererId 变成null,
// * //将invoice和apply 中的状态待分配 1020
// * //添加拒绝原因
// */
// async examine1040(params, _apply, _invoice) {
// //更改发票表信息
// _invoice.status = this.trim(params.nextStatus);
// //添加拒绝原因
// let delivererData = {
// breakReason: this.trim(params.breakReason),
// id: _apply.delivererId
// };
// //更改申请表信息
// _apply.status = "1020";
// _apply.delivererId = null;
// let applyData = {};
// applyData.id = _apply.id;
// applyData.status = "1020";
// applyData.delivererId = '';
// let invoiceData = {};
// invoiceData.status = "1020";
// await this.db.transaction(async (t) => {
// //更新申请表状态
// await this.applyDao.update(applyData, t);
// //更新发票表状态
// await this.invoiceDao.update(invoiceData, t);
// //更新拒绝原因
// await this.dao.update(delivererData, t);
// }).catch(error => {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// });
// return system.getResultSuccess();
// }
// /**
// * 交付商开具
// * @param {*} params
// * @param {*} _apply
// */
// async examine1050(params, _apply, _invoice) {
// //更改发票表信息
// let invoiceData = {};
// invoiceData.id = params.id;
// invoiceData.invoiceNo = this.trim(params.invoiceNo);
// invoiceData.invoiceTime = this.trim(params.invoiceTime);
// invoiceData.invoiceImg = this.trim(params.invoiceImg);
// invoiceData.status = this.trim(params.nextStatus);
// //更改申请表信息
// let applyData = {};
// applyData.id = params.id;
// applyData.status = this.trim(params.nextStatus);
// applyData.customerStatus = this.trim(params.nextStatus);
// await this.db.transaction(async (t) => {
// //更新申请表状态
// await this.applyDao.update(applyData, t);
// //更新发票表状态
// await this.invoiceDao.update(invoiceData, t);
// }).catch(error => {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// });
// return system.getResultSuccess();
// }
// /**
// * 交付商提交审核
// * @param {*} params
// * {
// * nextStatus:xxx, //发票状态
// * id:xxx //发票id
// * }
// * @param {*} _apply
// */
// async examine1060(params, _apply, _invoice) {
// let invoiceData = {}, applyData = {};
// invoiceData.status = params.nextStatus;
// invoiceData.id = params.id;
// if (params.invoiceNo) {
// invoiceData.invoiceNo = this.trim(params.invoiceNo);
// }
// if (params.invoiceTime) {
// invoiceData.invoiceTime = this.trim(params.invoiceTime);
// }
// if (params.invoiceImg) {
// invoiceData.invoiceImg = this.trim(params.invoiceImg);
// }
// applyData.status = params.nextStatus;
// applyData.id = params.id;
// await this.db.transaction(async (t) => {
// //更新申请表状态
// await this.applyDao.update(applyData, t);
// //更新发票表状态
// await this.invoiceDao.update(invoiceData, t);
// }).catch(error => {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// });
// return system.getResultSuccess();
// }
// /**
// * 交付商已邮寄
// * @param {*} params
// * {
// * nextStatus:xxx, //发票状态
// * id:xxx //发票id
// * }
// * @param {*} _apply
// */
// async examine1080(params, _apply, _invoice) {
// let invoiceData = {}, applyData = {}, delivererData = {};
// //更改发票表信息
// invoiceData.status = this.trim(params.nextStatus);
// invoiceData.mailNo = this.trim(params.mailNo);
// invoiceData.id = this.trim(params.id);
// //更改申请表信息
// applyData.status = this.trim(params.nextStatus);
// applyData.id = this.trim(params.id);
// //交付商
// let _deliverer = await this.dao.findOne({ id: _apply.delivererId });
// delivererData.delivererMailNo = params.mailNo;
// delivererData.id = _deliverer.id;
// await this.db.transaction(async (t) => {
// //更新申请表状态
// await this.applyDao.update(applyData, t);
// //更新发票表状态
// await this.invoiceDao.update(invoiceData, t);
// //更新交付商信息
// await this.dao.update(delivererData, t);
// }).catch(error => {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// });
// return system.getResultSuccess();
// }
// /**
// * 检查状态是否正确
// * @param {*} params
// * {
// * id:xxx //发票id
// * nextStatus:xxx //发票状态
// * }
// */
// async verification(params) {
// let _apply = await this.applyDao.findOne({ id: params.id });
// let _invoice = await this.invoiceDao.findOne({ id: params.id });
// if (!_invoice) { return system.getResult(null, `此发票不存在`); }
// //获取当前状态 的对象
// let _status = this.invoiceStatus[_invoice.status];
// //如果不符合状态则退出
// if (params.nextStatus == "1300" || params.nextStatus == "1040" || params.nextStatus == "1010") {
// let obj = {
// _apply: _apply,
// _invoice: _invoice
// };
// return obj;
// } else if (!_status && _status.dstatus != params.nextStatus) {
// let name = this.invoiceStatus[this.invoiceStatus[_invoice.status].dstatus].name;
// return system.getResult(null, `更新状态错误,提示:当前状态的下一个状态是 ${name}`);
// }
// let obj = {
// _apply: _apply,
// _invoice: _invoice
// };
// return obj;
// }
// /**
// * 查看业务办理
// */
// async queryProcess(params) {
// let _apply = await this.applyDao.model.findOne({ where: { id: this.trim(params.id) }, attributes: ['delivererId'] });
// if (!_apply) {
// return system.getResult(null, `发票不存在`);
// }
// let _deliverer = await this.dao.findOne({ id: _apply.delivererId });
// return system.getResult(_deliverer);
// }
// /**
// * 平台更新邮寄地址
// * @param {*} params
// */
// async updateEmailNo(params) {
// try {
// let _apply = await this.applyDao.model.findOne({ where: { id: this.trim(params.id) }, attributes: ['delivererId'] });
// if (!_apply) { return system.getResult(null, `发票不存在,请确认发票ID`); }
// let _deliverer = await this.dao.model.findOne({ where: { id: _apply.delivererId } });
// if (!_deliverer) { return system.getResult(null, `交付商办理信息不存在,请联系管理员`); }
// _deliverer.platformMailNo = this.trim(params.platformMailNo);
// let res = await _deliverer.save();
// return system.getResult(res);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 交付商申请列表
// * @param {*} params
// */
// async delivererApplyInvoices(params) {
// try {
// if (params.delivererId) {
// params.delivererId=this.trim(params.delivererId);
// }
// if (this.trim(params.applyNo)) {
// params.applyNo=this.trim(params.applyNo);
// }
// if (this.trim(params.invoiceTime)) {
// params.invoiceTime=this.trim(params.invoiceTime);
// }
// if (this.trim(params.startTime)) {
// params.startTime=this.trim(params.startTime);
// }
// if (this.trim(params.endTime)) {
// params.endTime=this.trim(params.endTime);
// }
// if (this.trim(params.type)) {
// params.type=this.trim(params.type);
// }
// if (this.trim(params.status)) {
// params.status=this.trim(params.status);
// }
// params.statRow = (Number(this.trim(params.pageIndex)) - 1) * Number(this.trim(params.pageSize));
// if (params.statRow <= 0) { params.statRow = 0; }
// params.pageSize = Number(this.trim(params.pageSize)) <= 0 ? 10 : Number(this.trim(params.pageSize));
// let total = await this.dao.countApplyByParams(params);
// if (total[0].count == 0) {
// let res = { rows: [], count: 0 };
// return system.getResult(res);
// }
// let rows = await this.dao.delivererApplyInvoices(params);
// for (let item of rows) {
// if (item.type == "10") {
// item.type = "普通发票";
// } else if (item.type == "20") {
// item.type = "增值税专用发票";
// } else if (item.type == "30") {
// item.type = "电子发票";
// } else {
// item.type = "";
// }
// this.handleDate(item, ["invoice_time"], "YYYY-MM-DD HH:mm:ss", -8);
// this.dao.setRowCodeName(item, "status");
// }
// let res = { count: total[0].count, rows: rows };
// return system.getResult(res);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 查询发票明细(交付商)
// * @param {*} applyNo
// * @param {*} merchantId
// */
// async queryInvoiceDeliverer(applyNo, merchantId, id) {
// try {
// let _apply;
// if (merchantId && applyNo) {
// _apply = await this.applyDao.model.findOne({
// where: {
// merchantId: this.trim(merchantId),
// applyNo: this.trim(applyNo)
// },
// attributes: this._applyAttribute,
// raw: true
// });
// } else if (id) {
// _apply = await this.applyDao.model.findOne({
// where: { id: this.trim(id) },
// attributes: this._applyAttribute,
// raw: true
// });
// } else {
// _apply = null;
// }
// if (!_apply) { return system.getResult(null) }
// //格式化字典
// _apply.isBank = this.isBank == 1 ? '开户' : '未开户';
// if (_apply.type == 10) {
// _apply.type = "普通发票";
// } else if (_apply.type == 20) {
// _apply.type = "增值税专用发票";
// } else {
// _apply.type = "电子发票"
// }
// //格式化日期
// this.handleDate(_apply, ["invoiceTime"], "YYYY-MM-DD HH:mm:ss", -8);
// this.handleDate(_apply, ["createdAt"], "YYYY-MM-DD HH:mm:ss", -8);
// //查询平台审批内容
// let deliverer = await this.dao.model.findOne({
// where: { id: _apply.delivererId },
// raw: true,
// attributes: this._delivererAttribute
// });
// //查询发票信息
// let invoice = await this.invoiceDao.model.findOne({
// where: { id: _apply.id },
// attributes: this._invoiceAttribute,
// raw: true
// });
// this.handleDate(invoice, ["invoiceTime"], "YYYY-MM-DD HH:mm:ss", -8);
// this.handleDate(invoice, ["taxTime"], "YYYY-MM-DD HH:mm:ss", -8);
// invoice.complateTax = invoice.complateTax == 1 ? '已完税' : '未完税';
// deliverer.status = invoice.status;
// //格式化状态
// this.dao.setRowCodeName(deliverer, "status");
// _apply.deliverer = deliverer;
// delete invoice["status"];
// _apply.invoice = invoice;
// _apply.deliverer = deliverer || null;
// return system.getResult(_apply);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息:${error}`);
// }
// }
// /**
// * 发票列表(交付商)
// * @param {*} params
// */
// async delInvs(params) {
// if (params.delivererId) {
// params.delivererId=this.trim(params.delivererId);
// }
// if (this.trim(params.applyNo)) {
// params.applyNo=this.trim(params.applyNo);
// }
// if (this.trim(params.invoiceNo)) {
// params.invoiceNo=this.trim(params.invoiceNo);
// }
// if (this.trim(params.invoiceTime)) {
// params.invoiceTime=this.trim(params.invoiceTime);
// }
// if (this.trim(params.startTime)) {
// params.startTime=this.trim(params.startTime);
// }
// if (this.trim(params.endTime)) {
// params.endTime=this.trim(params.endTime);
// }
// if (this.trim(params.type)) {
// params.type=this.trim(params.type);
// }
// if (this.trim(params.status)) {
// params.status=this.trim(params.status);
// }
// if (this.trim(params.complateTax) == "1" || this.trim(params.complateTax) == "0") {
// params.complateTax=this.trim(params.complateTax);
// }
// if (this.trim(params.redStatus)) {
// params.red_status=this.trim(params.red_status);
// }
// params.statRow = (Number(this.trim(params.pageIndex)) - 1) * Number(this.trim(params.pageSize));
// if (params.statRow <= 0) { params.statRow = 0; }
// params.pageSize = Number(this.trim(params.pageSize)) <= 0 ? 10 : Number(this.trim(params.pageSize));
// try {
// //查总数
// let total = await this.dao.countInvoiceByParams(params);
// //查列表信息
// let rows = await this.dao.delivererInvoices(params);
// for (let item of rows) {
// if (item.type == 10) {
// item.type = '普通发票';
// } else if (item.type == 20) {
// item.type = '增值税专用发票';
// } else if (item.type == 30) {
// item.type = '电子发票';
// } else { }
// if (item.red_status == 1) {
// item.red_status = '未红冲';
// } else if (item.red_status == 2) {
// item.red_status = '红冲中';
// } else if (item.red_status == 3) {
// item.red_status = '红冲失败';
// } else if (item.red_status == 4) {
// item.red_status = '红冲成功';
// } else {
// item.red_status = '';
// }
// item.month = moment(item.invoice_time).month() + 1;
// item.complate_tax = item.complate_tax == 1 ? '已完成' : '未完成';
// this.handleDate(item, ["invoice_time"], "YYYY-MM-DD HH:mm:ss", -8);
// this.dao.setRowCodeName(item, "status");
// }
// let res = { count: total[0].count, rows: rows };
// return system.getResult(res);
// } catch (error) {
// return system.getResult(null, `系统错误 错误信息 ${error}`);
// }
// }
// /**
// * 列举所有日期
// * @param {*} end
// */
// getDays(end) {
// var days = [];
// var month = moment(end).format("YYYY-MM");
// var endDay = Number(moment(end).format("DD"));
// for (var i = 1; i <= endDay; i++) {
// if (i < 10) {
// days.push(month + "-0" + i);
// } else {
// days.push(month + "-" + i);
// }
// }
// return days;
// }
// // addStatCount(statusMap, statuses) {
// // var count = 0;
// // if(!statuses) {
// // return count;
// // }
// // for(var status of statuses) {
// // count = count + Number(statusMap[status] || 0);
// // }
// // return count;
// // }
// }
// module.exports = IinvoicedelivererService;
\ No newline at end of file
/**
* 1 算法文件命名规则 : calInvoice + 销售方编码
* 2 如果算法中途出现异常 则需直接return
* 3 如果算法顺利执行 返回参数中除包含必须的四个税值外,还需要包含一个累计不含税价字段 字段名称为 "x1"
* 4 此文件必须提供 calcInvoice 和 formatParams 方法
*/
const system = require("../../../system");
const applySve = system.getObject("service.invoice.applySve");
const Decimal = require('decimal.js');
const PER_TAX = 1; //个税
const VAL_TAX = 2; //增值税
/**
* 试算接口
* 注意:1 由于销售方类型不同 所以算法不同 需要对参数验证单独处理
*
* 税率的格式 传去除 %号的数值 比如:
* 96%, 则这个值就传 "taxCostPriRat"=96
*/
module.exports.calcInvoice = async (params) => {
try {
// 服务费率
let serviceRate = Number(params.serviceRate || 0);
let serviceCharge = Number((params.invoiceAmount * serviceRate) / 100).toFixed(0) || 0;
//计算累计不含税价 businessmenId,businessmenCreditCode,taxIncPriRat,invoiceAmount,type,valCalWay,perCalWay,invoiceTime
let x1 = await applySve.calAccumulatedPriceExcludingTax(params.businessmenId, params.businessmenType, params.businessmenCreditCode, params.taxIncPriRat, params.invoiceAmount, PER_TAX, null, params.perCalWay, params.invoiceTime);
console.log("个税 累计不含税价总额:" + x1);
//计算累计利润
let x2 = calAccumulatedProfit(x1, params.taxCostPriRat);
//根据 cumulativeProfit 查找对应梯度的个税税率和速算扣除数
let calRateRangeResForPer = calRateRange(x2, params.perIncTaxRange, PER_TAX);
let { taxPer, quiCalDed } = calRateRangeResForPer;
//计算年累计的个税
let cumulativeProfit = await applySve.calCumulativeProfit(params.businessmenId,params.businessmenType, PER_TAX, params.valCalWay);
//计算个税
let personalIncomeTax = calTaxPersonal(x2, taxPer, quiCalDed, cumulativeProfit);
/*计算增值税*/
//计算累计不含税价
let x3 = await applySve.calAccumulatedPriceExcludingTax(params.businessmenId,params.businessmenType, params.businessmenCreditCode, params.taxIncPriRat, params.invoiceAmount, VAL_TAX, params.valCalWay, null, params.invoiceTime);
console.log("增值税 累计不含税价总额:" + x3);
//根据 cumulativeProfitOfvalTax 查找对应梯度的个税税率
let calRateRangeResForVal = calRateRange(x3, params.valAddTaxRange, VAL_TAX);
let {valAddTaxRat,addTaxRat} = calRateRangeResForVal;
//计算年累计的增值税
let cumulativeProfitOfvalTax = await applySve.calCumulativeProfit(params.businessmenId,params.businessmenType, VAL_TAX, params.valCalWay);
//计算增值税
let valueAddedTax = calValTax(x3, valAddTaxRat, cumulativeProfitOfvalTax);
//附加税
let additionalTax = calAddTax(valueAddedTax, addTaxRat);
let res = {
x1: x1, //累计不含税价
serviceCharge: serviceCharge, //服务费
personalIncomeTax: personalIncomeTax, //个税
valueAddedTax: valueAddedTax, //附加税
additionalTax: additionalTax, //附加税
}
console.log("计算的各种税额:" + JSON.stringify(res));
return res;
} catch (error) {
return system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
/**
* 计算累计利润
* @param {*} x1 年累计金额
* @param {*} taxCostPriRat 核定成本费用率
*/
let calAccumulatedProfit = (x1, taxCostPriRat) => {
if (taxCostPriRat == 0) {
return 0;
} else {
return new Decimal(x1).mul(Decimal.sub(1, taxCostPriRat)).toFixed(2);
}
}
/**
* 计算税率值
* @param {*} amount 金额
* @param {*} taxRange 税率范围
* @param {*} type 类型 1:个税 2 增值税
*/
let calRateRange = (amount, taxRange, type) => {
let res = {};
if (type === PER_TAX) {
for (let item of taxRange) {
if (item.minValue <= amount && amount <= item.maxValue) {
res.taxPer = item.rate;
res.quiCalDed = item.quiCalDed;
break;
}
}
} else {
for (let item of taxRange) {
if (item.minValue <= amount && amount <= item.maxValue) {
res.valAddTaxRat = item.zengzhiRate;
res.addTaxRat = item.fujiaRate;
break;
}
}
}
return res;
}
/**
* 计算个税
* @param {*} x2 //累计利润
* @param {*} taxPer //个税税率
* @param {*} quiCalDed //速算扣除数
* @param {*} cumulativeProfit //累计缴纳的个税
*/
let calTaxPersonal=(x2, taxPer, quiCalDed, cumulativeProfit)=>{
x2 = x2 || 0;
quiCalDed = quiCalDed || 0;
taxPer = taxPer || 0;
cumulativeProfit = cumulativeProfit || 0;
if (taxPer == 0) {
return 0;
}
return (new Decimal(x2).mul(taxPer).div(100).sub(quiCalDed).sub(cumulativeProfit)).toFixed(2);
}
/**
* 计算增值税
* @param {*} x3 //累计不含说价
* @param {*} valAddTaxRat //增值税率
* @param {*} cumulativeProfitOfvalTax //累计缴纳的增值税
*/
let calValTax=(x3, valAddTaxRat, cumulativeProfitOfvalTax)=>{
if (valAddTaxRat == 0) {
return 0;
}
let res = new Decimal(x3).mul(valAddTaxRat).div(100).sub(cumulativeProfitOfvalTax).toFixed(2);
return res;
}
/**
* 计算附加税
* @param {*} valueAddedTax
* @param {*} addTaxRat
*/
let calAddTax=(valueAddedTax, addTaxRat)=>{
if (addTaxRat == 0) {
return 0
} else {
return new Decimal(valueAddedTax).mul(addTaxRat).div(100).toFixed(2);
}
}
/**
* 格式化参数
*/
module.exports.formatParams=(params)=>{
//后期添加格式化参数信息
params=verificationParams(params);
return params;
}
/**
* 校验各种费率 的合法性
* @param {*} params
* params
*/
let verificationParams = (params) => {
if (params.taxIncPriRat > 100 || params.serviceRate > 100 || params.taxCostPriRat > 100) {
return system.getResult(-1,`参数错误 费率不合法`);
} else {
params.taxIncPriRat = new Decimal(params.taxIncPriRat).div(100).toFixed(4);
params.taxCostPriRat = new Decimal(params.taxCostPriRat).div(100).toFixed(4);
params.serviceRate = new Decimal(params.serviceRate).div(100).toFixed(4);
}
return params;
}
\ No newline at end of file
//去除空格
module.exports.trim=(o)=> {
if(!o) {
return "";
}
return o.toString().trim();
}
\ No newline at end of file
/**
* 发票配置文件
*/
module.exports={
//根据销售方区别不同的配置信息
/**
* @MAX_AMOUNT 最大的金额 单位分
*
* 10:个体工商胡 20:自然人
*/
"10":{
MAX_AMOUNT:500000000,
WARNING_AMOUNT:400000000,
ruleCode:"10"
},
"20":{
MAX_AMOUNT:400000000,
WARNING_AMOUNT:300000000,
ruleCode:"10"
}
}
\ No newline at end of file
/**
* 发票计税算法-参数字典表
*/
const common = require("./common");
const system = require("../../system");
const valApi=require("./validate");
/**
* 算法分发器
*/
module.exports.dispatcher=async (params)=>{
try {
if(!params.businessmenType){
return system.getResult(-1,`参数错误 销售方类型不能为空`);
}
//加载算法类
let ruleCode = common.trim(params.ruleCode);
let filePath =`./algorithm/calInvoice${ruleCode}`;
console.log(filePath);
let calInvApi = require(filePath);
if(!calInvApi){
return system.getResult(-1,`系统错误 错误信息 算法不存在`);
}
let valCon ={};
//验证参数
valCon.businessmenType=common.trim(params.businessmenType);
valCon.businessmenId=common.trim(params.businessmenId);
valCon.businessmenCreditCode=common.trim(params.businessmenCreditCode);
valCon.invoiceAmount=common.trim(params.invoiceAmount);
//格式化参数
let calCon = calInvApi.formatParams(params);
if(calCon.hasOwnProperty("status")){
return calCon;
}
//计算参数
return await valApi.validate(valCon,calInvApi.calcInvoice,calCon);
} catch (error) {
console.log(error);
return system.getResult(-1,`参数错误 销售方类型不存在`);
}
}
const invoiceConfig = require("./invoiceConfig");
const system = require("../../system");
const common = require("./common");
const applySve = system.getObject("service.invoice.applySve");
const Decimal = require('decimal.js');
/**
* 开票验证
* 注意:验证和测试高度耦合(需要传入测试计算方法)
* @businessmenType 用户类别
* @businessmenId 销售方ID
* @businessmenCreditCode 非必添 销售方统一社会信用代码
* @invoiceAmount 开票金额
* @fn 试算方法
*/
module.exports.validate=async (params,fn,formate)=>{
let businessmenType = common.trim(params.businessmenType);
let businessmenId = common.trim(params.businessmenId);
let businessmenCreditCode = common.trim(params.businessmenCreditCode);
let invoiceAmount = Number(common.trim(params.invoiceAmount));
if(!businessmenType || !invoiceAmount || !businessmenId){
return system.getResult(-1,`参数错误 销售方信息参数有误 请核对参数`);
}
//获取配置文件信息
let busCon = invoiceConfig[businessmenType];
if(!busCon){
return system.getResult(-1,`参数错误 销售方类型不能为空`);
}
if(busCon.MAX_AMOUNT<params.invoiceAmount){
return system.getResult(-1,`开票金额超出最大范围`);
}
//试算获取累计含税价
let calAmount = await fn(formate);
if(calAmount.hasOwnProperty("status")){
return system.getResult(-1,`计算参数错误 请核对税率、金额以及销售方信息`);
}
_totalAmount = Decimal(calAmount.x1).plus(invoiceAmount).toNumber();
if(busCon.MAX_AMOUNT<_totalAmount){
return system.getResult(-1,`累计开票金额超出本年度最大金额`);
}
let warning = "";
if(busCon.WARNING_AMOUNT<_totalAmount){
warning=`累计开票金额达到${_totalAmount}`;
}
//查询发票状态 只有在状态为 '1000','0090' 或者信息不存在的情况下 验证成功 参考 applySve.verificationByBusinessmenCreditCode接口
let isLegal = await applySve.verificationInvoiceStatus(businessmenType,businessmenId,businessmenCreditCode);
if(!isLegal){
return system.getResult(-1,`验证失败 此用户存在未完成的发票`);
}
//移除累计税价
delete calAmount.x1;
if(warning){
calAmount.warning=warning;
}
return system.getResult(calAmount);
}
\ No newline at end of file
//平台审核发票申请失败 1010 但执行的状态是 1000
const system = require("../../../system");
const common = require("./common");
module.exports.auditFailForCustomer=async function (params){
console.log("第一次未审批 状态 1000");
let _apply = await common.applyVerification(params);
if(_apply.status==-1){return _apply;}
params.nextStatus = common.trim(params.nextStatus);
params.remark = common.trim(params.remark);
_apply.status = params.nextStatus;
_apply.customerStatus = params.nextStatus;
_apply.remark = params.remark;
if (params.nextStatus != "1010") {
return system.getResult(-1,`参数错误 请核对状态码`);
}
try {
await _apply.save();
return system.getResultSuccess();
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
\ No newline at end of file
const common = require("./common");
const system = require("../../../system");
const applyDao = system.getObject("db.invoice.applyDao");
const invoiceDao = system.getObject("db.invoice.invoiceDao");
const delivererDao = system.getObject("db.invoice.delivererDao");
//审核通过 1070
module.exports.auditSuccessForDeliverer=async function (params){
console.log("审核通过 1070");
let _apply =await common.applyVerification(params);
if(_apply.status==-1){return _apply;}
let delivererData = {},
applyData = {},
invoiceData = {};
let _deliverer = await delivererDao.findOne({
id: _apply.delivererId
});
delivererData.auditContent = common.trim(params.auditContent);
delivererData.delivererContent = common.trim(params.delivererContent);
delivererData.mailAddr = common.trim(params.mailAddr);
delivererData.mailMobile = common.trim(params.mailMobile);
delivererData.mailTo = common.trim(params.mailTo);
delivererData.mailEmail = common.trim(params.mailEmail);
delivererData.id = common.trim(_deliverer.id);
applyData.status = common.trim(params.nextStatus);
applyData.id = common.trim(params.id);
invoiceData.status = common.trim(params.nextStatus);
invoiceData.id = common.trim(params.id);
await applyDao.db.transaction(async (t) => {
//更新deliverer信息
await delivererDao.update(delivererData, t);
//更新 申请单和发票单
await applyDao.update(applyData, t);
await invoiceDao.update(invoiceData, t);
if (_apply.parentId) {
await invoiceDao.update({ id: _apply.parentId, redStatus: '4' }, t);
}
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
\ No newline at end of file
const system = require("../../../system");
const applyDao = system.getObject("db.invoice.applyDao");
const invoiceDao = system.getObject("db.invoice.invoiceDao");
const is = system.getObject("util.invoiceStatus");
const invoiceStatus = is.status;
/**
* 平台状态验证
*/
module.exports.applyVerification=async (params) =>{
let _apply = await applyDao.findOne({
id: trim(params.id)
});
if (!_apply) {
return system.getResult(null, `此发票不存在`);
}
//获取当前状态 的对象
let _status = invoiceStatus[_apply.status];
//如果不符合状态则退出
if (params.nextStatus == "1300" || params.nextStatus == "1040" || params.nextStatus == "1010") {
return _apply;
}
if (!_status && _status.next != params.nextStatus) {
let name = invoiceStatus[invoiceStatus[_apply.status].next].name;
return system.getResult(null, `更新状态错误,提示:当前状态的下一个状态是 ${name}`);
}
return _apply;
}
/**
* 交付商转该验证
*/
module.exports.delivererVerification=async (params)=> {
let _apply = await applyDao.findOne({ id: params.id });
let _invoice = await invoiceDao.findOne({ id: params.id });
if (!_invoice) { return system.getResult(null, `此发票不存在`); }
//获取当前状态 的对象
let _status = invoiceStatus[_invoice.status];
//如果不符合状态则退出
if (params.nextStatus == "1300" || params.nextStatus == "1040" || params.nextStatus == "1010") {
let obj = {
_apply: _apply,
_invoice: _invoice
};
return obj;
} else if (!_status && _status.dstatus != params.nextStatus) {
let name = invoiceStatus[invoiceStatus[_invoice.status].dstatus].name;
return system.getResult(null, `更新状态错误,提示:当前状态的下一个状态是 ${name}`);
}
let obj = {
_apply: _apply,
_invoice: _invoice
};
return obj;
}
function trim(o) {
if(!o) {
return "";
}
return o.toString().trim();
}
module.exports.trim=(o)=>{
if(!o) {
return "";
}
return o.toString().trim();
}
const system = require("../../../system");
const applyDao = system.getObject("db.invoice.applyDao");
const invoiceDao = system.getObject("db.invoice.invoiceDao");
const delivererDao = system.getObject("db.invoice.delivererDao");
const common = require("./common");
//交付商关闭 1040
module.exports.delivererClose = async function (params) {
console.log("交付商关闭 1040");
let obj = await common.delivererVerification(params);
if (obj.status == -1) { return obj; }
let _apply = obj._apply;
let _invoice = obj._invoice;
//更改发票表信息
_invoice.status = common.trim(params.nextStatus);
//添加拒绝原因
let delivererData = {
breakReason: common.trim(params.breakReason) || "",
id: _apply.delivererId
};
//更改申请表信息
_apply.status = "1020";
_apply.delivererId = null;
let applyData = {};
applyData.id = _apply.id;
applyData.status = "1020";
applyData.delivererId = '';
let invoiceData = {};
invoiceData.status = "1020";
invoiceData.id=_apply.id;
await delivererDao.db.transaction(async (t) => {
//更新申请表状态
await applyDao.update(applyData, t);
//更新发票表状态
await invoiceDao.update(invoiceData, t);
//更新拒绝原因
await delivererDao.update(delivererData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
\ No newline at end of file
const common = require("./common");
const system = require("../../../system");
const applyDao = system.getObject("db.invoice.applyDao");
//完成 1090
module.exports.finish=async function (params){
console.log("完成 1090");
let _apply =await common.applyVerification(params);
if(_apply.status==-1){return _apply;}
let applyData = {};
applyData.status = common.trim(params.nextStatus);
applyData.customerStatus = common.trim(params.nextStatus);
applyData.id = common.trim(params.id);
// invoiceData.status = common.trim(params.nextStatus);
// invoiceData.id=common.trim(params.id);
await applyDao.db.transaction(async (t) => {
//更新 申请单和发票单
await applyDao.update(applyData, t);
// await this.invoiceDao.update(invoiceData,t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
\ No newline at end of file
module.exports={
//客户未付款 0090
unAuditForCustomer:require('./unAuditForCustomer'),
//客户提交审核 状态1000
unAuditForCustomer:require('./unAuditForCustomer'),
//平台审核发票申请失败 1010
auditFailForCustomer:require('./auditFailForCustomer'),
//待分配 1020
toBeAllocated:require('./toBeAllocated'),
//待处理 1030
pendingDisposal:require('./pendingDisposal'),
//交付商关闭 1040
delivererClose:require('./delivererClose'),
//已开具 1050
invoiced:require('./invoiced'),
//待审核 1060
unAuditedForDeliverer:require('./unAuditedForDeliverer'),
//审核失败(平台第二次审核) 1300
unAuditFailForDeliverer:require('./unAuditFailForDeliverer'),
//审核通过 1070
auditSuccessForDeliverer:require('./auditSuccessForDeliverer'),
//已邮寄 1080
mailed:require('./mailed'),
//完成 1090
finish:require('./finish'),
//发票撤回 1100
withdrawInvoice:require('./withdrawInvoice'),
//红冲 1200
redRush:require('./redRush'),
}
\ No newline at end of file
const system = require("../../../system");
const applyDao = system.getObject("db.invoice.applyDao");
const invoiceDao = system.getObject("db.invoice.invoiceDao");
const delivererDao = system.getObject("db.invoice.delivererDao");
const common = require("./common");
//已开具 1050
module.exports.invoiced=async function(params){
console.log("已开具 1050");
let obj = await common.delivererVerification(params);
if(obj.status==-1){return obj;}
//更改发票表信息
let invoiceData = {};
invoiceData.id = params.id;
invoiceData.invoiceNo = common.trim(params.invoiceNo);
invoiceData.invoiceTime = common.trim(params.invoiceTime);
invoiceData.invoiceImg = common.trim(params.invoiceImg);
invoiceData.status = common.trim(params.nextStatus);
//更改申请表信息
let applyData = {};
applyData.id = params.id;
applyData.status = common.trim(params.nextStatus);
applyData.customerStatus = common.trim(params.nextStatus);
await delivererDao.db.transaction(async (t) => {
//更新申请表状态
await applyDao.update(applyData, t);
//更新发票表状态
await invoiceDao.update(invoiceData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
\ No newline at end of file
const system = require("../../../system");
const applyDao = system.getObject("db.invoice.applyDao");
const invoiceDao = system.getObject("db.invoice.invoiceDao");
const delivererDao = system.getObject("db.invoice.delivererDao");
const common = require("./common");
//已邮寄 1080
module.exports.mailed=async (params)=>{
console.log("已邮寄 1080");
let obj = await common.delivererVerification(params);
if(obj.status==-1){return obj;}
let _apply = obj._apply;
let invoiceData = {}, applyData = {}, delivererData = {};
//更改发票表信息
invoiceData.status = common.trim(params.nextStatus);
invoiceData.mailNo = common.trim(params.mailNo);
invoiceData.id = common.trim(params.id);
//更改申请表信息
applyData.status = common.trim(params.nextStatus);
applyData.id = common.trim(params.id);
//交付商
let _deliverer = await delivererDao.findOne({ id: _apply.delivererId });
delivererData.delivererMailNo = params.mailNo;
delivererData.id = _deliverer.id;
await delivererDao.db.transaction(async (t) => {
//更新申请表状态
await applyDao.update(applyData, t);
//更新发票表状态
await invoiceDao.update(invoiceData, t);
//更新交付商信息
await delivererDao.update(delivererData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
\ No newline at end of file
const common = require("./common");
const system = require("../../../system");
const applyDao = system.getObject("db.invoice.applyDao");
const invoiceDao = system.getObject("db.invoice.invoiceDao");
const delivererDao = system.getObject("db.invoice.delivererDao");
//待处理 1030
module.exports.pendingDisposal=async function (params){
console.log("待处理 1030");
if (!params.id || !params.delivererName) {
return system.getResult(-1, `系统错误 错误信息 ${error}`);
}
let _apply =await common.applyVerification(params);
if(_apply.status==-1){return _apply;}
await applyDao.db.transaction(async (t) => {
let _deliverer = await delivererDao.create({
invoiceId: _apply.id,
applyNo: _apply.applyNo,
merchantId: _apply.merchantId,
delivererId: common.trim(params.delivererId),
delivererName: common.trim(params.delivererName),
delivererAmount: Number(common.trim(params.delivererAmount))
}, t);
let applyData = {};
applyData.status = common.trim(params.nextStatus);
applyData.customerStatus = common.trim(params.nextStatus);
applyData.delivererId = common.trim(_deliverer.id);
applyData.id = common.trim(params.id);
//更新申请发票内容
await applyDao.update(applyData, t);
//更改发票状态
let invoiceData = {};
invoiceData.status = common.trim(params.nextStatus);
invoiceData.id = common.trim(params.id);
await invoiceDao.update(invoiceData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
\ No newline at end of file
//红冲 1200
module.exports.redRush=async (params)=>{
console.log("红冲 1200");
}
\ No newline at end of file
const common = require("./common");
const system = require("../../../system");
//待分配 1020
module.exports.toBeAllocated=async function(params){
console.log("//待分配 1020");
let _apply =await common.applyVerification(params);
if(_apply.status==-1){return _apply;}
if (Number(params.isPay) != 1) {
return system.getResult(null, `参数错误 请核对付款信息`);
}
params.nextStatus = common.trim(params.nextStatus);
params.remark = common.trim(params.remark);
_apply.status = params.nextStatus;
_apply.remark = params.remark;
_apply.isPay = Number(params.isPay);
try {
await _apply.save();
return system.getResultSuccess();
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
\ No newline at end of file
const system = require("../../../system");
const applyDao = system.getObject("db.invoice.applyDao");
const invoiceDao = system.getObject("db.invoice.invoiceDao");
const delivererDao = system.getObject("db.invoice.delivererDao");
const common = require("./common");
//待处理 1300(平台第二次审核失败)
module.exports.unAuditFailForDeliverer=async (params)=>{
console.log("待处理 1300");
let _apply =await common.applyVerification(params);
if(_apply.status==-1){return _apply;}
// let _apply = await applyDao.findOne({
// id: common.trim(params.id)
// });
if (!_apply) {
return system.getResult(null, `发票不存在,请核对发票ID`);
}
let _deliverer = await delivererDao.model.findOne({
where: {
id: _apply.delivererId
}
});
if (!_deliverer) {
return system.getResult(null, `交付商不存在,请联系管理员`);
}
await applyDao.db.transaction(async (t) => {
//更新 申请单和发票单
await applyDao.update({
status: "1300",
id: _apply.id
}, t);
await invoiceDao.update({
status: "1300",
id: _apply.id
}, t);
if (_deliverer.id) {
//提交审核信息
await delivererDao.update({
auditContent: common.trim(params.auditContent),
id: _deliverer.id
});
}
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
\ No newline at end of file
const applySve = require("../../../service/impl/invoice/applySve");
const common = require("./common");
//第一次未审批 状态 1000
module.exports.unAuditForCustomer=async function (params) {
console.log("第一次未审批 状态 1000");
let _apply =await common.applyVerification(params);
if(_apply.status==-1){return _apply;}
return applySve.examine1000(params, _apply);
}
\ No newline at end of file
const system = require("../../../system");
const applyDao = system.getObject("db.invoice.applyDao");
const invoiceDao = system.getObject("db.invoice.invoiceDao");
const delivererDao = system.getObject("db.invoice.delivererDao");
const common = require("./common");
//待审核 1060
module.exports.unAuditedForDeliverer=async (params)=>{
console.log("待审核 1060");
let obj = await common.delivererVerification(params);
if(obj.status==-1){return obj;}
let invoiceData = {}, applyData = {};
invoiceData.status = params.nextStatus;
invoiceData.id = params.id;
if (params.invoiceNo) {
invoiceData.invoiceNo = common.trim(params.invoiceNo);
}
if (params.invoiceTime) {
invoiceData.invoiceTime = common.trim(params.invoiceTime);
}
if (params.invoiceImg) {
invoiceData.invoiceImg = common.trim(params.invoiceImg);
}
applyData.status = params.nextStatus;
applyData.id = params.id;
await delivererDao.db.transaction(async (t) => {
//更新申请表状态
await applyDao.update(applyData, t);
//更新发票表状态
await invoiceDao.update(invoiceData, t);
}).catch(error => {
return system.getResult(null, `系统错误 错误信息 ${error}`);
});
return system.getResultSuccess();
}
\ No newline at end of file
module.exports = {
// "0090": "未付款",
// "1000": "待审核",
// "1010": "审核不通过",
// "1020": "待分配",
// "1030": "待处理",
// "1040": "交付商关闭",
// "1050": "已开具",
// "1060": "待审核",
// "1300": "审核失败(平台第二次审核)",
// "1070": "审核通过",
// "1080": "已邮寄",
// "1090": "完成",
// "1100": "发票撤回",
// "1200": "红冲",
"0090": "unAuditForCustomer",
"1000": "unAuditForCustomer",
"1010": "auditFailForCustomer",
"1020": "toBeAllocated",
"1030": "pendingDisposal",
"1040": "delivererClose",
"1050": "invoiced",
"1060": "unAuditedForDeliverer",
"1300": "unAuditFailForDeliverer",
"1070": "auditSuccessForDeliverer",
"1080": "mailed",
"1090": "finish",
"1100": "withdrawInvoice",
"1200": "redRush",
};
\ No newline at end of file
//发票撤回 1100
const applySve = require("../../../service/impl/invoice/applySve");
const common = require("./common");
module.exports.withdrawInvoice=async function(params){
console.log("发票撤回 1100 ");
}
\ No newline at end of file
const StateBase = require('./stateBase');
const API = require('./actions/index');
const AllState =require('./actions/util');
const system = require("../../system");
class Context {
constructor(){
this.stateBase=new StateBase(API);
this.allState=AllState;
}
async request(params){
let methodName = this.allState[params.nextStatus];
if(!methodName){
return system.getResult(-1,`参数错误 状态码错误`);
}
let _self = this.stateBase.setState(methodName);
return await _self.doAction(params);
}
}
module.exports=Context;
\ No newline at end of file
const system = require("../../system");
class StateBase{
constructor(api){
this.actions=api;
this.curState=null;
}
//改变状态
setState(curState){
this.curState=curState;
return this;
}
//执行操作
async doAction(params){
try {
if(this.actions[this.curState]){
return await this.actions[this.curState][this.curState].apply(this,[params]);
}else{
return system.getResult(-1,`系统错误 未找到处理器`);
}
} catch (error) {
return system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
}
module.exports = StateBase;
const strategies = require('./strategiesBase');
/**
* 增值税的环境类
*
* 将注册的说有增值税算法实现都通过环境类调用
* @param{*} businessmenType 销售方类型
* @param{*} params 算法的参数
*/
class ContextAdditionalTax{
constructor(){
console.log("初始化 附加税环境类 ContextAdditionalTax");
}
async doAction (businessmenType,params){
return await strategies[businessmenType]['calcInvoice'](params);
}
}
module.exports=ContextAdditionalTax;
\ No newline at end of file
const system = require("../../../../system");
const Decimal = require('decimal.js');
const PER_TAX = 1; //个税
/**
* 附加税算法
* 注意:1 由于销售方类型不同 所以算法不同 需要对参数验证单独处理
*
* 税率的格式 传去除 %号的数值 比如:
* 96%, 则这个值就传 "taxCostPriRat"=96
*/
module.exports.calcInvoice = (params) => {
try {
//根据 cumulativeProfitOfvalTax 查找对应梯度的个税税率
let calRateRangeResForVal = calRateRange(params.valueAddedTax, params.valAddTaxRange, null);
let {addTaxRat} = calRateRangeResForVal;
//参数验证
verificationParams(params.valueAddedTax,addTaxRat);
//附加税
let res = calAddTax(Number(params.valueAddedTax || 0), Number(addTaxRat || 0));
return system.getResult(res);
} catch (error) {
return system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
/**
* 计算附加税
* @param {*} valueAddedTax
* @param {*} addTaxRat
*/
let calAddTax=(valueAddedTax, addTaxRat)=>{
if (addTaxRat == 0) {
return 0
} else {
return new Decimal(valueAddedTax).mul(addTaxRat).div(100).toFixed(2);
}
}
/**
* 计算税率值
* @param {*} amount 金额
* @param {*} taxRange 税率范围
* @param {*} type 类型 1:个税 2 增值税
*/
let calRateRange = (amount, taxRange, type=2) => {
let res = {};
if (type === PER_TAX) {
for (let item of taxRange) {
if (item.minValue <= amount && amount <= item.maxValue) {
res.taxPer = item.rate;
res.quiCalDed = item.quiCalDed;
break;
}
}
} else {
for (let item of taxRange) {
if (item.minValue <= amount && amount <= item.maxValue) {
res.valAddTaxRat = item.zengzhiRate;
res.addTaxRat = item.fujiaRate;
break;
}
}
}
return res;
}
/**
* 校验各种费率 的合法性
* @param {*} params
* params
*/
let verificationParams = (valueAddedTax,addTaxRat) => {
if(addTaxRat > 100){
system.getResult(-1,`参数错误 销售方类型非法`);
}
}
\ No newline at end of file
const system = require("../../../../system");
const Decimal = require('decimal.js');
/**
* 附加税算法
* 注意:1 由于销售方类型不同 所以算法不同 需要对参数验证单独处理
*
* 税率的格式 传去除 %号的数值 比如:
* 96%, 则这个值就传 "taxCostPriRat"=96
*/
module.exports.calcInvoice = (valueAddedTax,addTaxRat) => {
try {
//参数验证
verificationParams(valueAddedTax,addTaxRat);
//附加税
return calAddTax(valueAddedTax, addTaxRat);
} catch (error) {
return system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
/**
* 计算附加税
* @param {*} valueAddedTax
* @param {*} addTaxRat
*/
let calAddTax=(valueAddedTax, addTaxRat)=>{
if (addTaxRat == 0) {
return 0
} else {
return new Decimal(valueAddedTax).mul(addTaxRat).div(100).toFixed(2);
}
}
/**
* 校验各种费率 的合法性
* @param {*} params
* params
*/
let verificationParams = (valueAddedTax,addTaxRat) => {
if(params.addTaxRat > 1){
system.getResult(-1,`参数错误 销售方类型非法`);
}
params.addTaxRat = Number(addTaxRat || 0);
params.valueAddedTax = Number(valueAddedTax || 0);
}
\ No newline at end of file
/**
* 导出所有的实现类
*/
module.exports={
//个体工商户
"calInvoice10":require("./calInvoice10"),
//自然人
"calInvoice20":require("./calInvoice20"),
}
\ No newline at end of file
/**
* 定义个增值税的所有接口
*
* 格式:JSON
* key: businessmenType (销售方类型)
* value:Fuction
*
* ps:如果要增加新的增值税算法,需要在此注册
*/
const impl = require('./impl');
module.exports={
//个体工商户
'10': impl.calInvoice10,
//自然人
'20': impl.calInvoice20
}
\ No newline at end of file
var Invoice = require("./invoice");
var system = require("../../system");
var ContextFactory = require("./contextFactory");
/**
* 计算类
*
* 组装的Invoice对象
*/
class Calculation{
constructor(params){
console.log("初始化计算类")
this.contextFactory = new ContextFactory();
this.invoice = new Invoice();
this.init(params);
}
getInvoice(){
return this.invoice;
}
/**
* @param {*} params
* calculation
* @param.calNames 计算种类 是 增值税:valueAddedTax 附加税:additionalTax
*/
init (params){
if(params.calNames instanceof Array){
for (let item of params.calNames) {
if(item=="valueAddedTax"){
this.invoice.setContextValueAddedTax(this.contextFactory.getInstance(system.trim(item)));
}else if(item=="additionalTax"){
this.invoice.setContextAdditionalTax(this.contextFactory.getInstance(system.trim(item)));
}else{
system.getResult(-1,`参数错误 非法的计算类型`);
}
}
}else {
if(system.trim(params.calNames) != "valueAddedTax" && system.trim(params.calNames) != "additionalTax"
&& system.trim(params.calNames) != "individualIncomeTax"){
system.getResult(-1,`参数错误 非法的计算类型`);
}else{
if(params.calNames=="valueAddedTax"){
this.invoice.setContextValueAddedTax(this.contextFactory.getInstance(system.trim(params.calNames)));
}else if(params.calNames=="additionalTax"){
this.invoice.setContextAdditionalTax(this.contextFactory.getInstance(system.trim(params.calNames)));
}else{
system.getResult(-1,`参数错误 非法的计算类型`);
}
}
}
}
}
module.exports=Calculation;
\ No newline at end of file
/**
* 环境工厂类
*/
const ContextAdditionalTax = require("./additionalTax/contextAdditionalTax");
const ContextValueAddedTax = require("./valueAddedTax/contextValueAddedTax");
class ContextFactory {
constructor() {
// this.context = context;
}
getInstance(context) {
let bean = null;
switch (context) {
case "additionalTax":
bean = new ContextAdditionalTax();
break;
case "valueAddedTax":
bean = new ContextValueAddedTax();
break;
default:
console.log("算法环境初始化失败");
bean = null
}
return bean;
}
}
module.exports=ContextFactory;
\ No newline at end of file
/**
* 发票类
*
* 构造器参数: contextAdditionalTax, //附加税上下文
* contextValueAddedTax, //增值税上下文
* contextIndividualIncomeTax //个人所得税上下文
*/
class Invoice {
constructor(contextAdditionalTax,contextValueAddedTax,contextIndividualIncomeTax){
this.contextAdditionalTax = contextAdditionalTax || null;
this.contextValueAddedTax = contextValueAddedTax || null;
// this.contextIndividualIncomeTax = contextIndividualIncomeTax;
}
setContextAdditionalTax(contextAdditionalTax){
this.contextAdditionalTax=contextAdditionalTax;
}
setContextValueAddedTax(contextValueAddedTax){
this.contextValueAddedTax=contextValueAddedTax;
}
//计算附加税
async doActionAddtitionalTax(params){
return await this.contextAdditionalTax.doAction(params.businessmenType,params);
}
//计算增值税
async doActionValueAddedTax(params){
return await this.contextValueAddedTax.doAction(params.businessmenType,params);
}
//计算个人所的税
// async doActionIndividualIncomeTax(params.businessmenType,params){
// }
}
module.exports=Invoice;
\ No newline at end of file
const strategies = require('./strategiesBase');
/**
* 增值税的环境类
*
* 将注册的说有增值税算法实现都通过环境类调用
* @param{*} businessmenType 销售方类型
* @param{*} params 算法的参数
*/
class ContextValueAddedTax{
constructor (){
console.log("初始化 增资税环境类 ContextValueAddedTax");
}
async doAction (businessmenType,params){
return await strategies[businessmenType]['calcInvoice'](params);
}
}
module.exports=ContextValueAddedTax
\ No newline at end of file
/**
* 1 算法文件命名规则 : calInvoice + 销售方编码
* 2 如果算法中途出现异常 则需直接return
* 3 如果算法顺利执行 返回参数中除包含必须的四个税值外,还需要包含一个累计不含税价字段 字段名称为 "x1"
* 4 此文件必须提供 calcInvoice 和 formatParams 方法
*/
const system = require("../../../../system");
const applySve = system.getObject("service.invoice.applySve");
const Decimal = require('decimal.js');
const VAL_TAX = 2; //增值税
const PER_TAX = 1; //个税
/**
* 增值税 businessmen10(个体工商户) 算法实现
* 注意:1 由于销售方类型不同 所以算法不同 需要对参数验证单独处理
*/
module.exports.calcInvoice = async (params) => {
try {
//校验参数
verificationParams(params);
//计算累计不含税价
/**
* 累计不含税价
* @param {*} businessmenId 商户id
* @param {*} businessmenType 商户类型
* @param {*} businessmenCreditCode 统一社会信用代码
* @param {*} taxIncPriRat 不含税价百分比
* @param {*} invoiceAmount 发票总额
* @param {*} type 计算类型 1:个税 2:增值税
* @param {*} valCalWay 增值税计算类型 1:月 2:季度 3:年
* @param {*} perCalWay 个人所的税计算类型 1:月 2:季度 3:年
* @param {*} invoiceTime 格式 YYYY-MM-DD hh:mm:ss
*/
let x3 = await applySve.calAccumulatedPriceExcludingTax(params.businessmenId,params.businessmenType, params.businessmenCreditCode,
params.taxIncPriRat, params.invoiceAmount, VAL_TAX, params.valCalWay, null, params.invoiceTime);
console.log("增值税 累计不含税价总额:" + x3);
//根据 cumulativeProfitOfvalTax 查找对应梯度的个税税率
let calRateRangeResForVal = calRateRange(x3, params.valAddTaxRange, VAL_TAX);
let {valAddTaxRat} = calRateRangeResForVal;
//计算年累计的增值税
let cumulativeProfitOfvalTax = await applySve.calCumulativeProfit(params.businessmenId,params.businessmenType, VAL_TAX, params.valCalWay);
//计算增值税
let valueAddedTax = calValTax(x3, valAddTaxRat, cumulativeProfitOfvalTax);
return system.getResult(valueAddedTax);
} catch (error) {
return system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
/**
* 计算税率值
* @param {*} amount 金额
* @param {*} taxRange 税率范围
* @param {*} type 类型 1:个税 2 增值税
*/
let calRateRange = (amount, taxRange, type) => {
let res = {};
if (type === PER_TAX) {
for (let item of taxRange) {
if (item.minValue <= amount && amount <= item.maxValue) {
res.taxPer = item.rate;
res.quiCalDed = item.quiCalDed;
break;
}
}
} else {
for (let item of taxRange) {
if (item.minValue <= amount && amount <= item.maxValue) {
res.valAddTaxRat = item.zengzhiRate;
res.addTaxRat = item.fujiaRate;
break;
}
}
}
return res;
}
/**
* 计算增值税
* @param {*} x3 //累计不含说价
* @param {*} valAddTaxRat //增值税率
* @param {*} cumulativeProfitOfvalTax //累计缴纳的增值税
*/
let calValTax=(x3, valAddTaxRat, cumulativeProfitOfvalTax)=>{
if (valAddTaxRat == 0) {
return 0;
}
let res = new Decimal(x3).mul(valAddTaxRat).div(100).sub(cumulativeProfitOfvalTax).toFixed(2);
return res;
}
/**
* 校验各种费率 的合法性
* @param {*} params
* params
*/
let verificationParams = (params) => {
if(params.businessmenType != "10"){
system.getResult(-1,`参数错误 销售方类型非法`);
}
if(!params.businessmenCreditCode){
system.getResult(-1,`参数错误 销售方统一社会信用代码非法`);
}
if(params.taxIncPriRat>1){
system.getResult(-1,`参数错误 不含税价百分比不能大于1 例如 3% ,请传 0.03`);
}
if(!params.invoiceAmount){
system.getResult(-1,`参数错误 发票金额非法`);
}
}
\ No newline at end of file
/**
* 1 算法文件命名规则 : calInvoice + 销售方编码
* 2 如果算法中途出现异常 则需直接return
* 3 如果算法顺利执行 返回参数中除包含必须的四个税值外,还需要包含一个累计不含税价字段 字段名称为 "x1"
* 4 此文件必须提供 calcInvoice 和 formatParams 方法
*/
const system = require("../../../../system");
const applySve = system.getObject("service.invoice.applySve");
const Decimal = require('decimal.js');
const VAL_TAX = 2; //增值税
/**
* 增值税 businessmen10(个体工商户) 算法实现
* 注意:1 由于销售方类型不同 所以算法不同 需要对参数验证单独处理
*/
module.exports.calcInvoice = async (params) => {
try {
//校验参数
verificationParams();
//计算累计不含税价
/**
* 累计不含税价
* @param {*} businessmenId 商户id
* @param {*} businessmenType 商户类型
* @param {*} businessmenCreditCode 统一社会信用代码
* @param {*} taxIncPriRat 不含税价百分比
* @param {*} invoiceAmount 发票总额
* @param {*} type 计算类型 1:个税 2:增值税
* @param {*} valCalWay 增值税计算类型 1:月 2:季度 3:年
* @param {*} perCalWay 个人所的税计算类型 1:月 2:季度 3:年
* @param {*} invoiceTime 格式 YYYY-MM-DD hh:mm:ss
*/
let x3 = await applySve.calAccumulatedPriceExcludingTax(params.businessmenId,params.businessmenType, params.businessmenCreditCode,
params.taxIncPriRat, params.invoiceAmount, VAL_TAX, params.valCalWay, null, params.invoiceTime);
console.log("增值税 累计不含税价总额:" + x3);
//根据 cumulativeProfitOfvalTax 查找对应梯度的个税税率
let calRateRangeResForVal = calRateRange(x3, params.valAddTaxRange, VAL_TAX);
let {valAddTaxRat} = calRateRangeResForVal;
//计算年累计的增值税
let cumulativeProfitOfvalTax = await applySve.calCumulativeProfit(params.businessmenId,params.businessmenType, VAL_TAX, params.valCalWay);
//计算增值税
let valueAddedTax = calValTax(x3, valAddTaxRat, cumulativeProfitOfvalTax);
return valueAddedTax;
} catch (error) {
return system.getResult(-1,`系统错误 错误信息 ${error}`);
}
}
/**
* 计算税率值
* @param {*} amount 金额
* @param {*} taxRange 税率范围
* @param {*} type 类型 1:个税 2 增值税
*/
let calRateRange = (amount, taxRange, type) => {
let res = {};
if (type === PER_TAX) {
for (let item of taxRange) {
if (item.minValue <= amount && amount <= item.maxValue) {
res.taxPer = item.rate;
res.quiCalDed = item.quiCalDed;
break;
}
}
} else {
for (let item of taxRange) {
if (item.minValue <= amount && amount <= item.maxValue) {
res.valAddTaxRat = item.zengzhiRate;
res.addTaxRat = item.fujiaRate;
break;
}
}
}
return res;
}
/**
* 计算增值税
* @param {*} x3 //累计不含说价
* @param {*} valAddTaxRat //增值税率
* @param {*} cumulativeProfitOfvalTax //累计缴纳的增值税
*/
let calValTax=(x3, valAddTaxRat, cumulativeProfitOfvalTax)=>{
if (valAddTaxRat == 0) {
return 0;
}
let res = new Decimal(x3).mul(valAddTaxRat).div(100).sub(cumulativeProfitOfvalTax).toFixed(2);
return res;
}
/**
* 校验各种费率 的合法性
* @param {*} params
* params
*/
let verificationParams = (params) => {
if(params.businessmenType != "10"){
system.getResult(-1,`参数错误 销售方类型非法`);
}
if(!params.businessmenCreditCode){
system.getResult(-1,`参数错误 销售方统一社会信用代码非法`);
}
if(params.taxIncPriRat>1){
system.getResult(-1,`参数错误 不含税价百分比不能大于1 例如 3% ,请传 0.03`);
}
if(!params.invoiceAmount){
system.getResult(-1,`参数错误 发票金额非法`);
}
}
\ No newline at end of file
/**
* 导出所有的实现类
*/
module.exports={
//个体工商户
"calInvoice10":require("./calInvoice10"),
//自然人
"calInvoice20":require("./calInvoice20"),
}
\ No newline at end of file
/**
* 定义个增值税的所有接口
*
* 格式:JSON
* key: businessmenType (销售方类型)
* value:Fuction
*
* ps:如果要增加新的增值税算法,需要在此注册
*/
const impl = require('./impl');
module.exports={
//个体工商户
'10': impl.calInvoice10,
//自然人
'20': impl.calInvoice20
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment