salix/back/methods/dms/saveSign.js

147 lines
4.2 KiB
JavaScript
Raw Normal View History

const md5 = require('md5');
module.exports = Self => {
Self.remoteMethodCtx('saveSign', {
description: 'Save sign',
accessType: 'WRITE',
accepts:
[
{
arg: 'singContent',
type: 'string',
required: true,
description: 'The sign content'
}, {
arg: 'tickets',
type: ['number'],
required: true,
description: 'The tickets'
}, {
arg: 'signedTime',
type: 'date',
description: 'The signed time'
}, {
arg: 'addressFk',
type: 'number',
required: true,
description: 'The address fk'
}
],
returns: {
type: 'Object',
root: true
},
http: {
path: `/saveSign`,
verb: 'POST'
}
});
async function createGestDoc(ticketId, userFk) {
if (!gestDocExists(ticketId)) {
const query = `SELECT t.warehouseFk,
t.companyFk,
c.name,
r.id
FROM vn.ticket t
JOIN vn.client c ON t.clientFk = c.id
JOIN vn.route r ON t.routeFk = r.id
WHERE t.id = ?`;
const result = await Self.rawSql(query, [ticketId]);
const warehouseFk = result[0].warehouseFk;
const companyFk = result[0].companyFk;
const client = result[0].name;
const route = result[0].id;
const queryDmsType = `SELECT id
FROM vn.dmsType
WHERE code='Ticket'`;
const resultDmsType = await Self.rawSql(queryDmsType, []);
const dmsInsert = `INSERT INTO vn.dms
(dmsTypeFk, reference, description, companyFk, warehouseFk, workerFk)
VALUES (?, ?, ?, ?, ?, ?)`;
const resultDms = await Self.rawSql(
dmsInsert,
[
resultDmsType[0].id, ticketId,
`Ticket ${ticketId} Cliente ${client} Ruta ${route}`,
companyFk, warehouseFk, userFk
]
);
return resultDms.insertId;
}
return null;
}
async function gestDocExists(ticket) {
const dMSQuery = `SELECT dmsFk as id FROM vn.ticketDms WHERE ticketFk = ?`;
const result = await Self.rawSql(dMSQuery, [ticket]);
if (result.length > 0) {
const isSigned = await Self.rawSql(
`SELECT isSigned FROM vn.ticket WHERE id = ?`, [ticket]
);
if (isSigned[0].isSigned)
return true;
else
deleteFromGestDoc(ticket);
}
return false;
}
async function deleteFromGestDoc(ticket) {
await Self.rawSql(
`DELETE FROM vn.dms WHERE reference = ?`, [ticket]
);
}
Self.saveSign = async(ctx, signContent, tickets, signedTime, addressFk) => {
let tx = await Self.beginTransaction({});
const userId = ctx.req.accessToken.userId;
const dmsDir = await Self.rawSql(`SELECT dmsDir FROM hedera.config`);
for (let i = 0; i < tickets.length; i++) {
const call = `SELECT alertLevel FROM vn.ticketState WHERE ticketFk = ${tickets[i]}`;
const result = await Self.rawSql(call);
alertLevel = result[0].alertLevel;
signedTime ? signedTime != undefined : signedTime = new Date();
if (alertLevel >= 2) {
if (!await gestDocExists(tickets[i])) {
const id = createGestDoc(tickets[i], userId);
const hashDir = md5(id).substring(0, 3);
const dir = `${dmsDir[0].dmsDir}/${hashDir}`;
if (!fs.existsSync(dir))
fs.mkdirSync(dir);
}
}
}
try {
if (tx) await tx.commit();
return {
success: true,
message: 'Sign saved'
};
} catch (err) {
await tx.rollback();
throw err;
}
};
};