Merge branch 'dev' into 4090-global_invoincing
gitea/salix/pipeline/head There was a failure building this commit Details

This commit is contained in:
Javi Gallego 2022-10-06 13:01:56 +02:00
commit d73dab3454
410 changed files with 68775 additions and 20730 deletions

View File

@ -8,7 +8,7 @@ module.exports = Self => {
},
http: {
path: `/notifyIssues`,
verb: 'GET'
verb: 'POST'
}
});

View File

@ -10,7 +10,7 @@ module.exports = Self => {
},
http: {
path: `/sendQueued`,
verb: 'GET'
verb: 'POST'
}
});
@ -33,14 +33,14 @@ module.exports = Self => {
await Self.sendCheckingUserStatus(chat);
await updateChat(chat, sentStatus);
} catch (error) {
await updateChat(chat, errorStatus);
await updateChat(chat, errorStatus, error);
}
} else {
try {
await Self.sendMessage(chat.senderFk, chat.recipient, chat.message);
await updateChat(chat, sentStatus);
} catch (error) {
await updateChat(chat, errorStatus);
await updateChat(chat, errorStatus, error);
}
}
}
@ -75,7 +75,7 @@ module.exports = Self => {
const channelName = department && department.chatName;
if (channelName)
return Self.sendMessage(chat.senderFk, `#${channelName}`, `@${recipient.name}${message}`);
return Self.sendMessage(chat.senderFk, `#${channelName}`, `@${recipient.name}${chat.message}`);
else
return Self.sendMessage(chat.senderFk, `@${recipient.name}`, chat.message);
} else
@ -127,12 +127,14 @@ module.exports = Self => {
*
* @param {object} chat - The chat
* @param {string} status - The new status
* @param {string} error - The error
* @return {Promise} - The request promise
*/
async function updateChat(chat, status) {
async function updateChat(chat, status, error) {
return chat.updateAttributes({
status: status,
attempts: ++chat.attempts
attempts: ++chat.attempts,
error: error
});
}

View File

@ -2,10 +2,10 @@ const models = require('vn-loopback/server/server').models;
describe('ticket getCollection()', () => {
it('should return a list of collections', async() => {
let ctx = {req: {accessToken: {userId: 1106}}};
let ctx = {req: {accessToken: {userId: 1107}}};
let response = await models.Collection.getCollection(ctx);
expect(response.length).toBeGreaterThan(0);
expect(response[0].collectionFk).toEqual(1);
expect(response[0].collectionFk).toEqual(3);
});
});

View File

@ -12,7 +12,7 @@ module.exports = Self => {
},
http: {
path: `/deleteTrashFiles`,
verb: 'GET'
verb: 'POST'
}
});
@ -53,8 +53,12 @@ module.exports = Self => {
const pathHash = DmsContainer.getHash(dms.id);
const dmsContainer = await DmsContainer.container(pathHash);
const dstFile = path.join(dmsContainer.client.root, pathHash, dms.file);
try {
await fs.unlink(dstFile);
} catch (err) {
continue;
}
const dstFolder = path.join(dmsContainer.client.root, pathHash);
await fs.unlink(dstFile);
try {
await fs.rmdir(dstFolder);
await dms.destroy(myOptions);

View File

@ -12,7 +12,7 @@ module.exports = Self => {
},
http: {
path: `/updateData`,
verb: 'GET'
verb: 'POST'
}
});
@ -20,83 +20,93 @@ module.exports = Self => {
const models = Self.app.models;
// Get files checksum
const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileConfig');
const tx = await Self.beginTransaction({});
const updatableFiles = [];
for (const file of files) {
const fileChecksum = await getChecksum(file);
try {
const options = {transaction: tx};
const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileConfig', null, options);
if (file.checksum != fileChecksum) {
updatableFiles.push({
name: file.name,
checksum: fileChecksum
});
} else
console.debug(`File already updated, skipping...`);
}
const updatableFiles = [];
for (const file of files) {
const fileChecksum = await getChecksum(file);
if (updatableFiles.length === 0)
return false;
// Download files
const container = await models.TempContainer.container('edi');
const tempPath = path.join(container.client.root, container.name);
let remoteFile;
let tempDir;
let tempFile;
const fileNames = updatableFiles.map(file => file.name);
const tables = await Self.rawSql(`
SELECT fileName, toTable, file
FROM edi.tableConfig
WHERE file IN (?)`, [fileNames]);
for (const table of tables) {
const fileName = table.file;
console.debug(`Downloading file ${fileName}...`);
remoteFile = `codes/${fileName}.ZIP`;
tempDir = `${tempPath}/${fileName}`;
tempFile = `${tempPath}/${fileName}.zip`;
try {
await fs.readFile(tempFile);
} catch (error) {
if (error.code === 'ENOENT') {
const downloadOutput = await downloadFile(remoteFile, tempFile);
if (downloadOutput.error)
continue;
}
if (file.checksum != fileChecksum) {
updatableFiles.push({
name: file.name,
checksum: fileChecksum
});
} else
console.debug(`File already updated, skipping...`);
}
console.debug(`Extracting file ${fileName}...`);
await extractFile(tempFile, tempDir);
if (updatableFiles.length === 0)
return false;
console.debug(`Updating table ${table.toTable}...`);
await dumpData(tempDir, table);
}
// Download files
const container = await models.TempContainer.container('edi');
const tempPath = path.join(container.client.root, container.name);
// Update files checksum
for (const file of updatableFiles) {
await Self.rawSql(`
UPDATE edi.fileConfig
SET checksum = ?
WHERE name = ?`,
[file.checksum, file.name]);
}
let remoteFile;
let tempDir;
let tempFile;
// Clean files
try {
await fs.remove(tempPath);
const fileNames = updatableFiles.map(file => file.name);
const tables = await Self.rawSql(`
SELECT fileName, toTable, file
FROM edi.tableConfig
WHERE file IN (?)`, [fileNames], options);
for (const table of tables) {
const fileName = table.file;
remoteFile = `codes/${fileName}.ZIP`;
tempDir = `${tempPath}/${fileName}`;
tempFile = `${tempPath}/${fileName}.zip`;
try {
await fs.readFile(tempFile);
} catch (error) {
if (error.code === 'ENOENT') {
console.debug(`Downloading file ${fileName}...`);
const downloadOutput = await downloadFile(remoteFile, tempFile);
if (downloadOutput.error)
continue;
}
}
await extractFile(fileName, tempFile, tempDir);
console.debug(`Updating table ${table.toTable}...`);
await dumpData(tempDir, table, options);
}
// Update files checksum
for (const file of updatableFiles) {
console.log(`Updating file ${file.name} checksum...`);
await Self.rawSql(`
UPDATE edi.fileConfig
SET checksum = ?
WHERE name = ?`,
[file.checksum, file.name], options);
}
await tx.commit();
// Clean files
try {
console.debug(`Cleaning files...`);
await fs.remove(tempPath);
} catch (error) {
if (error.code !== 'ENOENT')
throw e;
}
return true;
} catch (error) {
if (error.code !== 'ENOENT')
throw e;
await tx.rollback();
throw error;
}
return true;
};
let ftpClient;
@ -126,9 +136,9 @@ module.exports = Self => {
const response = await new Promise((resolve, reject) => {
ftpClient.exec((err, response) => {
if (response.error) {
if (err || response.error) {
console.debug(`Error downloading checksum file... ${response.error}`);
reject(err);
return reject(err);
}
resolve(response);
@ -159,9 +169,9 @@ module.exports = Self => {
return new Promise((resolve, reject) => {
ftpClient.exec((err, response) => {
if (response.error) {
if (err || response.error) {
console.debug(`Error downloading file... ${response.error}`);
reject(err);
return reject(err);
}
resolve(response);
@ -169,11 +179,12 @@ module.exports = Self => {
});
}
async function extractFile(tempFile, tempDir) {
async function extractFile(fileName, tempFile, tempDir) {
const JSZip = require('jszip');
try {
await fs.mkdir(tempDir);
console.debug(`Extracting file ${fileName}...`);
} catch (error) {
if (error.code !== 'EEXIST')
throw e;
@ -196,66 +207,32 @@ module.exports = Self => {
}
}
async function dumpData(tempDir, table) {
async function dumpData(tempDir, table, options) {
const toTable = table.toTable;
const baseName = table.fileName;
const firstEntry = entries[0];
const entryName = firstEntry.entryName;
const startIndex = (entryName.length - 10);
const endIndex = (entryName.length - 4);
const dateString = entryName.substring(startIndex, endIndex);
console.log(`Emptying table ${toTable}...`);
const tableName = `edi.${toTable}`;
await Self.rawSql(`DELETE FROM ??`, [tableName]);
const lastUpdated = new Date();
const dirFiles = await fs.readdir(tempDir);
const files = dirFiles.filter(file => file.startsWith(baseName));
let updated = null;
if (file.updated) {
updated = new Date(file.updated);
updated.setHours(0, 0, 0, 0);
}
for (const file of files) {
console.log(`Dumping data from file ${file}...`);
// Format string date to a date object
lastUpdated.setFullYear(`20${dateString.substring(4, 6)}`);
lastUpdated.setMonth(parseInt(dateString.substring(2, 4)) - 1);
lastUpdated.setDate(dateString.substring(0, 2));
lastUpdated.setHours(0, 0, 0, 0);
const templatePath = path.join(__dirname, `./sql/${toTable}.sql`);
const sqlTemplate = await fs.readFile(templatePath, 'utf8');
const filePath = path.join(tempDir, file);
if (updated && lastUpdated <= updated) {
console.debug(`Table ${toTable} already updated, skipping...`);
return;
}
const tx = await Self.beginTransaction({});
try {
const options = {transaction: tx};
const tableName = `edi.${toTable}`;
await Self.rawSql(`DELETE FROM ??`, [tableName], options);
const dirFiles = await fs.readdir(tempDir);
const files = dirFiles.filter(file => file.startsWith(baseName));
for (const file of files) {
console.log(`Dumping data from file ${file}...`);
const templatePath = path.join(__dirname, `./sql/${toTable}.sql`);
const sqlTemplate = await fs.readFile(templatePath, 'utf8');
const filePath = path.join(tempDir, file);
await Self.rawSql(sqlTemplate, [filePath], options);
await Self.rawSql(`
await Self.rawSql(sqlTemplate, [filePath], options);
await Self.rawSql(`
UPDATE edi.tableConfig
SET updated = ?
WHERE fileName = ?
`, [new Date(), baseName], options);
}
tx.commit();
} catch (error) {
tx.rollback();
throw error;
}
console.log(`Updated table ${toTable}\n`);
}
};

View File

@ -0,0 +1,118 @@
const jsdom = require('jsdom');
const mysql = require('mysql');
module.exports = Self => {
Self.remoteMethodCtx('closeTicket', {
description: 'Close tickets without response from the user',
accessType: 'READ',
returns: {
type: 'Object',
root: true
},
http: {
path: `/closeTicket`,
verb: 'POST'
}
});
Self.closeTicket = async ctx => {
const models = Self.app.models;
const config = await models.OsTicketConfig.findOne();
const ostUri = `${config.host}/login.php`;
if (!config.user || !config.password || !config.userDb || !config.passwordDb)
return false;
const con = mysql.createConnection({
host: `${config.hostDb}`,
user: `${config.userDb}`,
password: `${config.passwordDb}`,
port: `${config.portDb}`
});
const sql = `SELECT ot.ticket_id, ot.number
FROM osticket.ost_ticket ot
JOIN osticket.ost_ticket_status ots ON ots.id = ot.status_id
JOIN osticket.ost_thread ot2 ON ot2.object_id = ot.ticket_id AND ot2.object_type = 'T'
JOIN (
SELECT ote.thread_id, MAX(ote.created) created, MAX(ote.updated) updated
FROM osticket.ost_thread_entry ote
WHERE ote.staff_id != 0 AND ote.type = 'R'
GROUP BY ote.thread_id
) sub ON sub.thread_id = ot2.id
WHERE ot.isanswered = 1
AND ots.state = '${config.oldStatus}'
AND IF(sub.updated > sub.created, sub.updated, sub.created) < DATE_SUB(CURDATE(), INTERVAL ${config.day} DAY)`;
let ticketsId = [];
con.connect(err => {
if (err) throw err;
con.query(sql, (err, results) => {
if (err) throw err;
for (const result of results)
ticketsId.push(result.ticket_id);
});
});
await requestToken();
async function requestToken() {
const response = await fetch(ostUri);
const result = response.headers.get('set-cookie');
const [firtHeader] = result.split(' ');
const firtCookie = firtHeader.substring(0, firtHeader.length - 1);
const body = await response.text();
const dom = new jsdom.JSDOM(body);
const token = dom.window.document.querySelector('[name="__CSRFToken__"]').value;
await login(token, firtCookie);
}
async function login(token, firtCookie) {
const data = {
__CSRFToken__: token,
do: 'scplogin',
userid: config.user,
passwd: config.password,
ajax: 1
};
const params = {
method: 'POST',
body: new URLSearchParams(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie': firtCookie
}
};
const response = await fetch(ostUri, params);
const result = response.headers.get('set-cookie');
const [firtHeader] = result.split(' ');
const secondCookie = firtHeader.substring(0, firtHeader.length - 1);
await close(token, secondCookie);
}
async function close(token, secondCookie) {
for (const ticketId of ticketsId) {
const ostUri = `${config.host}/ajax.php/tickets/${ticketId}/status`;
const data = {
status_id: config.newStatusId,
comments: config.comment,
undefined: config.action
};
const params = {
method: 'POST',
body: new URLSearchParams(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-CSRFToken': token,
'Cookie': secondCookie
}
};
return fetch(ostUri, params);
}
}
};
};

View File

@ -0,0 +1,29 @@
const {Email} = require('vn-print');
module.exports = Self => {
Self.remoteMethodCtx('osTicketReportEmail', {
description: 'Sends the buyer waste email',
accessType: 'WRITE',
accepts: [],
returns: {
type: ['object'],
root: true
},
http: {
path: '/osticket-report-email',
verb: 'POST'
}
});
Self.osTicketReportEmail = async ctx => {
const models = Self.app.models;
const printConfig = await models.PrintConfig.findOne();
const email = new Email('osticket-report', {
recipient: printConfig.itRecipient,
lang: ctx.req.getLocale()
});
return email.send();
};
};

View File

@ -116,8 +116,14 @@
"OsTicket": {
"dataSource": "osticket"
},
"OsTicketConfig": {
"dataSource": "vn"
},
"Edi": {
"dataSource": "vn"
},
"PrintConfig": {
"dataSource": "vn"
}
}

View File

@ -32,6 +32,9 @@
},
"attempts": {
"type": "number"
},
"error": {
"type": "string"
}
},
"acls": [{

View File

@ -0,0 +1,52 @@
{
"name": "OsTicketConfig",
"base": "VnModel",
"options": {
"mysql": {
"table": "osTicketConfig"
}
},
"properties": {
"id": {
"type": "number",
"id": true,
"description": "Identifier"
},
"host": {
"type": "string"
},
"user": {
"type": "string"
},
"password": {
"type": "string"
},
"oldStatus": {
"type": "string"
},
"newStatusId": {
"type": "number"
},
"action": {
"type": "string"
},
"day": {
"type": "number"
},
"comment": {
"type": "string"
},
"hostDb": {
"type": "string"
},
"userDb": {
"type": "string"
},
"passwordDb": {
"type": "string"
},
"portDb": {
"type": "number"
}
}
}

4
back/models/osticket.js Normal file
View File

@ -0,0 +1,4 @@
module.exports = Self => {
require('../methods/osticket/osTicketReportEmail')(Self);
require('../methods/osticket/closeTicket')(Self);
};

View File

@ -1,12 +1,5 @@
{
"name": "OsTicket",
"base": "VnModel",
"acls": [{
"property": "validations",
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}]
"base": "VnModel"
}

View File

@ -0,0 +1,29 @@
{
"name": "PrintConfig",
"description": "Print config",
"base": "VnModel",
"options": {
"mysql": {
"table": "salix.printConfig"
}
},
"properties": {
"id": {
"id": true,
"type": "number",
"description": "Identifier"
},
"itRecipient": {
"type": "string"
},
"incidencesEmail": {
"type": "string"
}
},
"acls": [{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW"
}]
}

View File

@ -7,13 +7,18 @@ process.on('warning', warning => {
console.log(warning.stack);
});
process.on('exit', async function() {
if (container) await container.rm();
});
let container;
async function test() {
let isCI = false;
if (process.argv[2] === 'ci')
isCI = true;
const container = new Docker();
container = new Docker();
await container.run(isCI);
dataSources = JSON.parse(JSON.stringify(dataSources));
@ -46,6 +51,7 @@ async function test() {
jasmine.addReporter(new JunitReporter.JUnitXmlReporter());
jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
jasmine.exitOnCompletion = true;
}
const backSpecs = [
@ -60,11 +66,10 @@ async function test() {
helpers: [],
});
jasmine.exitOnCompletion = false;
await jasmine.execute();
if (app) await app.disconnect();
if (container) await container.rm();
console.log('app disconnected & container removed');
console.log('App disconnected & container removed');
}
test();

View File

@ -1,2 +0,0 @@
INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
VALUES('InvoiceInDueDay', '*', '*', 'ALLOW', 'ROLE', 'administrative');

View File

@ -1,248 +0,0 @@
DROP PROCEDURE IF EXISTS vn.invoiceInBookingMain;
DELIMITER $$
$$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`invoiceInBookingMain`(vInvoiceInId INT)
BEGIN
DECLARE vTotalAmount,vTotalAmountDivisa DECIMAL(10,2);
DECLARE vBookNumber,vSerialNumber INT;
DECLARE vRate DECIMAL(10,4);
CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber);
SELECT SUM(iit.taxableBase * IF( i.serial= 'R' AND ti.Iva <> 'HP DEVENGADO 21 ISP', 1 +(ti.PorcentajeIva/100),1)),
SUM(iit.foreignValue * IF( i.serial= 'R', 1 + (ti.PorcentajeIva/100),1)),
iit.taxableBase/iit.foreignValue
INTO vTotalAmount, vTotalAmountDivisa, vRate
FROM newInvoiceIn i
JOIN invoiceInTax iit ON iit.invoiceInFk = i.id
LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk;
CALL vn.ledger_next(vBookNumber);
-- Apunte del proveedor
INSERT INTO XDiario(ASIEN,
FECHA,
SUBCTA,
EUROHABER,
CONCEPTO,
CAMBIO,
HABERME,
NFACTICK,
CLAVE,
empresa_id
)
SELECT
vBookNumber,
n.bookEntried,
s.supplierAccount,
vTotalAmount EUROHABER,
n.conceptWithSupplier,
vRate,
vTotalAmountDivisa,
n.invoicesCount,
vInvoiceInId,
n.companyFk
FROM newInvoiceIn n
JOIN newSupplier s;
-- Línea de Gastos
INSERT INTO XDiario ( ASIEN,
FECHA,
SUBCTA,
CONTRA,
EURODEBE,
EUROHABER,
CONCEPTO,
CAMBIO,
DEBEME,
HABERME,
NFACTICK,
empresa_id
)
SELECT vBookNumber ASIEN,
n.bookEntried FECHA,
IF(e.isWithheld , LPAD(RIGHT(s.supplierAccount,5),10,iit.expenceFk),iit.expenceFk) SUBCTA,
s.supplierAccount CONTRA,
IF(e.isWithheld AND iit.taxableBase < 0, NULL, ROUND(SUM(iit.taxableBase),2)) EURODEBE,
IF(e.isWithheld AND iit.taxableBase < 0,ROUND(SUM(-iit.taxableBase),2),NULL) EUROHABER,
n.conceptWithSupplier CONCEPTO,
vRate,
IF(e.isWithheld,NULL,ABS(ROUND(SUM(iit.foreignValue),2))) DEBEME,
IF(e.isWithheld,ABS(ROUND(SUM(iit.foreignValue),2)),NULL) HABERME,
n.invoicesCount NFACTICK,
n.companyFk empresa_id
FROM newInvoiceIn n
JOIN newSupplier s
JOIN invoiceInTax iit ON iit.invoiceInFk = n.id
JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = iit.expenceFk
WHERE e.name != 'Suplidos Transitarios nacionales'
GROUP BY iit.expenceFk;
-- Líneas de IVA
INSERT INTO XDiario( ASIEN,
FECHA,
SUBCTA,
CONTRA,
EURODEBE,
BASEEURO,
CONCEPTO,
FACTURA,
IVA,
AUXILIAR,
SERIE,
TIPOOPE,
FECHA_EX,
FECHA_OP,
NFACTICK,
FACTURAEX,
L340,
LRECT349,
TIPOCLAVE,
TIPOEXENCI,
TIPONOSUJE,
TIPOFACT,
TIPORECTIF,
TERIDNIF,
TERNIF,
TERNOM,
FECREGCON,
empresa_id
)
SELECT vBookNumber ASIEN,
n.bookEntried FECHA,
IF(n.expenceFkDeductible>0, n.expenceFkDeductible, ti.CuentaIvaSoportado) SUBCTA,
s.supplierAccount CONTRA,
SUM(ROUND(ti.PorcentajeIva * it.taxableBase / 100 /* + 0.0001*/ , 2)) EURODEBE,
SUM(it.taxableBase) BASEEURO,
GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO,
vSerialNumber FACTURA,
ti.PorcentajeIva IVA,
IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR,
n.serial SERIE,
ttr.ClaveOperacionDefecto,
n.issued FECHA_EX,
n.operated FECHA_OP,
n.invoicesCount NFACTICK,
n.supplierRef FACTURAEX,
TRUE L340,
(isSameCountry OR NOT isUeeMember) LRECT349,
n.cplusTrascendency472Fk TIPOCLAVE,
n.cplusTaxBreakFk TIPOEXENCI,
n.cplusSubjectOpFk TIPONOSUJE,
n.cplusInvoiceType472Fk TIPOFACT,
n.cplusRectificationTypeFk TIPORECTIF,
iis.cplusTerIdNifFk TERIDNIF,
s.nif AS TERNIF,
s.name AS TERNOM,
n.booked FECREGCON,
n.companyFk
FROM newInvoiceIn n
JOIN newSupplier s
JOIN invoiceInTax it ON n.id = it.invoiceInFk
JOIN sage.TiposIva ti ON ti.CodigoIva = it.taxTypeSageFk
JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = it.transactionTypeSageFk
JOIN invoiceInSerial iis ON iis.code = n.serial
JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = it.expenceFk
LEFT JOIN (
SELECT eWithheld.id
FROM invoiceInTax hold
JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld
WHERE hold.invoiceInFk = vInvoiceInId LIMIT 1
) eWithheld ON TRUE
WHERE it.taxTypeSageFk IS NOT NULL
AND it.taxTypeSageFk NOT IN (22, 90)
GROUP BY ti.PorcentajeIva, e.id;
-- Línea iva inversor sujeto pasivo
INSERT INTO XDiario( ASIEN,
FECHA,
SUBCTA,
CONTRA,
EUROHABER,
BASEEURO,
CONCEPTO,
FACTURA,
IVA,
AUXILIAR,
SERIE,
TIPOOPE,
FECHA_EX,
FECHA_OP,
NFACTICK,
FACTURAEX,
L340,
LRECT349,
TIPOCLAVE,
TIPOEXENCI,
TIPONOSUJE,
TIPOFACT,
TIPORECTIF,
TERIDNIF,
TERNIF,
TERNOM,
empresa_id
)
SELECT vBookNumber ASIEN,
n.bookEntried FECHA,
ti.CuentaIvaRepercutido SUBCTA,
s.supplierAccount CONTRA,
SUM(ROUND(ti.PorcentajeIva * it.taxableBase / 100,2)) EUROHABER,
ROUND(SUM(it.taxableBase),2) BASEEURO,
GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO,
vSerialNumber FACTURA,
ti.PorcentajeIva IVA,
'*' AUXILIAR,
n.serial SERIE,
ttr.ClaveOperacionDefecto,
n.issued FECHA_EX,
n.operated FECHA_OP,
n.invoicesCount NFACTICK,
n.supplierRef FACTURAEX,
FALSE L340,
(isSameCountry OR NOT isUeeMember) LRECT349,
1 TIPOCLAVE,
n.cplusTaxBreakFk TIPOEXENCI,
n.cplusSubjectOpFk TIPONOSUJE,
n.cplusInvoiceType472Fk TIPOFACT,
n.cplusRectificationTypeFk TIPORECTIF,
iis.cplusTerIdNifFk TERIDNIF,
s.nif AS TERNIF,
s.name AS TERNOM,
n.companyFk
FROM newInvoiceIn n
JOIN newSupplier s
JOIN invoiceInTax it ON n.id = it.invoiceInFk
JOIN sage.TiposIva ti ON ti.CodigoIva = it.taxTypeSageFk
JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = it.transactionTypeSageFk
JOIN invoiceInSerial iis ON iis.code = n.serial
JOIN (SELECT * FROM expence e GROUP BY e.id)e ON e.id = it.expenceFk
WHERE ti.Iva = 'HP DEVENGADO 21 ISP' OR MID(s.account, 4, 1) = '1'
GROUP BY ti.PorcentajeIva, e.id;
-- Actualización del registro original
UPDATE invoiceIn ii
JOIN newInvoiceIn ni ON ii.id = ni.id
SET ii.serialNumber = vSerialNumber,
ii.isBooked = TRUE;
-- Problemas derivados de la precisión en los decimales al calcular los impuestos
UPDATE XDiario
SET EURODEBE = EURODEBE -
(SELECT IF(ABS(sub.difference) = 0.01, sub.difference, 0)
FROM(
SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference
FROM XDiario
WHERE ASIEN = vBookNumber
)sub
)
WHERE ASIEN = vBookNumber
AND EURODEBE <> 0
ORDER BY id DESC
LIMIT 1;
END$$
DELIMITER ;

View File

@ -1,12 +0,0 @@
UPDATE `vn`.`companyGroup`
SET `code`='verdnatura'
WHERE `id`=1;
UPDATE `vn`.`companyGroup`
SET `code`='ornamental'
WHERE `id`=2;
UPDATE `vn`.`companyGroup`
SET `code`='other'
WHERE `id`=3;
UPDATE `vn`.`companyGroup`
SET `code`='provisional'
WHERE `id`=4;

View File

@ -1,38 +0,0 @@
USE vn;
DELIMITER $$
$$
CREATE OR REPLACE
ALGORITHM = UNDEFINED VIEW `vn`.`saleVolume` AS
select
`s`.`ticketFk` AS `ticketFk`,
`s`.`id` AS `saleFk`,
round(`ic`.`cm3delivery` * `s`.`quantity` / 1000, 0) AS `litros`,
`t`.`routeFk` AS `routeFk`,
`t`.`shipped` AS `shipped`,
`t`.`landed` AS `landed`,
`s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `volume`,
`s`.`quantity` * `ic`.`grams` / 1000 AS `physicalWeight`,
`s`.`quantity` * `ic`.`cm3delivery` * greatest(`i`.`density`, 167) / 1000000 AS `weight`,
`s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `physicalVolume`,
`s`.`quantity` * `ic`.`cm3delivery` * ifnull(`t`.`zonePrice`, `z`.`price`) / (`vc`.`standardFlowerBox` * 1000) AS `freight`,
`t`.`zoneFk` AS `zoneFk`,
`t`.`clientFk` AS `clientFk`,
`s`.`isPicked` AS `isPicked`,
`s`.`quantity` * `s`.`price` * (100 - `s`.`discount`) / 100 AS `eurosValue`,
`i`.`itemPackingTypeFk` AS `itemPackingTypeFk`
from
(((((`sale` `s`
join `item` `i` on
(`i`.`id` = `s`.`itemFk`))
join `ticket` `t` on
(`t`.`id` = `s`.`ticketFk`))
join `zone` `z` on
(`z`.`id` = `t`.`zoneFk`))
join `volumeConfig` `vc`)
join `itemCost` `ic` on
(`ic`.`itemFk` = `s`.`itemFk`
and `ic`.`warehouseFk` = `t`.`warehouseFk`))
where
`s`.`quantity` > 0;
$$
DELIMITER ;

View File

@ -1,25 +0,0 @@
ALTER TABLE `postgresql`.`business` ADD payedHolidays INT NULL;
ALTER TABLE `postgresql`.`business` CHANGE payedHolidays payedHolidays INT NULL AFTER reasonEndFk;
CREATE OR REPLACE
ALGORITHM = UNDEFINED VIEW `vn`.`workerLabour` AS
select
`b`.`business_id` AS `businessFk`,
`p`.`id_trabajador` AS `workerFk`,
`bl`.`workcenter_id` AS `workCenterFk`,
`b`.`date_start` AS `started`,
`b`.`date_end` AS `ended`,
`d`.`id` AS `departmentFk`,
`b`.`payedHolidays` AS `payedHolidays`
from
((((`postgresql`.`person` `p`
join `postgresql`.`profile` `pr` on
((`pr`.`person_id` = `p`.`person_id`)))
join `postgresql`.`business` `b` on
((`b`.`client_id` = `pr`.`profile_id`)))
join `postgresql`.`business_labour` `bl` on
((`b`.`business_id` = `bl`.`business_id`)))
join `vn`.`department` `d` on
((`d`.`id` = `bl`.`department_id`)))
order by
`b`.`date_start` desc

View File

@ -1,2 +0,0 @@
DELETE FROM `salix`.`ACL`
WHERE model = 'ClaimEnd' AND property = 'importTicketSales';

View File

@ -1,3 +0,0 @@
INSERT INTO `salix`.`ACL`
(model, property, accessType, permission, principalType, principalId)
VALUES('Collection', 'setSaleQuantity', '*', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,3 +0,0 @@
INSERT INTO `salix`.`ACL`
(model, property, accessType, permission, principalType, principalId)
VALUES('Docuware', '*', '*', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,3 +0,0 @@
UPDATE `salix`.`defaultViewConfig`
SET `columns`='{"intrastat":false,"stemMultiplier":false,"landed":false,"producer":false}'
WHERE tableCode ='itemsIndex';

View File

@ -1,11 +0,0 @@
CREATE TABLE `vn`.`docuware` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`code` varchar(50) NULL,
`fileCabinetName` varchar(50) NULL,
`dialogName` varchar(255) DEFAULT NULL,
`find` varchar(50) DEFAULT NULL
);
INSERT INTO `vn`.`docuware` (`code`, `fileCabinetName`, `dialogName` , `find`)
VALUES
('deliveryClient', 'Albaranes cliente', 'findTicket', 'N__ALBAR_N');

View File

@ -1,9 +0,0 @@
CREATE TABLE `vn`.`docuwareConfig` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`url` varchar(75) NULL,
`token` varchar(1000) DEFAULT NULL
);
INSERT INTO `vn`.`docuwareConfig` (`url`)
VALUES
('https://verdnatura.docuware.cloud/docuware/platform');

View File

@ -1,26 +0,0 @@
ALTER TABLE `vn`.`state` ADD classColor varchar(12) NULL;
UPDATE `vn`.`state` s
SET s.classColor = 'warning'
WHERE s.alertLevel = 1;
UPDATE `vn`.`state` s
SET s.classColor = 'alert'
WHERE s.alertLevel = 0;
UPDATE `vn`.`state` s
SET s.classColor = 'success'
WHERE s.code LIKE 'OK';
UPDATE `vn`.`state` s
SET s.classColor = 'notice'
WHERE s.code LIKE 'FREE';
UPDATE `vn`.`state` s
SET s.classColor = 'success'
WHERE s.order >= 4
AND (s.alertLevel = 0 OR s.alertLevel = 1);
UPDATE `vn`.`state` s
SET s.classColor = 'warning'
WHERE s.code IN ('PREVIOUS_PREPARATION', 'PREPARED', 'ON_PREPARATION', 'ON_CHECKING', 'CHECKED');

View File

@ -1,46 +0,0 @@
DROP PROCEDURE IF EXISTS `vn`.`ticket_getMovable`;
DELIMITER $$
$$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`ticket_getMovable`(vTicketFk INT, vDatedNew DATETIME, vWarehouseFk INT)
BEGIN
/**
* Cálcula el stock movible para los artículos de un ticket
* vDatedNew debe ser menor que vDatedOld, en los otros casos se
* asume que siempre es posible
*
* @param vTicketFk -> Ticket
* @param vDatedNew -> Nueva fecha
* @return Sales con Movible
*/
DECLARE vDatedOld DATETIME;
SET vDatedNew = DATE_ADD(vDatedNew, INTERVAL 1 DAY);
SELECT t.shipped INTO vDatedOld
FROM ticket t
WHERE t.id = vTicketFk;
CALL itemStock(vWarehouseFk, vDatedNew, NULL);
CALL item_getMinacum(vWarehouseFk, vDatedNew, DATEDIFF(DATE_SUB(vDatedOld, INTERVAL 1 DAY), vDatedNew), NULL);
SELECT s.id,
s.itemFk,
s.quantity,
s.concept,
s.price,
s.reserved,
s.discount,
i.image,
i.subName,
il.stock + IFNULL(im.amount, 0) AS movable
FROM ticket t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk AND im.warehouseFk = vWarehouseFk
LEFT JOIN tmp.itemList il ON il.itemFk = s.itemFk
WHERE t.id = vTicketFk;
DROP TEMPORARY TABLE IF EXISTS tmp.itemList;
DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum;
END$$
DELIMITER ;

View File

@ -1,2 +0,0 @@
INSERT INTO `salix`.`ACL` (model,property,accessType,principalId)
VALUES ('AgencyTerm','*','*','administrative');

View File

@ -1,3 +0,0 @@
INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
VALUES
('ClaimLog', '*', 'READ', 'ALLOW', 'ROLE', 'claimManager');

View File

@ -1 +0,0 @@
UPDATE `account`.`user` SET `role` = 57 WHERE id IN (2294, 4365, 7294);

View File

@ -1,2 +0,0 @@
INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
VALUES ('Edi', 'updateData', 'WRITE', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,2 +0,0 @@
INSERT INTO `salix`.`ACL` (`id`, `model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES(304, 'Agency', '*', '*', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,3 +0,0 @@
INSERT INTO `salix`.`ACL`
(`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('InvoiceInIntrastat', '*', '*', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,10 +0,0 @@
CREATE TABLE `vn`.`agencyTermConfig` (
`expenceFk` varchar(10) DEFAULT NULL,
`vatAccountSupported` varchar(15) DEFAULT NULL,
`vatPercentage` decimal(28,10) DEFAULT NULL,
`transaction` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `vn`.`agencyTermConfig`
(`expenceFk`, `vatAccountSupported`, `vatPercentage`, `transaction`)
VALUES('6240000000', '4721000015', 21.0000000000, 'Adquisiciones intracomunitarias de servicios');

View File

@ -1,8 +0,0 @@
CREATE TABLE `vn`.`claimConfig` (
`id` int(11) NOT NULL,
`pickupContact` varchar(250),
PRIMARY KEY (`id`)
);
INSERT INTO vn.claimConfig (id, pickupContact)
VALUES(1, 'Email: cmorenoa@logista.com Telf: 961594250 Extensión: 206');

View File

@ -1,2 +0,0 @@
ALTER TABLE `vn`.`claimState` ADD `hasToNotify` TINYINT DEFAULT 0 NULL;
UPDATE `vn`.`claimState` SET `hasToNotify` = 1 WHERE `code` IN ('canceled', 'incomplete');

View File

@ -1 +0,0 @@
ALTER TABLE `vn`.`claim` ADD packages smallint(10) unsigned DEFAULT 0 NULL COMMENT 'packages received by the client';

View File

@ -1,2 +0,0 @@
INSERT INTO `vn`.`component` (`name`,`typeFk`,`classRate`,`isRenewable`,`code`,`isRequired`)
VALUES ('maná reclamacion',7,4,0,'manaClaim',0);

View File

@ -1,90 +0,0 @@
ALTER TABLE `vn`.`country` ADD `a3Code` INT NULL COMMENT 'Código país para a3';
UPDATE `vn`.`country` c
JOIN `vn2008`.`payroll_pais` `p` ON `p`.`pais` = `c`.`country`
SET `c`.`a3Code` = `p`.`codpais`;
UPDATE `vn`.`country`
SET `a3Code` = 710
WHERE `country` = 'Sud-Africa'; -- ÁFRICA DEL SUR
UPDATE `vn`.`country`
SET `a3Code` = 643
WHERE `country` = 'Rusia'; -- FEDERACIÓN DE RUSIA
UPDATE `vn`.`country`
SET `a3Code` = 28
WHERE `country` = 'Antigua'; -- ANTIGUA Y BARBUDA
UPDATE `vn`.`country`
SET `a3Code` = 840
WHERE `country` = 'USA'; -- ESTADOS UNIDOS
UPDATE `vn`.`country`
SET `a3Code` = 404
WHERE `country` = 'Kenya'; -- KENIA
UPDATE `vn`.`country`
SET `a3Code` = 498
WHERE `country` = 'Moldavia'; -- REPÚBLICA DE MOLDAVIA
UPDATE `vn`.`country`
SET `a3Code` = 826
WHERE `country` = 'Gran Bretaña'; -- REINO UNIDO
UPDATE `vn`.`country`
SET `a3Code` = 484
WHERE `country` = 'Mexico'; -- MÉJICO
UPDATE `vn`.`country`
SET `a3Code` = 716
WHERE `country` = 'Zimbawe'; -- ZINBABWE
UPDATE `vn`.`country`
SET `a3Code` = 203
WHERE `country` = 'Chequia'; -- REPÚBLICA CHECA
UPDATE `vn`.`country`
SET `a3Code` = 764
WHERE `country` = 'Thailandia'; -- TAILANDIA
UPDATE `vn`.`country`
SET `a3Code` = 276
WHERE `country` = 'Alemania'; -- REPÚBLICA FEDERAL DE ALEMANIA
UPDATE `vn`.`country`
SET `a3Code` = 112
WHERE `country` = 'Bielorrusia'; -- BELARUS
UPDATE `vn`.`country`
SET `a3Code` = 528
WHERE `country` = 'Holanda'; -- PAÍSES BAJOS
UPDATE `vn`.`country`
SET `a3Code` = 410
WHERE `country` = 'Corea del Sur'; -- COREA (REPÚBLICA)
UPDATE `vn`.`country`
SET `a3Code` = 724
WHERE `country` = 'España exento'; -- ESPAÑA
-- Borrar registro USA de country:
UPDATE `vn`.`supplier` `s`
SET `s`.`countryFk` = 62
WHERE `s`.`countryFk` = 12;
UPDATE `vn`.`bankEntity`
SET `countryFk` = 62
WHERE `countryFk` = 12;
DELETE FROM `vn`.`country`
WHERE `id`= 12;
UPDATE `vn2008`.`payroll_pais`
SET `pais`='COREA NORTE (REPÚBLICA DEM. POPULAR)'
WHERE `codpais`=408;
UPDATE `vn2008`.`payroll_pais`
SET `pais`='COREA SUR (REPÚBLICA) '
WHERE `codpais`=410;
RENAME TABLE `vn2008`.`payroll_pais` TO `vn2008`.`payroll_pais__`;

View File

@ -1,2 +0,0 @@
INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`)
VALUES ('InvoiceInIntrastat','*','*','ALLOW','ROLE','employee');

View File

@ -1,106 +0,0 @@
DROP PROCEDURE IF EXISTS `bs`.`manaCustomerUpdate`;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `bs`.`manaCustomerUpdate`()
BEGIN
DECLARE vToDated DATE;
DECLARE vFromDated DATE;
DECLARE vForDeleteDated DATE;
DECLARE vManaId INT;
DECLARE vManaAutoId INT;
DECLARE vClaimManaId INT;
DECLARE vManaBankId INT;
DECLARE vManaGreugeTypeId INT;
SELECT id INTO vManaId
FROM `component` WHERE code = 'mana';
SELECT id INTO vManaAutoId
FROM `component` WHERE code = 'autoMana';
SELECT id INTO vClaimManaId
FROM `component` WHERE code = 'manaClaim';
SELECT id INTO vManaBankId
FROM `bank` WHERE code = 'mana';
SELECT id INTO vManaGreugeTypeId
FROM `greugeType` WHERE code = 'mana';
SELECT IFNULL(max(dated), '2016-01-01')
INTO vFromDated
FROM bs.manaCustomer;
DELETE
FROM bs.manaCustomer
WHERE dated = vFromDated;
SELECT IFNULL(max(dated), '2016-01-01')
INTO vFromDated
FROM bs.manaCustomer;
WHILE timestampadd(DAY,30,vFromDated) < CURDATE() DO
SELECT
timestampadd(DAY,30,vFromDated),
timestampadd(DAY,-90,vFromDated)
INTO
vToDated,
vForDeleteDated;
DELETE FROM bs.manaCustomer
WHERE dated <= vForDeleteDated;
INSERT INTO bs.manaCustomer(Id_Cliente, Mana, dated)
SELECT
Id_Cliente,
cast(sum(mana) as decimal(10,2)) as mana,
vToDated as dated
FROM
(
SELECT cs.Id_Cliente, Cantidad * Valor as mana
FROM vn2008.Tickets t
JOIN vn2008.Consignatarios cs using(Id_Consigna)
JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket
JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento
WHERE Id_Componente IN (vManaAutoId, vManaId, vClaimManaId)
AND t.Fecha > vFromDated
AND date(t.Fecha) <= vToDated
UNION ALL
SELECT r.Id_Cliente, - Entregado
FROM vn2008.Recibos r
WHERE Id_Banco = vManaBankId
AND Fechacobro > vFromDated
AND Fechacobro <= vToDated
UNION ALL
SELECT g.Id_Cliente, g.Importe
FROM vn2008.Greuges g
WHERE Greuges_type_id = vManaGreugeTypeId
AND Fecha > vFromDated
AND Fecha <= vToDated
UNION ALL
SELECT Id_Cliente, mana
FROM bs.manaCustomer
WHERE dated = vFromDated
) sub
GROUP BY Id_Cliente
HAVING Id_Cliente;
SET vFromDated = vToDated;
END WHILE;
END$$
DELIMITER ;

View File

@ -1,75 +0,0 @@
DROP PROCEDURE IF EXISTS `vn`.`manaSpellersRequery`;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`manaSpellersRequery`(vWorkerFk INTEGER)
BEGIN
/**
* Recalcula el mana consumido por un trabajador
*
* @param vWorkerFk Id Trabajador
*/
DECLARE vWorkerIsExcluded BOOLEAN;
DECLARE vFromDated DATE;
DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,CURDATE());
DECLARE vMana INT;
DECLARE vAutoMana INT;
DECLARE vClaimMana INT;
DECLARE vManaBank INT;
DECLARE vManaGreugeType INT;
SELECT COUNT(*) INTO vWorkerIsExcluded
FROM workerManaExcluded
WHERE workerFk = vWorkerFk;
IF NOT vWorkerIsExcluded THEN
SELECT id INTO vMana
FROM `component` WHERE code = 'mana';
SELECT id INTO vAutoMana
FROM `component` WHERE code = 'autoMana';
SELECT id INTO vClaimMana
FROM `component` WHERE code = 'manaClaim';
SELECT id INTO vManaBank
FROM `bank` WHERE code = 'mana';
SELECT id INTO vManaGreugeType
FROM `greugeType` WHERE code = 'mana';
SELECT max(dated) INTO vFromDated
FROM clientManaCache;
REPLACE workerMana (workerFk, amount)
SELECT vWorkerFk, sum(mana) FROM
(
SELECT s.quantity * sc.value as mana
FROM ticket t
JOIN address a ON a.id = t.addressFk
JOIN client c ON c.id = a.clientFk
JOIN sale s ON s.ticketFk = t.id
JOIN saleComponent sc ON sc.saleFk = s.id
WHERE c.salesPersonFk = vWorkerFk AND sc.componentFk IN (vMana, vAutoMana, vClaimMana)
AND t.shipped > vFromDated AND t.shipped < vToDated
UNION ALL
SELECT - r.amountPaid
FROM receipt r
JOIN client c ON c.id = r.clientFk
WHERE c.salesPersonFk = vWorkerFk AND bankFk = vManaBank
AND payed > vFromDated
UNION ALL
SELECT g.amount
FROM greuge g
JOIN client c ON c.id = g.clientFk
WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType
AND g.shipped > vFromDated and g.shipped < CURDATE()
UNION ALL
SELECT cc.mana
FROM clientManaCache cc
JOIN client c ON c.id = cc.clientFk
WHERE c.salesPersonFk = vWorkerFk AND cc.dated = vFromDated
) sub;
END IF;
END$$
DELIMITER ;

View File

@ -1,48 +0,0 @@
ALTER TABLE `vn`.`agencyTerm` ADD `supplierFk` INT NULL;
ALTER TABLE `vn`.`agencyTerm` CHANGE `supplierFk` `supplierFk` INT NULL AFTER `agencyFk`;
UPDATE `vn`.`agencyTerm` `at`
JOIN `vn`.`agency` `a` ON `a`.`id` = `at`.`agencyFk`
SET `at`.`supplierFk` = `a`.`supplierFk`;
ALTER TABLE `vn`.`agencyTerm` ADD CONSTRAINT `agencyTerm_FK` FOREIGN KEY (`agencyFk`) REFERENCES `vn`.`agency`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `vn`.`agencyTerm` ADD CONSTRAINT `agencyTerm_FK_1` FOREIGN KEY (`supplierFk`) REFERENCES `vn`.`supplier`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
RENAME TABLE `vn`.`agencyTerm` TO `vn`.`supplierAgencyTerm`;
CREATE OR REPLACE
ALGORITHM = UNDEFINED
DEFINER=`root`@`localhost`
VIEW `vn`.`agencyTerm` AS
SELECT
`sat`.`agencyFk` AS `agencyFk`,
`sat`.`minimumPackages` AS `minimumPackages`,
`sat`.`kmPrice` AS `kmPrice`,
`sat`.`packagePrice` AS `packagePrice`,
`sat`.`routePrice` AS `routePrice`,
`sat`.`minimumKm` AS `minimumKm`,
`sat`.`minimumM3` AS `minimumM3`,
`sat`.`m3Price` AS `m3Price`
FROM
`vn`.`supplierAgencyTerm` `sat`;
ALTER TABLE `vn`.`agency` DROP FOREIGN KEY `agency_ibfk_4`;
ALTER TABLE `vn`.`agency` CHANGE `supplierFk` `supplierFk__` int(11) DEFAULT NULL NULL;
CREATE OR REPLACE
ALGORITHM = UNDEFINED
DEFINER=`root`@`localhost`
VIEW `vn2008`.`agency` AS
SELECT
`a`.`id` AS `agency_id`,
`a`.`name` AS `name`,
`a`.`warehouseFk` AS `warehouse_id`,
`a`.`isVolumetric` AS `por_volumen`,
`a`.`bankFk` AS `Id_Banco`,
`a`.`warehouseAliasFk` AS `warehouse_alias_id`,
`a`.`isOwn` AS `propios`,
`a`.`labelZone` AS `zone_label`,
`a`.`workCenterFk` AS `workCenterFk`,
`a`.`supplierFk__` AS `supplierFk__`
FROM
`vn`.`agency` `a`;

View File

@ -1,149 +0,0 @@
DROP PROCEDURE IF EXISTS `vn`.`ticket_doRefund`;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_doRefund`(IN vOriginTicket INT, OUT vNewTicket INT)
BEGIN
DECLARE vDone BIT DEFAULT 0;
DECLARE vCustomer MEDIUMINT;
DECLARE vWarehouse TINYINT;
DECLARE vCompany MEDIUMINT;
DECLARE vAddress MEDIUMINT;
DECLARE vRefundAgencyMode INT;
DECLARE vItemFk INT;
DECLARE vQuantity DECIMAL (10,2);
DECLARE vConcept VARCHAR(50);
DECLARE vPrice DECIMAL (10,2);
DECLARE vDiscount TINYINT;
DECLARE vSaleNew INT;
DECLARE vSaleMain INT;
DECLARE vZoneFk INT;
DECLARE vRsMainTicket CURSOR FOR
SELECT *
FROM tmp.sale;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1;
SELECT id INTO vRefundAgencyMode
FROM agencyMode WHERE `name` = 'ABONO';
SELECT clientFk, warehouseFk, companyFk, addressFk
INTO vCustomer, vWarehouse, vCompany, vAddress
FROM ticket
WHERE id = vOriginTicket;
SELECT id INTO vZoneFk
FROM zone WHERE agencyModeFk = vRefundAgencyMode
LIMIT 1;
INSERT INTO vn.ticket (
clientFk,
shipped,
addressFk,
agencyModeFk,
nickname,
warehouseFk,
companyFk,
landed,
zoneFk
)
SELECT
vCustomer,
CURDATE(),
vAddress,
vRefundAgencyMode,
a.nickname,
vWarehouse,
vCompany,
CURDATE(),
vZoneFk
FROM address a
WHERE a.id = vAddress;
SET vNewTicket = LAST_INSERT_ID();
SET vDone := 0;
OPEN vRsMainTicket ;
FETCH vRsMainTicket INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount;
WHILE NOT vDone DO
INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount)
VALUES( vNewTicket, vItemFk, vQuantity, vConcept, vPrice, vDiscount );
SET vSaleNew = LAST_INSERT_ID();
INSERT INTO vn.saleComponent(saleFk,componentFk,`value`)
SELECT vSaleNew,componentFk,`value`
FROM vn.saleComponent
WHERE saleFk = vSaleMain;
FETCH vRsMainTicket INTO vSaleMain, vItemFk, vQuantity, vConcept, vPrice, vDiscount;
END WHILE;
CLOSE vRsMainTicket;
INSERT INTO vn.ticketRefund(refundTicketFk, originalTicketFk)
VALUES(vNewTicket, vOriginTicket);
END$$
DELIMITER ;
CREATE TABLE `vn`.`ticketRefund` (
`id` INT auto_increment NULL,
`refundTicketFk` INT NOT NULL,
`originalTicketFk` INT NOT NULL,
CONSTRAINT `ticketRefund_PK` PRIMARY KEY (id)
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8
COLLATE=utf8_unicode_ci;
ALTER TABLE `vn`.`ticketRefund` ADD CONSTRAINT `ticketRefund_FK` FOREIGN KEY (`refundTicketFk`) REFERENCES `vn`.`ticket`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `vn`.`ticketRefund` ADD CONSTRAINT `ticketRefund_FK_1` FOREIGN KEY (`originalTicketFk`) REFERENCES `vn`.`ticket`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`ticketRefund_beforeInsert`
BEFORE INSERT ON `ticketRefund`
FOR EACH ROW
BEGIN
DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE;
IF NEW.refundTicketFk = NEW.originalTicketFk THEN
CALL util.throw('Original ticket and refund ticket has same id');
END IF;
SELECT COUNT(*) INTO vAlreadyExists
FROM ticketRefund
WHERE refundTicketFk = NEW.originalTicketFk;
IF vAlreadyExists > 0 THEN
CALL util.throw('This ticket is already a refund');
END IF;
END$$
DELIMITER ;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`ticketRefund_beforeUpdate`
BEFORE UPDATE ON `ticketRefund`
FOR EACH ROW
BEGIN
DECLARE vAlreadyExists BOOLEAN DEFAULT FALSE;
IF NEW.refundTicketFk = NEW.originalTicketFk THEN
CALL util.throw('Original ticket and refund ticket has same id');
END IF;
SELECT COUNT(*) INTO vAlreadyExists
FROM ticketRefund
WHERE refundTicketFk = NEW.originalTicketFk;
IF vAlreadyExists > 0 THEN
CALL util.throw('This ticket is already a refund');
END IF;
END$$
DELIMITER ;

View File

@ -1,16 +0,0 @@
DROP TRIGGER `vn`.`travelThermograph_beforeInsert`;
ALTER TABLE `vn`.`travelThermograph` CHANGE `temperature` `temperature__` enum('COOL','WARM','DRY') CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL NULL;
CREATE OR REPLACE
ALGORITHM = UNDEFINED VIEW `vn2008`.`travel_thermograph` AS
select
`tt`.`thermographFk` AS `thermograph_id`,
`tt`.`created` AS `odbc_date`,
`tt`.`warehouseFk` AS `warehouse_id`,
`tt`.`travelFk` AS `travel_id`,
`tt`.`temperatureFk` AS `temperature`,
`tt`.`result` AS `result`,
`tt`.`dmsFk` AS `gestdoc_id`
from
`vn`.`travelThermograph` `tt`;

View File

@ -1,51 +0,0 @@
ALTER TABLE `vn`.`worker` MODIFY COLUMN `maritalStatus__` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
UPDATE `vn`.`worker` `w`
SET `w`.`maritalStatus__` = NULL;
UPDATE `vn`.`worker` `w`
JOIN `vn`.`person` `p` ON `p`.`workerFk` = `w`.`id`
JOIN `postgresql`.`profile` `pr` ON `pr`.`person_id` = `p`.`id`
JOIN `vn2008`.`profile_labour_payroll` `pl` ON `pl`.`profile_id` = `pr`.`profile_id`
SET `w`.`maritalStatus__` = `pl`.`estadocivil`;
ALTER TABLE `vn`.`worker` ADD `originCountryFk` mediumint(8) unsigned NULL COMMENT 'País de origen';
ALTER TABLE `vn`.`worker` ADD `educationLevelFk` SMALLINT NULL;
ALTER TABLE `vn`.`worker` ADD `SSN` varchar(15) NULL;
ALTER TABLE `vn`.`worker` CHANGE `maritalStatus__` `maritalStatus` enum('S','M') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
ALTER TABLE `vn`.`worker` MODIFY COLUMN `maritalStatus` enum('S','M') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;
ALTER TABLE `vn`.`worker` CHANGE `maritalStatus` maritalStatus enum('S','M') CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL AFTER sectorFk;
ALTER TABLE `vn`.`worker` ADD CONSTRAINT `worker_FK_2` FOREIGN KEY (`educationLevelFk`) REFERENCES `vn`.`educationLevel`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `vn`.`worker` ADD CONSTRAINT `worker_FK_1` FOREIGN KEY (`originCountryFk`) REFERENCES `vn`.`country`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
INSERT INTO `vn`.`country` (`country`, `CEE`, `code`, `politicalCountryFk`, `isUeeMember`, `a3Code`)
VALUES
('Argentina',2,'AR',80,0,32),
('Cuba',2,'CU',81,0,192),
('Guinea Ecuatorial',2,'GQ',82,0,226),
('Guinea',2,'GN',83,0,324),
('Honduras',2,'HN',84,0,340),
('Mali',2,'ML',85,0,466),
('Nicaragua',2,'NI',86,0,558),
('Pakistán',2,'PK',87,0,586),
('Paraguay',2,'PY',88,0,600),
('Senegal',2,'SN',89,0,686),
('Uruguay',2,'UY',90,0,858),
('Venezuela',2,'VE',91,0,862),
('Bulgaria',2,'BG',92,1,100),
('Georgia',2,'GE',93,0,268);
UPDATE `vn`.`worker` `w`
JOIN `vn`.`person` `p` ON `p`.`workerFk` = `w`.`id`
JOIN `postgresql`.`profile` `pr` ON `pr`.`person_id` = `p`.`id`
JOIN `vn2008`.`profile_labour_payroll` `pl` ON `pl`.`profile_id` = `pr`.`profile_id`
JOIN `vn`.`country` `co` ON `co`.`a3Code` = `pl`.`codpais`
SET `w`.`originCountryFk` = `co`.`id`;
UPDATE `vn`.`worker` `w`
JOIN `vn`.`person` `p` ON `p`.`workerFk` = `w`.`id`
JOIN `postgresql`.`profile` `pr` ON `pr`.`person_id` = `p`.`id`
JOIN `vn2008`.`profile_labour_payroll` pl ON `pl`.`profile_id` = `pr`.`profile_id`
SET `w`.`SSN` = CONCAT(`pl`.`NSSProvincia`, `pl`.`NssNumero`, `pl`.`NssDC`);
RENAME TABLE `vn2008`.`profile_labour_payroll` TO `vn2008`.`profile_labour_payroll__`;

View File

@ -1,3 +0,0 @@
ALTER TABLE `postgresql`.`business_labour_payroll` DROP FOREIGN KEY `business_labour_payroll_cod_contrato`;
ALTER TABLE `vn`.`workerBusinessType` MODIFY COLUMN `id` int(11) NOT NULL;
ALTER TABLE `postgresql`.`business_labour_payroll` ADD CONSTRAINT `business_labour_payroll_FK` FOREIGN KEY (cod_contrato) REFERENCES `vn`.`workerBusinessType`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@ -1,73 +0,0 @@
DROP PROCEDURE IF EXISTS vn.timeControl_getError;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_getError`(vDatedFrom DATETIME, vDatedTo DATETIME)
BEGIN
/*
* @param vDatedFrom
* @param vDatedTo
* @table tmp.`user`(userFk)
* Fichadas incorrectas de las cuales no se puede calcular horas trabajadas
* @return tmp.timeControlError (id)
*/
DECLARE vDayMaxTime INTEGER;
SET @journeyCounter := 0;
SET @lastUserFk := NULL;
SELECT dayMaxTime INTO vDayMaxTime
FROM workerTimeControlConfig LIMIT 1;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
CREATE TEMPORARY TABLE tmp.timeControl
(INDEX(id), INDEX(journeyCounter))
ENGINE = MEMORY
SELECT sub.id,
sub.direction,
sub.timed,
IF(sub.direction = 'in' OR @hasOut OR sub.userFk <> @lastUserFk, @journeyCounter := @journeyCounter + 1, @journeyCounter) journeyCounter,
@lastUserFk := sub.userFk workerFk,
IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE)
FROM (
SELECT DISTINCT wtc.id,
wtc.direction,
wtc.timed,
wtc.userFk
FROM workerTimeControl wtc
JOIN tmp.`user` w ON w.userFk = wtc.userFk
WHERE wtc.timed BETWEEN DATE_SUB(vDatedFrom, INTERVAL 1 DAY) AND DATE_ADD(vDatedTo, INTERVAL 1 DAY)
ORDER BY wtc.userFk, wtc.timed
) sub;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
CREATE TEMPORARY TABLE tmp.timeControlAux
(INDEX(id), INDEX(journeyCounter))
ENGINE = MEMORY
SELECT * FROM tmp.timeControl;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError;
CREATE TEMPORARY TABLE tmp.timeControlError
(INDEX(id))
ENGINE = MEMORY
SELECT id
FROM tmp.timeControlAux tca
JOIN (SELECT journeyCounter,
UNIX_TIMESTAMP(MAX(timed)) - UNIX_TIMESTAMP(MIN(timed)) timeWork,
SUM(direction = 'in') totalIn,
SUM(direction = 'out') totalOut,
timed
FROM tmp.timeControl
GROUP BY journeyCounter
HAVING COUNT(*) MOD 2 = 1
OR totalIn <> 1
OR totalOut <> 1
OR timeWork >= vDayMaxTime
)sub ON sub.journeyCounter = tca.journeyCounter
WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControl;
DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux;
END$$
DELIMITER ;

View File

@ -1 +0,0 @@
ALTER TABLE `vn`.`userConfig` ADD darkMode tinyint(1) DEFAULT 1 NOT NULL COMMENT 'Salix interface dark mode';

View File

@ -1,2 +0,0 @@
INSERT INTO `salix`.`ACL`(`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('ExpeditionState', '*', 'READ', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,5 +0,0 @@
INSERT INTO `salix`.`ACL`(`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('Expense', '*', 'READ', 'ALLOW', 'ROLE', 'employee');
INSERT INTO `salix`.`ACL`(`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('Expense', '*', 'WRITE', 'ALLOW', 'ROLE', 'administrative');

View File

@ -1,6 +0,0 @@
UPDATE `salix`.`ACL`
SET `property`='refund'
WHERE `model`='Sale' AND `property`='payBack';
INSERT INTO `salix`.`ACL`(`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('Sale', 'refundAll', 'WRITE', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,5 +0,0 @@
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('SupplierActivity', '*', 'READ', 'ALLOW', 'ROLE', 'employee');
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('SupplierActivity', '*', 'WRITE', 'ALLOW', 'ROLE', 'administrative');

View File

@ -1,5 +0,0 @@
ALTER TABLE `vn`.`clientConfig` ADD `maxCreditRows` int(11) NULL COMMENT 'Máximo número de registros a mantener en la tabla clientCredit';
UPDATE `vn`.`clientConfig`
SET `maxCreditRows` = 10
WHERE `id` = 1;

View File

@ -1,8 +0,0 @@
ALTER TABLE `vn`.`propertyDms` DROP FOREIGN KEY propertyDms_FK;
ALTER TABLE `vn`.`propertyDms` ADD CONSTRAINT propertyDms_FK FOREIGN KEY (dmsFk) REFERENCES `vn`.`dms`(id) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `vn`.`clientDms` DROP FOREIGN KEY clientDms_ibfk_2;
ALTER TABLE `vn`.`clientDms` ADD CONSTRAINT clientDms_ibfk_2 FOREIGN KEY (dmsFk) REFERENCES `vn`.`dms`(id) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `vn`.`workerDocument` DROP FOREIGN KEY workerDocument_ibfk_2;
ALTER TABLE `vn`.`workerDocument` ADD CONSTRAINT workerDocument_ibfk_2 FOREIGN KEY (document) REFERENCES `vn`.`dms`(id) ON DELETE CASCADE ON UPDATE CASCADE;

View File

@ -1,5 +0,0 @@
ALTER TABLE `vn`.`dmsType` ADD monthToDelete INT UNSIGNED DEFAULT NULL NULL;
ALTER TABLE `vn`.`dmsType` MODIFY COLUMN monthToDelete int(10) unsigned DEFAULT NULL NULL COMMENT 'Meses en el pasado para ir borrando registros, dejar a null para no borrarlos nunca';
UPDATE `vn`.`dmsType`
SET monthToDelete=6
WHERE id=20;

View File

@ -1,18 +0,0 @@
DELIMITER $$
$$
CREATE TRIGGER `vn`.`dms_beforeDelete`
BEFORE DELETE
ON dms FOR EACH ROW
BEGIN
DECLARE vCanNotBeDeleted INT;
SELECT COUNT(*) INTO vCanNotBeDeleted
FROM dmsType dt
WHERE NOT (code <=> 'trash')
AND dt.id = OLD.dmsTypeFk;
IF vCanNotBeDeleted THEN
CALL util.throw('A dms can not be deleted');
END IF;
END$$
DELIMITER ;

View File

@ -1,175 +0,0 @@
DROP PROCEDURE IF EXISTS vn.clean;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clean`()
BEGIN
DECLARE vDateShort DATETIME;
DECLARE vOneYearAgo DATE;
DECLARE vFourYearsAgo DATE;
DECLARE v18Month DATE;
DECLARE v26Month DATE;
DECLARE v3Month DATE;
DECLARE vTrashId varchar(15);
SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE());
SET vOneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE());
SET vFourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE());
SET v18Month = TIMESTAMPADD(MONTH, -18,CURDATE());
SET v26Month = TIMESTAMPADD(MONTH, -26,CURDATE());
SET v3Month = TIMESTAMPADD(MONTH, -3, CURDATE());
DELETE FROM ticketParking WHERE created < vDateShort;
DELETE FROM routesMonitor WHERE dated < vDateShort;
DELETE FROM workerTimeControlLog WHERE created < vDateShort;
DELETE FROM `message` WHERE sendDate < vDateShort;
DELETE FROM messageInbox WHERE sendDate < vDateShort;
DELETE FROM messageInbox WHERE sendDate < vDateShort;
DELETE FROM workerTimeControl WHERE timed < vFourYearsAgo;
DELETE FROM itemShelving WHERE created < CURDATE() AND visible = 0;
DELETE FROM ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE());
DELETE FROM entryLog WHERE creationDate < vDateShort;
DELETE IGNORE FROM expedition WHERE created < v26Month;
DELETE FROM sms WHERE created < v18Month;
DELETE FROM saleTracking WHERE created < vOneYearAgo;
DELETE tobs FROM ticketObservation tobs
JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < TIMESTAMPADD(YEAR,-2,CURDATE());
DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo;
DELETE FROM sharingCart where ended < vDateShort;
DELETE FROM sharingClient where ended < vDateShort;
DELETE tw.* FROM ticketWeekly tw
LEFT JOIN sale s ON s.ticketFk = tw.ticketFk WHERE s.itemFk IS NULL;
DELETE FROM claim WHERE ticketCreated < vFourYearsAgo;
DELETE FROM message WHERE sendDate < vDateShort;
-- Robert ubicacion anterior de trevelLog comentario para debug
DELETE sc FROM saleChecked sc
JOIN sale s ON sc.saleFk = s.id WHERE s.created < vDateShort;
DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Month;
DELETE bm
FROM buyMark bm
JOIN buy b ON b.id = bm.id
JOIN entry e ON e.id = b.entryFk
JOIN travel t ON t.id = e.travelFk
WHERE t.landed <= vDateShort;
DELETE FROM stowaway WHERE created < v3Month;
DELETE FROM vn.buy WHERE created < vDateShort AND entryFk = 9200;
DELETE FROM vn.itemShelvingLog WHERE created < vDateShort;
DELETE FROM vn.stockBuyed WHERE creationDate < vDateShort;
-- Equipos duplicados
DELETE w.*
FROM workerTeam w
JOIN (SELECT id, team, workerFk, COUNT(*) - 1 as duplicated
FROM workerTeam
GROUP BY team,workerFk
HAVING duplicated
) d ON d.team = w.team AND d.workerFk = w.workerFk AND d.id != w.id;
DELETE sc
FROM saleComponent sc
JOIN sale s ON s.id= sc.saleFk
JOIN ticket t ON t.id= s.ticketFk
WHERE t.shipped < v18Month;
DELETE c
FROM vn.claim c
JOIN vn.claimState cs ON cs.id = c.claimStateFk
WHERE cs.description = "Anulado" AND
c.created < vDateShort;
DELETE
FROM vn.expeditionTruck
WHERE ETD < v3Month;
-- borrar travels sin entradas
DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete;
CREATE TEMPORARY TABLE tmp.thermographToDelete
SELECT th.id,th.dmsFk
FROM vn.travel t
LEFT JOIN vn.entry e ON e.travelFk = t.id
JOIN vn.travelThermograph th ON th.travelFk = t.id
WHERE t.shipped < TIMESTAMPADD(MONTH, -3, CURDATE()) AND e.travelFk IS NULL;
SELECT dt.id into vTrashId
FROM vn.dmsType dt
WHERE dt.code = 'trash';
UPDATE tmp.thermographToDelete th
JOIN vn.dms d ON d.id = th.dmsFk
SET d.dmsTypeFk = vTrashId;
DELETE th
FROM tmp.thermographToDelete tmp
JOIN vn.travelThermograph th ON th.id = tmp.id;
DELETE t
FROM vn.travel t
LEFT JOIN vn.entry e ON e.travelFk = t.id
WHERE t.shipped < TIMESTAMPADD(MONTH, -3, CURDATE()) AND e.travelFk IS NULL;
UPDATE dms d
JOIN dmsType dt ON dt.id = d.dmsTypeFk
SET d.dmsTypeFk = vTrashId
WHERE created < TIMESTAMPADD(MONTH, -dt.monthToDelete, CURDATE());
-- borrar entradas sin compras
DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete;
CREATE TEMPORARY TABLE tmp.entryToDelete
SELECT e.*
FROM vn.entry e
LEFT JOIN vn.buy b ON b.entryFk = e.id
JOIN vn.entryConfig ec ON e.id != ec.defaultEntry
WHERE e.dated < TIMESTAMPADD(MONTH, -3, CURDATE()) AND b.entryFK IS NULL;
DELETE e
FROM vn.entry e
JOIN tmp.entryToDelete tmp ON tmp.id = e.id;
-- borrar de route registros menores a 4 años
DROP TEMPORARY TABLE IF EXISTS tmp.routeToDelete;
CREATE TEMPORARY TABLE tmp.routeToDelete
SELECT *
FROM vn.route r
WHERE created < TIMESTAMPADD(YEAR,-4,CURDATE());
UPDATE tmp.routeToDelete tmp
JOIN vn.dms d ON d.id = tmp.gestdocFk
SET d.dmsTypeFk = vTrashId;
DELETE r
FROM tmp.routeToDelete tmp
JOIN vn.route r ON r.id = tmp.id;
-- borrar registros de dua y awb menores a 2 años
DROP TEMPORARY TABLE IF EXISTS tmp.duaToDelete;
CREATE TEMPORARY TABLE tmp.duaToDelete
SELECT *
FROM vn.dua
WHERE operated < TIMESTAMPADD(YEAR,-2,CURDATE());
UPDATE tmp.duaToDelete tm
JOIN vn.dms d ON d.id = tm.gestdocFk
SET d.dmsTypeFk = vTrashId;
DELETE d
FROM tmp.duaToDelete tmp
JOIN vn.dua d ON d.id = tmp.id;
DELETE FROM vn.awb WHERE created < TIMESTAMPADD(YEAR,-2,CURDATE());
-- Borra los ficheros gestDoc
INSERT INTO vn.printServerQueue(priorityFk, labelReportFk)VALUES(1,11);
-- Borra los registros de collection y ticketcollection
DELETE FROM vn.collection WHERE created < vDateShort;
DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete;
DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete;
DROP TEMPORARY TABLE IF EXISTS tmp.duaToDelete;
DELETE FROM travelLog WHERE creationDate < v3Month;
CALL shelving_clean;
END$$
DELIMITER ;

View File

@ -1,2 +0,0 @@
INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
VALUES ('Dms','deleteTrashFiles','WRITE','ALLOW','ROLE','employee')

View File

@ -1,10 +0,0 @@
CREATE TABLE `vn`.`clientUnpaid` (
`clientFk` int(11) NOT NULL,
`dated` date NOT NULL,
`amount` double DEFAULT 0,
PRIMARY KEY (`clientFk`),
CONSTRAINT `clientUnpaid_clientFk` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON UPDATE CASCADE
);
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('ClientUnpaid', '*', '*', 'ALLOW', 'ROLE', 'administrative');

View File

@ -1,8 +0,0 @@
CREATE TABLE `vn`.`invoiceOut_queue` (
`invoiceFk` int(10) unsigned not null,
`queued` datetime default now() not null,
`printed` datetime null,
`status` VARCHAR(50) DEFAULT '' NULL,
CONSTRAINT `invoiceOut_queue_pk` PRIMARY KEY (`invoiceFk`),
CONSTRAINT `invoiceOut_queue_invoiceOut_id_fk` FOREIGN KEY (`invoiceFk`) REFERENCES `vn`.`invoiceOut` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
) comment 'Queue for PDF invoicing';

View File

@ -0,0 +1,5 @@
ALTER TABLE `vn`.`itemType` CHANGE `transaction` transaction__ tinyint(4) DEFAULT 0 NOT NULL;
ALTER TABLE `vn`.`itemType` CHANGE location location__ varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL;
ALTER TABLE `vn`.`itemType` CHANGE hasComponents hasComponents__ tinyint(1) DEFAULT 1 NOT NULL;
ALTER TABLE `vn`.`itemType` CHANGE warehouseFk warehouseFk__ smallint(6) unsigned DEFAULT 60 NOT NULL;
ALTER TABLE `vn`.`itemType` CHANGE compression compression__ decimal(5,2) DEFAULT 1.00 NULL;

View File

@ -1,3 +1,3 @@
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES
('SupplierAgencyTerm', '*', '*', 'ALLOW', 'ROLE', 'administrative');
('OsTicket', '*', '*', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,2 +1,3 @@
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES('EducationLevel', '*', '*', 'ALLOW', 'ROLE', 'employee');
VALUES
('OsTicketConfig', '*', '*', 'ALLOW', 'ROLE', 'it');

View File

@ -0,0 +1,20 @@
CREATE TABLE `vn`.`osTicketConfig` (
`id` int(11) NOT NULL,
`host` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`user` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`password` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`oldStatus` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`newStatusId` int(11) DEFAULT NULL,
`action` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`day` int(11) DEFAULT NULL,
`comment` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`hostDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`userDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`passwordDb` varchar(100) COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`portDb` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
INSERT INTO `vn`.`osTicketConfig`(`id`, `host`, `user`, `password`, `oldStatus`, `newStatusId`, `action`, `day`, `comment`, `hostDb`, `userDb`, `passwordDb`, `portDb`)
VALUES
(0, 'https://cau.verdnatura.es/scp', NULL, NULL, 'open', 3, 'Cerrar', 60, 'Este CAU se ha cerrado automáticamente', NULL, NULL, NULL, NULL);

View File

@ -0,0 +1,49 @@
INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId)
VALUES
('ClientConsumptionQueue', '*', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Ticket', 'deliveryNotePdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Ticket', 'deliveryNoteEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Ticket', 'deliveryNoteCsvPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Ticket', 'deliveryNoteCsvEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'campaignMetricsPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'campaignMetricsEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'clientWelcomeHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'clientWelcomeEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'creditRequestPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'creditRequestHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'creditRequestEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'printerSetupHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'printerSetupEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'sepaCoreEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'letterDebtorPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'letterDebtorStHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'letterDebtorStEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'letterDebtorNdHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'letterDebtorNdEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'clientDebtStatementPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'clientDebtStatementHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'clientDebtStatementEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'incotermsAuthorizationPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'incotermsAuthorizationHtml', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Client', 'incotermsAuthorizationEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Client', 'consumptionSendQueued', 'WRITE', 'ALLOW', 'ROLE', 'system'),
('InvoiceOut', 'invoiceEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('InvoiceOut', 'exportationPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('InvoiceOut', 'sendQueued', 'WRITE', 'ALLOW', 'ROLE', 'system'),
('Ticket', 'invoiceCsvPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Ticket', 'invoiceCsvEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Supplier', 'campaignMetricsPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Supplier', 'campaignMetricsEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Travel', 'extraCommunityPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Travel', 'extraCommunityEmail', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Entry', 'entryOrderPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('OsTicket', 'osTicketReportEmail', 'WRITE', 'ALLOW', 'ROLE', 'system'),
('Item', 'buyerWasteEmail', 'WRITE', 'ALLOW', 'ROLE', 'system'),
('Claim', 'claimPickupPdf', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Claim', 'claimPickupEmail', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'),
('Item', 'labelPdf', 'READ', 'ALLOW', 'ROLE', 'employee');
INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
VALUES ('Sector','*','READ','ALLOW','ROLE','employee');
INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
VALUES ('Sector','*','WRITE','ALLOW','ROLE','employee');

View File

@ -0,0 +1,9 @@
create table `vn`.`clientConsumptionQueue`
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
params json not null,
queued datetime default current_timestamp() not null,
printed datetime null,
status varchar(50) default '' null
)
comment 'Queue for client consumption PDF mailing';

View File

@ -0,0 +1 @@
rename table `vn`.`invoiceOut_queue` to `vn`.`invoiceOutQueue`;

View File

@ -0,0 +1,5 @@
ALTER TABLE `vn`.`itemConfig`
ADD id int null PRIMARY KEY first;
ALTER TABLE `vn`.`itemConfig`
ADD wasteRecipients VARCHAR(50) NOT NULL comment 'Weekly waste report schedule recipients';

View File

@ -0,0 +1,10 @@
create table `salix`.`printConfig`
(
id int auto_increment,
itRecipient varchar(50) null comment 'IT recipients for report mailing',
incidencesEmail varchar(50) null comment 'CAU destinatary email',
constraint printConfig_pk
primary key (id)
)
comment 'Print service config';

View File

@ -0,0 +1,100 @@
DROP TRIGGER IF EXISTS vn.sale_afterUpdate;
USE vn;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`sale_afterUpdate`
AFTER UPDATE ON `sale`
FOR EACH ROW
BEGIN
DECLARE vIsToSendMail BOOL;
DECLARE vPickedLines INT;
DECLARE vCollectionFk INT;
DECLARE vUserRole VARCHAR(255);
IF !(NEW.id <=> OLD.id)
OR !(NEW.ticketFk <=> OLD.ticketFk)
OR !(NEW.itemFk <=> OLD.itemFk)
OR !(NEW.quantity <=> OLD.quantity)
OR !(NEW.created <=> OLD.created)
OR !(NEW.isPicked <=> OLD.isPicked) THEN
CALL stock.log_add('sale', NEW.id, OLD.id);
END IF;
IF !(NEW.price <=> OLD.price)
OR !(NEW.ticketFk <=> OLD.ticketFk)
OR !(NEW.itemFk <=> OLD.itemFk)
OR !(NEW.quantity <=> OLD.quantity)
OR !(NEW.discount <=> OLD.discount) THEN
CALL ticket_requestRecalc(NEW.ticketFk);
CALL ticket_requestRecalc(OLD.ticketFk);
END IF;
IF !(OLD.ticketFk <=> NEW.ticketFk) THEN
UPDATE ticketRequest SET ticketFk = NEW.ticketFk
WHERE saleFk = NEW.id;
END IF;
SELECT account.myUser_getName() INTO vUserRole;
SELECT account.user_getMysqlRole(vUserRole) INTO vUserRole;
IF !(OLD.quantity <=> NEW.quantity) THEN
SELECT COUNT(*) INTO vIsToSendMail
FROM vncontrol.inter i
JOIN vn.state s ON s.id = i.state_id
WHERE s.code='PACKED'
AND i.Id_Ticket = OLD.ticketFk
AND vUserRole IN ('salesPerson', 'salesTeamBoss')
LIMIT 1;
IF vIsToSendMail THEN
CALL vn.mail_insert('jefesventas@verdnatura.es',
'noreply@verdnatura.es',
CONCAT('Ticket ', OLD.ticketFk ,' modificada cantidad tras encajado'),
CONCAT('Ticket <a href="https://salix.verdnatura.es/#!/ticket/', OLD.ticketFk ,'/log">', OLD.ticketFk ,'</a>. <br>',
'Modificada la catidad de ', OLD.quantity, ' a ' , NEW.quantity,
' del artículo ', OLD.itemFk, ' tras estado encajado del ticket. <br>',
'Este email se ha generado automáticamente' )
);
END IF;
IF (OLD.quantity > NEW.quantity) THEN
INSERT INTO saleComponent(saleFk, componentFk, value)
SELECT NEW.id, cm.id, sc.value
FROM saleComponent sc
JOIN component cd ON cd.id = sc.componentFk
JOIN component cm ON cm.code = 'mana'
WHERE saleFk = NEW.id AND cd.code = 'lastUnitsDiscount'
ON DUPLICATE KEY UPDATE value = sc.value + VALUES(value);
DELETE sc.*
FROM vn.saleComponent sc
JOIN component c ON c.id = sc.componentFk
WHERE saleFk = NEW.id AND c.code = 'lastUnitsDiscount';
END IF;
INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`)
SELECT r.id
FROM vn.sale s
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.route r ON r.id = t.routeFk
WHERE r.isOk = FALSE
AND s.id = NEW.id
AND r.created >= CURDATE()
GROUP BY r.id;
END IF;
IF !(ABS(NEW.isPicked) <=> ABS(OLD.isPicked)) AND NEW.quantity > 0 THEN
UPDATE vn.collection c
JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk
SET c.salePickedCount = c.salePickedCount + IF(NEW.isPicked != 0, 1, -1);
END IF;
IF !(NEW.quantity <=> OLD.quantity) AND (NEW.quantity = 0 OR OLD.quantity = 0) THEN
UPDATE vn.collection c
JOIN vn.ticketCollection tc ON tc.collectionFk = c.id AND tc.ticketFk = NEW.ticketFk
SET c.saleTotalCount = c.saleTotalCount + IF(OLD.quantity = 0, 1, -1);
END IF;
END$$
DELIMITER ;

View File

@ -0,0 +1,6 @@
alter table `vn`.`sample`
add model VARCHAR(25) null comment 'Model name in plural';
UPDATE vn.sample t
SET t.model = 'Clients'
WHERE t.id IN(12, 13, 14, 15, 16, 18, 19, 20);

View File

@ -19,8 +19,9 @@ module.exports = class Docker {
* to avoid a bug with OverlayFS driver on MacOS.
*
* @param {Boolean} ci continuous integration environment argument
* @param {String} networkName Name of the container network
*/
async run(ci) {
async run(ci, networkName = 'jenkins') {
let d = new Date();
let pad = v => v < 10 ? '0' + v : v;
let stamp = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
@ -42,8 +43,16 @@ module.exports = class Docker {
let runChown = process.platform != 'linux';
let network = '';
if (ci) network = `--network="${networkName}"`;
log('Starting container...');
const container = await this.execP(`docker run --env RUN_CHOWN=${runChown} -d ${dockerArgs} salix-db`);
const container = await this.execP(`
docker run \
${network} \
--env RUN_CHOWN=${runChown} \
-d ${dockerArgs} salix-db
`);
this.id = container.stdout.trim();
try {
@ -51,10 +60,11 @@ module.exports = class Docker {
let inspect = await this.execP(`docker inspect -f "{{json .NetworkSettings}}" ${this.id}`);
let netSettings = JSON.parse(inspect.stdout);
if (ci)
this.dbConf.host = netSettings.Gateway;
this.dbConf.port = netSettings.Ports['3306/tcp'][0]['HostPort'];
if (ci) {
this.dbConf.host = netSettings.Networks[networkName].IPAddress;
this.dbConf.port = 3306;
} else
this.dbConf.port = netSettings.Ports['3306/tcp'][0]['HostPort'];
}
await this.wait();

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -239,7 +239,7 @@ xdescribe('worker workerTimeControl_check()', () => {
stmts.push('START TRANSACTION');
stmt = new ParameterizedSQL(`INSERT INTO postgresql.calendar_employee(business_id,calendar_state_id,date)
stmt = new ParameterizedSQL(`INSERT INTO postgresql.calendar_employee(businessFk,calendar_state_id,date)
VALUES
(?,1,CURDATE())`, [
workerId
@ -282,7 +282,7 @@ xdescribe('worker workerTimeControl_check()', () => {
stmts.push('START TRANSACTION');
stmt = new ParameterizedSQL(`UPDATE postgresql.business SET date_end=DATE_ADD(CURDATE(), INTERVAL -1 DAY) WHERE business_id=?`, [
stmt = new ParameterizedSQL(`UPDATE vn.business SET ended = DATE_ADD(CURDATE(), INTERVAL -1 DAY) WHERE id = ?`, [
workerId
]);
stmts.push(stmt);

View File

@ -391,7 +391,7 @@ export default {
intrastadCheckbox: '.vn-popover.shown vn-horizontal:nth-child(3) > vn-check[label="Intrastat"]',
originCheckbox: '.vn-popover.shown vn-horizontal:nth-child(3) > vn-check[label="Origin"]',
buyerCheckbox: '.vn-popover.shown vn-horizontal:nth-child(3) > vn-check[label="Buyer"]',
densityCheckbox: '.vn-popover.shown vn-horizontal:nth-child(3) > vn-check[label="Density"]',
weightByPieceCheckbox: '.vn-popover.shown vn-horizontal:nth-child(3) > vn-check[label="Weight/Piece"]',
saveFieldsButton: '.vn-popover.shown vn-button[label="Save"] > button'
},
itemFixedPrice: {
@ -835,14 +835,16 @@ export default {
confirmButton: '.vn-confirm.shown button[response="accept"]',
},
routeIndex: {
anyResult: 'vn-table a',
firstRouteCheckbox: 'a:nth-child(1) vn-td:nth-child(1) > vn-check',
anyResult: 'vn-route-index tbody > tr',
firstRouteCheckbox: 'vn-route-index tbody > tr:nth-child(1) > td:nth-child(1) > vn-check',
addNewRouteButton: 'vn-route-index a[ui-sref="route.create"]',
cloneButton: 'vn-route-index button > vn-icon[icon="icon-clone"]',
submitClonationButton: 'tpl-buttons > button[response="accept"]',
openAdvancedSearchButton: 'vn-searchbar .append vn-icon[icon="arrow_drop_down"]',
searchAgencyAutocomlete: 'vn-route-search-panel vn-autocomplete[ng-model="filter.agencyModeFk"]',
advancedSearchButton: 'vn-route-search-panel button[type=submit]',
previewButton: 'vn-route-index tbody > tr:nth-child(7) > td:nth-child(11) > vn-icon-button[icon="preview"]',
},
createRouteView: {
worker: 'vn-route-create vn-autocomplete[ng-model="$ctrl.route.workerFk"]',
@ -862,6 +864,8 @@ export default {
firstTicketDescriptor: '.vn-popover.shown vn-ticket-descriptor',
firstAlias: 'vn-route-summary vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(3) > span',
firstClientDescriptor: '.vn-popover.shown vn-client-descriptor',
goToRouteSummaryButton: 'vn-route-summary > vn-card > h5 > a',
},
routeBasicData: {
worker: 'vn-route-basic-data vn-autocomplete[ng-model="$ctrl.route.workerFk"]',
@ -1014,9 +1018,9 @@ export default {
save: 'vn-travel-create vn-submit > button'
},
travelExtraCommunity: {
anySearchResult: 'vn-travel-extra-community > vn-data-viewer div > vn-tbody > vn-tr',
firstTravelReference: 'vn-travel-extra-community vn-tbody:nth-child(2) vn-td-editable[name="reference"]',
firstTravelLockedKg: 'vn-travel-extra-community vn-tbody:nth-child(2) vn-td-editable[name="lockedKg"]',
anySearchResult: 'vn-travel-extra-community > vn-card div > tbody > tr[ng-attr-id="{{::travel.id}}"]',
firstTravelReference: 'vn-travel-extra-community tbody:nth-child(2) vn-textfield[ng-model="travel.ref"]',
firstTravelLockedKg: 'vn-travel-extra-community tbody:nth-child(2) vn-input-number[ng-model="travel.kg"]',
removeContinentFilter: 'vn-searchbar > form > vn-textfield > div.container > div.prepend > prepend > div > span:nth-child(3) > vn-icon > i'
},
travelBasicData: {

View File

@ -8,7 +8,7 @@ describe('Client Edit web access path', () => {
beforeAll(async() => {
browser = await getBrowser();
page = browser.page;
await page.loginAndModule('employee', 'client');
await page.loginAndModule('salesPerson', 'client');
await page.accessToSearchResult('max');
await page.accessToSection('client.card.webAccess');
});

View File

@ -31,7 +31,7 @@ describe('Item index path', () => {
await page.waitToClick(selectors.itemsIndex.intrastadCheckbox);
await page.waitToClick(selectors.itemsIndex.originCheckbox);
await page.waitToClick(selectors.itemsIndex.buyerCheckbox);
await page.waitToClick(selectors.itemsIndex.densityCheckbox);
await page.waitToClick(selectors.itemsIndex.weightByPieceCheckbox);
await page.waitToClick(selectors.itemsIndex.saveFieldsButton);
const message = await page.waitForSnackbar();
@ -64,7 +64,7 @@ describe('Item index path', () => {
await page.waitToClick(selectors.itemsIndex.intrastadCheckbox);
await page.waitToClick(selectors.itemsIndex.originCheckbox);
await page.waitToClick(selectors.itemsIndex.buyerCheckbox);
await page.waitToClick(selectors.itemsIndex.densityCheckbox);
await page.waitToClick(selectors.itemsIndex.weightByPieceCheckbox);
await page.waitToClick(selectors.itemsIndex.saveFieldsButton);
const message = await page.waitForSnackbar();

View File

@ -9,7 +9,8 @@ describe('Route summary path', () => {
browser = await getBrowser();
page = browser.page;
await page.loginAndModule('employee', 'route');
await page.waitToClick('vn-route-index vn-tbody > a:nth-child(7)');
await page.waitToClick(selectors.routeIndex.previewButton);
await page.waitToClick(selectors.routeSummary.goToRouteSummaryButton);
});
afterAll(async() => {
@ -34,6 +35,8 @@ describe('Route summary path', () => {
});
it('should click on the first ticket ID making the descriptor popover visible', async() => {
await page.waitForState('route.card.summary');
await page.waitForTimeout(250);
await page.waitToClick(selectors.routeSummary.firstTicketID);
await page.waitForSelector(selectors.routeSummary.firstTicketDescriptor);
const visible = await page.isVisible(selectors.routeSummary.firstTicketDescriptor);

View File

@ -22,7 +22,7 @@ describe('InvoiceOut manual invoice path', () => {
});
it('should create an invoice from a ticket', async() => {
await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceTicket, '7');
await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceTicket, '15');
await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceSerial, 'Global nacional');
await page.autocompleteSearch(selectors.invoiceOutIndex.manualInvoiceTaxArea, 'national');
await page.waitToClick(selectors.invoiceOutIndex.saveInvoice);

View File

@ -19,18 +19,22 @@ describe('Travel extra community path', () => {
it('should edit the travel reference and the locked kilograms', async() => {
await page.waitToClick(selectors.travelExtraCommunity.removeContinentFilter);
await page.waitForSpinnerLoad();
await page.writeOnEditableTD(selectors.travelExtraCommunity.firstTravelReference, 'edited reference');
await page.waitForSpinnerLoad();
await page.writeOnEditableTD(selectors.travelExtraCommunity.firstTravelLockedKg, '1500');
await page.clearInput(selectors.travelExtraCommunity.firstTravelReference);
await page.write(selectors.travelExtraCommunity.firstTravelReference, 'edited reference');
await page.clearInput(selectors.travelExtraCommunity.firstTravelLockedKg);
await page.write(selectors.travelExtraCommunity.firstTravelLockedKg, '1500');
const message = await page.waitForSnackbar();
expect(message.text).toContain('Data saved!');
});
it('should reload the index and confirm the reference and locked kg were edited', async() => {
await page.accessToSection('travel.index');
await page.accessToSection('travel.extraCommunity');
await page.waitToClick(selectors.travelExtraCommunity.removeContinentFilter);
await page.waitForTextInElement(selectors.travelExtraCommunity.firstTravelReference, 'edited reference');
const reference = await page.getProperty(selectors.travelExtraCommunity.firstTravelReference, 'innerText');
const lockedKg = await page.getProperty(selectors.travelExtraCommunity.firstTravelLockedKg, 'innerText');
const reference = await page.waitToGetProperty(selectors.travelExtraCommunity.firstTravelReference, 'value');
const lockedKg = await page.waitToGetProperty(selectors.travelExtraCommunity.firstTravelLockedKg, 'value');
expect(reference).toContain('edited reference');
expect(lockedKg).toContain(1500);

View File

@ -150,10 +150,12 @@ describe('Account create and basic data path', () => {
describe('Set password', () => {
it('should set the password using the descriptor menu', async() => {
const newPassword = 'quantum.12345';
await page.waitToClick(selectors.accountDescriptor.menuButton);
await page.waitToClick(selectors.accountDescriptor.setPassword);
await page.write(selectors.accountDescriptor.newPassword, 'quantum.crypt0graphy');
await page.write(selectors.accountDescriptor.repeatPassword, 'quantum.crypt0graphy');
await page.write(selectors.accountDescriptor.newPassword, newPassword);
await page.write(selectors.accountDescriptor.repeatPassword, newPassword);
await page.waitToClick(selectors.accountDescriptor.acceptButton);
const message = await page.waitForSnackbar();

View File

@ -23,12 +23,15 @@ export default class InputTime extends Field {
let date = null;
let value = this.input.value;
if (this.field && !this.modelDate)
this.modelDate = this.field;
if (value) {
let split = value.split(':').map(i => parseInt(i) || null);
date = this.field instanceof Date
? this.field
: new Date(this.field || null);
date = this.modelDate
? new Date(this.modelDate)
: new Date();
date.setHours(split[0], split[1], 0, 0);
}

View File

@ -10,9 +10,9 @@
<div ng-transclude="actions"></div>
</div>
<div class="actions-right">
<div class="totalRows" ng-if="$ctrl.model.data">
{{model.data.length}}
<span translate>results</span>
<div class="totalRows" ng-if="$ctrl.model.data">
{{model.data.length}}
<span translate>results</span>
</div>
<vn-button icon="search"
ng-if="$ctrl.options.activeButtons.search"
@ -40,7 +40,8 @@
</vn-button>
</div>
<vn-button icon="refresh"
ng-click="$ctrl.model.refresh()"
ng-click="$ctrl.refresh()"
disabled="$ctrl.isRefreshing"
vn-tooltip="Refresh">
</vn-button>
</div>
@ -64,7 +65,7 @@
<vn-crud-model
ng-if="$ctrl.viewConfigId"
vn-id="userViewModel"
vn-id="userViewModel"
url="UserConfigViews"
link="{tableCode: $ctrl.viewConfigId, userFk: $ctrl.currentUserId}"
data="$ctrl.viewConfig"
@ -75,9 +76,9 @@
<div class="smart-table-columns vn-pa-md vn-w-sm">
<vn-horizontal>
<h6 translate style="margin:0">Shown columns</h6>
<vn-icon
<vn-icon
vn-none
icon="info"
icon="info"
color-marginal
vn-tooltip="Check the columns you want to see"/>
</vn-horizontal>
@ -101,4 +102,4 @@
</vn-horizontal>
</div>
</tpl-body>
</vn-popover>
</vn-popover>

View File

@ -511,6 +511,12 @@ export default class SmartTable extends Component {
return this.model.save()
.then(() => this.vnApp.showSuccess(this.$t('Data saved!')));
}
refresh() {
this.isRefreshing = true;
this.model.refresh()
.then(() => this.isRefreshing = false);
}
}
SmartTable.$inject = ['$element', '$scope', '$transclude'];

View File

@ -10,24 +10,12 @@ class Email {
/**
* Sends an email displaying a notification when it's sent.
*
* @param {String} template The email report name
* @param {String} path The email report name
* @param {Object} params The email parameters
* @return {Promise} Promise resolved when it's sent
*/
send(template, params) {
return this.$http.get(`email/${template}`, {params})
.then(() => this.vnApp.showMessage(this.$t('Notification sent!')));
}
/**
* Sends an email displaying a notification when it's sent.
*
* @param {String} template The email report name
* @param {Object} params The email parameters
* @return {Promise} Promise resolved when it's sent
*/
sendCsv(template, params) {
return this.$http.get(`csv/${template}/send`, {params})
send(path, params) {
return this.$http.post(path, params)
.then(() => this.vnApp.showMessage(this.$t('Notification sent!')));
}
}

View File

@ -10,30 +10,16 @@ class Report {
* Shows a report in another window, automatically adds the authorization
* token to params.
*
* @param {String} report The report name
* @param {String} path The report name
* @param {Object} params The report parameters
*/
show(report, params) {
show(path, params) {
params = Object.assign({
authorization: this.vnToken.token
access_token: this.vnToken.token
}, params);
const serializedParams = this.$httpParamSerializer(params);
window.open(`api/report/${report}?${serializedParams}`);
}
/**
* Shows a report in another window, automatically adds the authorization
* token to params.
*
* @param {String} report The report name
* @param {Object} params The report parameters
*/
showCsv(report, params) {
params = Object.assign({
authorization: this.vnToken.token
}, params);
const serializedParams = this.$httpParamSerializer(params);
window.open(`api/csv/${report}/download?${serializedParams}`);
const query = serializedParams ? `?${serializedParams}` : '';
window.open(`api/${path}${query}`);
}
}
Report.$inject = ['$httpParamSerializer', 'vnToken'];

221
front/package-lock.json generated
View File

@ -1,78 +1,215 @@
{
"name": "salix-front",
"version": "1.0.0",
"lockfileVersion": 1,
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "salix-front",
"version": "1.0.0",
"license": "GPL-3.0",
"dependencies": {
"@uirouter/angularjs": "^1.0.20",
"angular": "^1.7.5",
"angular-animate": "^1.7.8",
"angular-moment": "^1.3.0",
"angular-translate": "^2.18.1",
"angular-translate-loader-partial": "^2.18.1",
"croppie": "^2.6.5",
"js-yaml": "^3.13.1",
"mg-crud": "^1.1.2",
"oclazyload": "^0.6.3",
"require-yaml": "0.0.1",
"validator": "^6.3.0"
}
},
"node_modules/@uirouter/angularjs": {
"version": "1.0.29",
"license": "MIT",
"dependencies": {
"@uirouter/core": "6.0.7"
},
"engines": {
"node": ">=4.0.0"
},
"peerDependencies": {
"angular": ">=1.2.0"
}
},
"node_modules/@uirouter/core": {
"version": "6.0.7",
"license": "MIT",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/angular": {
"version": "1.8.2",
"license": "MIT"
},
"node_modules/angular-animate": {
"version": "1.8.2",
"license": "MIT"
},
"node_modules/angular-moment": {
"version": "1.3.0",
"license": "MIT",
"dependencies": {
"moment": ">=2.8.0 <3.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/angular-translate": {
"version": "2.18.4",
"license": "MIT",
"dependencies": {
"angular": "^1.8.0"
},
"engines": {
"node": "*"
}
},
"node_modules/angular-translate-loader-partial": {
"version": "2.18.4",
"license": "MIT",
"dependencies": {
"angular-translate": "~2.18.4"
}
},
"node_modules/argparse": {
"version": "1.0.10",
"license": "MIT",
"dependencies": {
"sprintf-js": "~1.0.2"
}
},
"node_modules/croppie": {
"version": "2.6.5",
"license": "MIT"
},
"node_modules/esprima": {
"version": "4.0.1",
"license": "BSD-2-Clause",
"bin": {
"esparse": "bin/esparse.js",
"esvalidate": "bin/esvalidate.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/js-yaml": {
"version": "3.14.1",
"license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
},
"bin": {
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/mg-crud": {
"version": "1.1.2",
"license": "MIT",
"dependencies": {
"angular": "^1.6.1"
}
},
"node_modules/moment": {
"version": "2.29.1",
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/oclazyload": {
"version": "0.6.3",
"license": "MIT"
},
"node_modules/require-yaml": {
"version": "0.0.1",
"license": "BSD",
"dependencies": {
"js-yaml": ""
}
},
"node_modules/require-yaml/node_modules/argparse": {
"version": "2.0.1",
"license": "Python-2.0"
},
"node_modules/require-yaml/node_modules/js-yaml": {
"version": "4.1.0",
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
},
"bin": {
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/sprintf-js": {
"version": "1.0.3",
"license": "BSD-3-Clause"
},
"node_modules/validator": {
"version": "6.3.0",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
}
},
"dependencies": {
"@uirouter/angularjs": {
"version": "1.0.29",
"resolved": "https://registry.npmjs.org/@uirouter/angularjs/-/angularjs-1.0.29.tgz",
"integrity": "sha512-RImWnBarNixkMto0o8stEaGwZmvhv5cnuOLXyMU2pY8MP2rgEF74ZNJTLeJCW14LR7XDUxVH8Mk8bPI6lxedmQ==",
"requires": {
"@uirouter/core": "6.0.7"
}
},
"@uirouter/core": {
"version": "6.0.7",
"resolved": "https://registry.npmjs.org/@uirouter/core/-/core-6.0.7.tgz",
"integrity": "sha512-KUTJxL+6q0PiBnFx4/Z+Hsyg0pSGiaW5yZQeJmUxknecjpTbnXkLU8H2EqRn9N2B+qDRa7Jg8RcgeNDPY72O1w=="
"version": "6.0.7"
},
"angular": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/angular/-/angular-1.8.2.tgz",
"integrity": "sha512-IauMOej2xEe7/7Ennahkbb5qd/HFADiNuLSESz9Q27inmi32zB0lnAsFeLEWcox3Gd1F6YhNd1CP7/9IukJ0Gw=="
"version": "1.8.2"
},
"angular-animate": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/angular-animate/-/angular-animate-1.8.2.tgz",
"integrity": "sha512-Jbr9+grNMs9Kj57xuBU3Ju3NOPAjS1+g2UAwwDv7su1lt0/PLDy+9zEwDiu8C8xJceoTbmBNKiWGPJGBdCQLlA=="
"version": "1.8.2"
},
"angular-moment": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/angular-moment/-/angular-moment-1.3.0.tgz",
"integrity": "sha512-KG8rvO9MoaBLwtGnxTeUveSyNtrL+RNgGl1zqWN36+HDCCVGk2DGWOzqKWB6o+eTTbO3Opn4hupWKIElc8XETA==",
"requires": {
"moment": ">=2.8.0 <3.0.0"
}
},
"angular-translate": {
"version": "2.18.4",
"resolved": "https://registry.npmjs.org/angular-translate/-/angular-translate-2.18.4.tgz",
"integrity": "sha512-KohNrkH6J9PK+VW0L/nsRTcg5Fw70Ajwwe3Jbfm54Pf9u9Fd+wuingoKv+h45mKf38eT+Ouu51FPua8VmZNoCw==",
"requires": {
"angular": "^1.8.0"
}
},
"angular-translate-loader-partial": {
"version": "2.18.4",
"resolved": "https://registry.npmjs.org/angular-translate-loader-partial/-/angular-translate-loader-partial-2.18.4.tgz",
"integrity": "sha512-bsjR+FbB0sdA2528E/ugwKdlPPQhA1looxLxI3otayBTFXBpED33besfSZhYAISLgNMSL038vSssfRUen9qD8w==",
"requires": {
"angular-translate": "~2.18.4"
}
},
"argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
"integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
"requires": {
"sprintf-js": "~1.0.2"
}
},
"croppie": {
"version": "2.6.5",
"resolved": "https://registry.npmjs.org/croppie/-/croppie-2.6.5.tgz",
"integrity": "sha512-IlChnVUGG5T3w2gRZIaQgBtlvyuYnlUWs2YZIXXR3H9KrlO1PtBT3j+ykxvy9eZIWhk+V5SpBmhCQz5UXKrEKQ=="
"version": "2.6.5"
},
"esprima": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="
"version": "4.0.1"
},
"js-yaml": {
"version": "3.14.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz",
"integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==",
"requires": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
@ -80,39 +217,27 @@
},
"mg-crud": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/mg-crud/-/mg-crud-1.1.2.tgz",
"integrity": "sha1-p6AWGzWSPK7/8ZpIBpS2V1vDggw=",
"requires": {
"angular": "^1.6.1"
}
},
"moment": {
"version": "2.29.1",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.29.1.tgz",
"integrity": "sha512-kHmoybcPV8Sqy59DwNDY3Jefr64lK/by/da0ViFcuA4DH0vQg5Q6Ze5VimxkfQNSC+Mls/Kx53s7TjP1RhFEDQ=="
"version": "2.29.1"
},
"oclazyload": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/oclazyload/-/oclazyload-0.6.3.tgz",
"integrity": "sha1-Kjirv/QJDAihEBZxkZRbWfLoJ5w="
"version": "0.6.3"
},
"require-yaml": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/require-yaml/-/require-yaml-0.0.1.tgz",
"integrity": "sha1-LhsY2RPDuqcqWk03O28Tjd0sMr0=",
"requires": {
"js-yaml": "^4.1.0"
"js-yaml": ""
},
"dependencies": {
"argparse": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="
"version": "2.0.1"
},
"js-yaml": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
"requires": {
"argparse": "^2.0.1"
}
@ -120,14 +245,10 @@
}
},
"sprintf-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
"integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw="
"version": "1.0.3"
},
"validator": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/validator/-/validator-6.3.0.tgz",
"integrity": "sha1-R84j7Y1Ord+p1LjvAHG2zxB418g="
"version": "6.3.0"
}
}
}

View File

@ -24,6 +24,6 @@ describe('Model rewriteDbError()', () => {
error = e;
}
expect(error.message).toEqual(`The tag can't be repeated`);
expect(error.message).toEqual(`The tag or priority can't be repeated for an item`);
});
});

View File

@ -130,5 +130,7 @@
"Descanso diario 12h.": "Daily rest 12h.",
"Fichadas impares": "Odd signs",
"Descanso diario 9h.": "Daily rest 9h.",
"Descanso semanal 36h. / 72h.": "Weekly rest 36h. / 72h."
"Descanso semanal 36h. / 72h.": "Weekly rest 36h. / 72h.",
"Password does not meet requirements": "Password does not meet requirements",
"Not enough privileges to edit a client": "Not enough privileges to edit a client"
}

View File

@ -44,7 +44,7 @@
"is not a valid date": "No es una fecha valida",
"Barcode must be unique": "El código de barras debe ser único",
"The warehouse can't be repeated": "El almacén no puede repetirse",
"The tag can't be repeated": "El tag no puede repetirse",
"The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item",
"The observation type can't be repeated": "El tipo de observación no puede repetirse",
"A claim with that sale already exists": "Ya existe una reclamación para esta línea",
"You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo",
@ -146,7 +146,7 @@
"Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante",
"ORDER_ALREADY_CONFIRMED": "ORDER_ALREADY_CONFIRMED",
"Invalid password": "Invalid password",
"Password does not meet requirements": "Password does not meet requirements",
"Password does not meet requirements": "La contraseña no cumple los requisitos",
"Role already assigned": "Role already assigned",
"Invalid role name": "Invalid role name",
"Role name must be written in camelCase": "Role name must be written in camelCase",
@ -208,7 +208,7 @@
"Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes",
"Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio",
"You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito",
"You can't change the credit set to zero from a manager": "No puedes cambiar el cŕedito establecido a cero por un gerente",
"You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas",
"Amounts do not match": "Las cantidades no coinciden",
"The PDF document does not exists": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'",
"The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos",
@ -232,5 +232,8 @@
"Fichadas impares": "Fichadas impares",
"Descanso diario 12h.": "Descanso diario 12h.",
"Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.",
"Dirección incorrecta": "Dirección incorrecta"
"Dirección incorrecta": "Dirección incorrecta",
"Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador",
"Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador",
"Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente"
}

View File

@ -1,3 +1,3 @@
module.exports = function(app) {
require('../../../print/boot.js')(app);
require('vn-print').boot(app);
};

View File

@ -1,3 +1,9 @@
/**
* Transforms an object to a raw data CSV file.
*
* @param {Object} rows Data
* @return {String} Formatted CSV data
*/
function toCSV(rows) {
const [columns] = rows;
let content = Object.keys(columns).join('\t');

View File

@ -56,6 +56,12 @@ module.exports = Self => {
if (!userExists) {
await Self.rawSql('CREATE USER ?@? IDENTIFIED BY ?',
[mysqlUser, this.userHost, password]);
await Self.rawSql(
`UPDATE mysql.global_priv
SET Priv = JSON_SET(Priv, '$.autogenerated' , TRUE)
WHERE User = ? AND Host = ?`,
[mysqlUser, this.userHost]
);
userExists = true;
} else {
switch (this.dbType) {

View File

@ -0,0 +1,58 @@
const {Report, Email, smtp} = require('vn-print');
module.exports = Self => {
Self.remoteMethodCtx('claimPickupEmail', {
description: 'Sends the the claim pickup order email with an attached PDF',
accepts: [
{
arg: 'id',
type: 'number',
required: true,
description: 'The client id',
http: {source: 'path'}
},
{
arg: 'recipient',
type: 'string',
description: 'The recipient email',
required: true,
},
{
arg: 'replyTo',
type: 'string',
description: 'The sender email to reply to',
required: false
},
{
arg: 'recipientId',
type: 'number',
description: 'The recipient id to send to the recipient preferred language',
required: false
}
],
returns: {
type: ['object'],
root: true
},
http: {
path: '/:id/claim-pickup-email',
verb: 'POST'
}
});
Self.claimPickupEmail = async(ctx, id) => {
const args = Object.assign({}, ctx.args);
const params = {
recipient: args.recipient,
lang: ctx.req.getLocale()
};
delete args.ctx;
for (const param in args)
params[param] = args[param];
const email = new Email('claim-pickup-order', params);
return email.send();
};
};

View File

@ -0,0 +1,55 @@
const { Report } = require('vn-print');
module.exports = Self => {
Self.remoteMethodCtx('claimPickupPdf', {
description: 'Returns the claim pickup order pdf',
accepts: [
{
arg: 'id',
type: 'number',
required: true,
description: 'The claim id',
http: {source: 'path'}
},
{
arg: 'recipientId',
type: 'number',
description: 'The recipient id',
required: false
}
],
returns: [
{
arg: 'body',
type: 'file',
root: true
}, {
arg: 'Content-Type',
type: 'String',
http: {target: 'header'}
}, {
arg: 'Content-Disposition',
type: 'String',
http: {target: 'header'}
}
],
http: {
path: '/:id/claim-pickup-pdf',
verb: 'GET'
}
});
Self.claimPickupPdf = async(ctx, id) => {
const args = Object.assign({}, ctx.args);
const params = {lang: ctx.req.getLocale()};
delete args.ctx;
for (const param in args)
params[param] = args[param];
const report = new Report('claim-pickup-order', params);
const stream = await report.toPdfStream();
return [stream, 'application/pdf', `filename="doc-${id}.pdf"`];
};
};

View File

@ -9,4 +9,6 @@ module.exports = Self => {
require('../methods/claim/isEditable')(Self);
require('../methods/claim/updateClaimDestination')(Self);
require('../methods/claim/downloadFile')(Self);
require('../methods/claim/claimPickupPdf')(Self);
require('../methods/claim/claimPickupEmail')(Self);
};

Some files were not shown because too many files have changed in this diff Show More