Merge branch 'dev' into 7716-travel_setDelivered
gitea/salix/pipeline/pr-dev This commit looks good Details

This commit is contained in:
Robert Ferrús 2024-07-19 11:55:02 +00:00
commit 6cef9175c0
87 changed files with 950 additions and 511 deletions

View File

@ -63,8 +63,7 @@ module.exports = Self => {
iss.isPicked iss.isPicked
FROM ticketCollection tc FROM ticketCollection tc
LEFT JOIN collection c ON c.id = tc.collectionFk LEFT JOIN collection c ON c.id = tc.collectionFk
JOIN ticket t ON t.id = tc.ticketFk JOIN sale s ON s.ticketFk = tc.ticketFk
JOIN sale s ON s.ticketFk = t.id
LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk
LEFT JOIN parking p2 ON p2.id = sg.parkingFk LEFT JOIN parking p2 ON p2.id = sg.parkingFk
@ -103,9 +102,8 @@ module.exports = Self => {
FROM sectorCollection sc FROM sectorCollection sc
JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id
JOIN saleGroup sg ON sg.id = ss.saleGroupFk JOIN saleGroup sg ON sg.id = ss.saleGroupFk
JOIN ticket t ON t.id = sg.ticketFk LEFT JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id
JOIN sale s ON s.ticketFk = t.id JOIN sale s ON s.id = sgd.saleFk
LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id
LEFT JOIN parking p2 ON p2.id = sg.parkingFk LEFT JOIN parking p2 ON p2.id = sg.parkingFk
JOIN item i ON i.id = s.itemFk JOIN item i ON i.id = s.itemFk
JOIN itemShelvingSale iss ON iss.saleFk = s.id JOIN itemShelvingSale iss ON iss.saleFk = s.id

View File

@ -24,7 +24,7 @@ module.exports = Self => {
try { try {
const options = {transaction: tx, userId: ctx.req.accessToken.userId}; const options = {transaction: tx, userId: ctx.req.accessToken.userId};
const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileConfig', null, options); const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileMultiConfig', null, options);
const updatableFiles = []; const updatableFiles = [];
for (const file of files) { for (const file of files) {
@ -54,7 +54,7 @@ module.exports = Self => {
const tables = await Self.rawSql(` const tables = await Self.rawSql(`
SELECT fileName, toTable, file SELECT fileName, toTable, file
FROM edi.tableConfig FROM edi.tableMultiConfig
WHERE file IN (?)`, [fileNames], options); WHERE file IN (?)`, [fileNames], options);
for (const table of tables) { for (const table of tables) {
@ -85,7 +85,7 @@ module.exports = Self => {
for (const file of updatableFiles) { for (const file of updatableFiles) {
console.log(`Updating file ${file.name} checksum...`); console.log(`Updating file ${file.name} checksum...`);
await Self.rawSql(` await Self.rawSql(`
UPDATE edi.fileConfig UPDATE edi.fileMultiConfig
SET checksum = ? SET checksum = ?
WHERE name = ?`, WHERE name = ?`,
[file.checksum, file.name], options); [file.checksum, file.name], options);
@ -228,7 +228,7 @@ module.exports = Self => {
await Self.rawSql(sqlTemplate, [filePath], options); await Self.rawSql(sqlTemplate, [filePath], options);
await Self.rawSql(` await Self.rawSql(`
UPDATE edi.tableConfig UPDATE edi.tableMultiConfig
SET updated = ? SET updated = ?
WHERE fileName = ? WHERE fileName = ?
`, [Date.vnNew(), baseName], options); `, [Date.vnNew(), baseName], options);

View File

@ -2,7 +2,7 @@
<soap:Header> <soap:Header>
<mrw:AuthInfo> <mrw:AuthInfo>
<mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia> <mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia>
<mrw:CodigoAbonado><%= mrw.subscriberCode %></mrw:CodigoAbonado> <mrw:CodigoAbonado><%= clientType %></mrw:CodigoAbonado>
<mrw:CodigoDepartamento/> <mrw:CodigoDepartamento/>
<mrw:UserName><%= mrw.user %></mrw:UserName> <mrw:UserName><%= mrw.user %></mrw:UserName>
<mrw:Password><%= mrw.password %></mrw:Password> <mrw:Password><%= mrw.password %></mrw:Password>

View File

@ -13,7 +13,7 @@ module.exports = Self => {
required: true required: true
}], }],
returns: { returns: {
type: ['object'], type: 'boolean',
root: true root: true
}, },
http: { http: {
@ -27,9 +27,9 @@ module.exports = Self => {
const mrw = await models.MrwConfig.findOne(); const mrw = await models.MrwConfig.findOne();
const {externalId} = await models.Expedition.findById(expeditionFk); const {externalId} = await models.Expedition.findById(expeditionFk);
const clientType = await models.MrwConfig.getClientType(expeditionFk);
const template = fs.readFileSync(__dirname + '/cancelShipment.ejs', 'utf-8'); const template = fs.readFileSync(__dirname + '/cancelShipment.ejs', 'utf-8');
const renderedXml = ejs.render(template, {mrw, externalId}); const renderedXml = ejs.render(template, {mrw, externalId, clientType});
const response = await axios.post(mrw.url, renderedXml, { const response = await axios.post(mrw.url, renderedXml, {
headers: { headers: {
'Content-Type': 'application/soap+xml; charset=utf-8' 'Content-Type': 'application/soap+xml; charset=utf-8'
@ -39,6 +39,7 @@ module.exports = Self => {
const xmlString = response.data; const xmlString = response.data;
const parser = new DOMParser(); const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
return xmlDoc.getElementsByTagName('Mensaje')[0].textContent; const result = xmlDoc.getElementsByTagName('Mensaje')[0].textContent;
return result.toLowerCase().includes('se ha cancelado correctamente');
}; };
}; };

View File

@ -3,7 +3,7 @@
<soap:Header> <soap:Header>
<mrw:AuthInfo> <mrw:AuthInfo>
<mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia> <mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia>
<mrw:CodigoAbonado><%= expeditionData.clientType %></mrw:CodigoAbonado> <mrw:CodigoAbonado><%= clientType %></mrw:CodigoAbonado>
<mrw:CodigoDepartamento/> <mrw:CodigoDepartamento/>
<mrw:UserName><%= mrw.user %></mrw:UserName> <mrw:UserName><%= mrw.user %></mrw:UserName>
<mrw:Password><%= mrw.password %></mrw:Password> <mrw:Password><%= mrw.password %></mrw:Password>

View File

@ -22,6 +22,7 @@ module.exports = Self => {
Self.createShipment = async expeditionFk => { Self.createShipment = async expeditionFk => {
const models = Self.app.models; const models = Self.app.models;
const mrw = await Self.getConfig(); const mrw = await Self.getConfig();
const clientType = await models.MrwConfig.getClientType(expeditionFk);
const today = Date.vnNew(); const today = Date.vnNew();
const [hours, minutes] = mrw?.expeditionDeadLine ? mrw.expeditionDeadLine.split(':').map(Number) : [0, 0]; const [hours, minutes] = mrw?.expeditionDeadLine ? mrw.expeditionDeadLine.split(':').map(Number) : [0, 0];
@ -52,8 +53,7 @@ module.exports = Self => {
CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference, CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference,
LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth, '0') serviceType, LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth, '0') serviceType,
IF(mw.weekdays, 'S', 'N') weekDays, IF(mw.weekdays, 'S', 'N') weekDays,
oa.description deliveryObservation, oa.description deliveryObservation
LPAD(ms.clientType, mc.clientTypeWidth, '0') clientType
FROM expedition e FROM expedition e
JOIN ticket t ON e.ticketFk = t.id JOIN ticket t ON e.ticketFk = t.id
JOIN agencyMode am ON am.id = t.agencyModeFk JOIN agencyMode am ON am.id = t.agencyModeFk
@ -63,8 +63,7 @@ module.exports = Self => {
JOIN client c ON t.clientFk = c.id JOIN client c ON t.clientFk = c.id
JOIN address a ON t.addressFk = a.id JOIN address a ON t.addressFk = a.id
LEFT JOIN addressObservation oa ON oa.addressFk = a.id LEFT JOIN addressObservation oa ON oa.addressFk = a.id
LEFT JOIN observationType ot ON ot.id = oa.observationTypeFk AND oa.observationTypeFk IN (SELECT id FROM observationType ot WHERE ot.code = 'delivery')
AND ot.code = 'delivery'
JOIN province p ON a.provinceFk = p.id JOIN province p ON a.provinceFk = p.id
JOIN country co ON co.id = p.countryFk JOIN country co ON co.id = p.countryFk
JOIN mrwConfig mc JOIN mrwConfig mc
@ -73,22 +72,19 @@ module.exports = Self => {
const [expeditionData] = await Self.rawSql(query, [expeditionFk]); const [expeditionData] = await Self.rawSql(query, [expeditionFk]);
if (!expeditionData)
throw new UserError(`This expedition is not a MRW shipment`);
if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today.setHours(0, 0, 0, 0)) if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today.setHours(0, 0, 0, 0))
throw new UserError(`This ticket has a shipped date earlier than today`); throw new UserError(`This ticket has a shipped date earlier than today`);
const shipmentResponse = await Self.sendXmlDoc( const shipmentResponse = await Self.sendXmlDoc(
__dirname + `/createShipment.ejs`, __dirname + `/createShipment.ejs`,
{mrw, expeditionData}, {mrw, expeditionData, clientType},
'application/soap+xml' 'application/soap+xml'
); );
const shipmentId = Self.getTextByTag(shipmentResponse, 'NumeroEnvio'); const shipmentId = Self.getTextByTag(shipmentResponse, 'NumeroEnvio');
if (!shipmentId) throw new UserError(Self.getTextByTag(shipmentResponse, 'Mensaje')); if (!shipmentId) throw new UserError(Self.getTextByTag(shipmentResponse, 'Mensaje'));
const file = await models.MrwConfig.getLabel(shipmentId); const file = await models.MrwConfig.getLabel(shipmentId, clientType);
return {shipmentId, file}; return {shipmentId, file};
}; };

View File

@ -2,7 +2,7 @@
<soapenv:Header> <soapenv:Header>
<mrw:AuthInfo> <mrw:AuthInfo>
<mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia> <mrw:CodigoFranquicia><%= mrw.franchiseCode %></mrw:CodigoFranquicia>
<mrw:CodigoAbonado><%= mrw.subscriberCode %></mrw:CodigoAbonado> <mrw:CodigoAbonado><%= clientType %></mrw:CodigoAbonado>
<mrw:CodigoDepartamento/> <mrw:CodigoDepartamento/>
<mrw:UserName><%= mrw.user %></mrw:UserName> <mrw:UserName><%= mrw.user %></mrw:UserName>
<mrw:Password><%= mrw.password %></mrw:Password> <mrw:Password><%= mrw.password %></mrw:Password>

View File

@ -6,7 +6,13 @@ module.exports = Self => {
arg: 'shipmentId', arg: 'shipmentId',
type: 'string', type: 'string',
required: true required: true
}], },
{
arg: 'clientType',
type: 'string',
required: true
},
],
returns: { returns: {
type: 'string', type: 'string',
root: true root: true
@ -17,10 +23,14 @@ module.exports = Self => {
} }
}); });
Self.getLabel = async shipmentId => { Self.getLabel = async(shipmentId, clientType) => {
const mrw = await Self.getConfig(); const mrw = await Self.getConfig();
const getLabelResponse = await Self.sendXmlDoc(__dirname + `/getLabel.ejs`, {mrw, shipmentId}, 'text/xml'); const getLabelResponse = await Self.sendXmlDoc(
__dirname + `/getLabel.ejs`,
{mrw, shipmentId, clientType},
'text/xml'
);
return Self.getTextByTag(getLabelResponse, 'EtiquetaFile'); return Self.getTextByTag(getLabelResponse, 'EtiquetaFile');
}; };

View File

@ -40,15 +40,12 @@ describe('MRWConfig createShipment()', () => {
); );
await models.MrwService.create(
{'agencyModeCodeFk': 'mrw', 'clientType': '000001', 'serviceType': 105, 'kg': 10}
);
await createMrwConfig(); await createMrwConfig();
await models.Application.rawSql(
`INSERT INTO vn.mrwService
SET agencyModeCodeFk = 'mrw',
clientType = 1,
serviceType = 1,
kg = 1`, null
);
await models.Ticket.create(ticket1); await models.Ticket.create(ticket1);
await models.Expedition.create(expedition1); await models.Expedition.create(expedition1);
}); });
@ -82,7 +79,8 @@ describe('MRWConfig createShipment()', () => {
'user': 'user', 'user': 'user',
'password': 'password', 'password': 'password',
'franchiseCode': 'franchiseCode', 'franchiseCode': 'franchiseCode',
'subscriberCode': 'subscriberCode' 'subscriberCode': 'subscriberCode',
'clientTypeWidth': 6
} }
); );
} }
@ -115,10 +113,10 @@ describe('MRWConfig createShipment()', () => {
it('should fail if expeditionFk is not a MrwExpedition', async() => { it('should fail if expeditionFk is not a MrwExpedition', async() => {
let error; let error;
await models.MrwConfig.createShipment(undefined).catch(e => { await models.MrwConfig.createShipment(15).catch(e => {
error = e; error = e;
}).finally(async() => { }).finally(async() => {
expect(error.message).toEqual(`This expedition is not a MRW shipment`); expect(error.message).toEqual(`ClientType not available`);
}); });
}); });

View File

@ -20,7 +20,7 @@ module.exports = Self => {
} }
}); });
Self.renderer = async (expeditionFk) => { Self.renderer = async expeditionFk => {
const models = Self.app.models; const models = Self.app.models;
const viaexpressConfig = await models.ViaexpressConfig.findOne({ const viaexpressConfig = await models.ViaexpressConfig.findOne({
@ -109,7 +109,7 @@ module.exports = Self => {
const ticket = expedition.ticket(); const ticket = expedition.ticket();
const sender = ticket.company().client(); const sender = ticket.company().client();
const shipped = ticket.shipped.toISOString(); const shipped = ticket.shipped.toISOString();
const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk) const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk);
const data = { const data = {
viaexpressConfig, viaexpressConfig,
sender, sender,

View File

@ -192,5 +192,8 @@
}, },
"RouteConfig": { "RouteConfig": {
"dataSource": "vn" "dataSource": "vn"
},
"MrwService": {
"dataSource": "vn"
} }
} }

View File

@ -3,7 +3,7 @@
"base": "VnModel", "base": "VnModel",
"options": { "options": {
"mysql": { "mysql": {
"table": "salix.defaultViewConfig" "table": "salix.defaultViewMultiConfig"
} }
}, },
"properties": { "properties": {

View File

@ -31,5 +31,30 @@ module.exports = Self => {
}); });
return parser.parseFromString(data.data, 'text/xml'); return parser.parseFromString(data.data, 'text/xml');
}; };
Self.getClientType = async function(expeditionFk) {
if (!expeditionFk) throw new UserError(`No expeditionFk defined`);
const {clientTypeWidth} = await Self.getConfig();
const result = await Self.app.models.Expedition.findById(expeditionFk,
{include: [{
relation: 'ticket',
scope: {
include: {
relation: 'agencyMode',
scope: {
include: {
relation: 'mrwService',
}
}
}
}
}]}
);
const clientType = result?.ticket()?.agencyMode()?.mrwService()?.clientType;
if (!clientType || !clientTypeWidth) throw new UserError(`ClientType not available`);
return clientType.toString().padStart(clientTypeWidth, '0');
};
}; };

View File

@ -45,6 +45,9 @@
}, },
"notified":{ "notified":{
"type": "date" "type": "date"
},
"clientTypeWidth": {
"type": "number"
} }
} }
} }

View File

@ -0,0 +1,33 @@
{
"name": "MrwService",
"base": "VnModel",
"options": {
"mysql": {
"table": "mrwService"
}
},
"properties": {
"agencyModeCodeFk": {
"id": true,
"type": "string",
"required": true
},
"clientType": {
"type": "number",
"required": true
},
"serviceType": {
"type": "number"
},
"kg": {
"type": "number"
}
},
"relations": {
"agency": {
"type": "hasOne",
"model": "AgencyMode",
"foreignKey": "code"
}
}
}

View File

@ -3,7 +3,7 @@
"base": "VnModel", "base": "VnModel",
"options": { "options": {
"mysql": { "mysql": {
"table": "userConfig" "table": "userMultiConfig"
} }
}, },
"properties": { "properties": {

View File

@ -10,9 +10,6 @@ SET foreign_key_checks = 0;
INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled) INSERT INTO util.config (id, environment, mockTime, mockUtcTime, mockEnabled)
VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE); VALUES (1, 'local', '2001-01-01 12:00:00', '2001-01-01 11:00:00', TRUE);
INSERT INTO util.binlogQueue (code,logName, `position`)
VALUES ('mylogger', 'bin.000001', 4);
/* #5483 /* #5483
INSERT INTO vn.entryConfig (defaultEntry, mailToNotify, inventorySupplierFk, maxLockTime, defaultSupplierFk) INSERT INTO vn.entryConfig (defaultEntry, mailToNotify, inventorySupplierFk, maxLockTime, defaultSupplierFk)
VALUES(1, NULL, 1, 300, 1); VALUES(1, NULL, 1, 300, 1);
@ -314,5 +311,4 @@ INSERT INTO mysql.roles_mapping (`User`, `Host`, `Role`, `Admin_option`)
SELECT SUBSTR(`User`, @prefixLen + 1), `Host`, `Role`, `Admin_option` SELECT SUBSTR(`User`, @prefixLen + 1), `Host`, `Role`, `Admin_option`
FROM mysql.roles_mapping FROM mysql.roles_mapping
WHERE `User` LIKE @prefixedLike AND `Host` = @genRoleHost; WHERE `User` LIKE @prefixedLike AND `Host` = @genRoleHost;
FLUSH PRIVILEGES; FLUSH PRIVILEGES;

View File

@ -121,7 +121,7 @@ INSERT INTO hedera.orderConfig (`id`, `employeeFk`, `defaultAgencyFk`, `guestMet
INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `password`,`role`,`active`,`email`,`lang`, `image`) INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `password`,`role`,`active`,`email`,`lang`, `image`)
VALUES VALUES
(1101, 'brucewayne', 'Bruce Wayne', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'BruceWayne@mydomain.com', 'es','1101'), (1101, 'brucewayne', 'Bruce Wayne', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'BruceWayne@mydomain.com', 'es','1101'),
(1102, 'petterparker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'PetterParker@mydomain.com', 'en','1102'), (1102, 'petterparker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 131, 1, 'PetterParker@mydomain.com', 'en','1102'),
(1103, 'clarkkent', 'Clark Kent', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'ClarkKent@mydomain.com', 'fr','1103'), (1103, 'clarkkent', 'Clark Kent', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'ClarkKent@mydomain.com', 'fr','1103'),
(1104, 'tonystark', 'Tony Stark', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'TonyStark@mydomain.com', 'es','1104'), (1104, 'tonystark', 'Tony Stark', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'TonyStark@mydomain.com', 'es','1104'),
(1105, 'maxeisenhardt', 'Max Eisenhardt', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt','1105'), (1105, 'maxeisenhardt', 'Max Eisenhardt', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt','1105'),
@ -996,7 +996,7 @@ INSERT INTO `vn`.`priceFixed`(`id`, `itemFk`, `rate0`, `rate1`, `rate2`, `rate3`
INSERT INTO `vn`.`itemMinimumQuantity`(`itemFk`, `quantity`, `started`, `ended`, `warehouseFk`) INSERT INTO `vn`.`itemMinimumQuantity`(`itemFk`, `quantity`, `started`, `ended`, `warehouseFk`)
VALUES VALUES
(1, 5, util.VN_CURDATE() - INTERVAL 2 MONTH, util.VN_CURDATE() + INTERVAL 1 MONTH, 1), (1, 5, util.VN_CURDATE() - INTERVAL 2 MONTH, util.VN_CURDATE() + INTERVAL 1 MONTH, 1),
(2, 10, util.VN_CURDATE() - INTERVAL 2 DAY, NULL, 2), (2, 10, util.VN_CURDATE() - INTERVAL 2 DAY, util.VN_CURDATE() - INTERVAL 1 DAY, 2),
(3, 15, util.VN_CURDATE() + INTERVAL 3 DAY, util.VN_CURDATE() + INTERVAL 2 WEEK, 3), (3, 15, util.VN_CURDATE() + INTERVAL 3 DAY, util.VN_CURDATE() + INTERVAL 2 WEEK, 3),
(2, 10, util.VN_CURDATE() + INTERVAL 2 MONTH, NULL, 5), (2, 10, util.VN_CURDATE() + INTERVAL 2 MONTH, NULL, 5),
(4, 8, util.VN_CURDATE() - INTERVAL 3 MONTH, NULL, NULL); (4, 8, util.VN_CURDATE() - INTERVAL 3 MONTH, NULL, NULL);
@ -1500,7 +1500,8 @@ INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseO
(5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5), (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5),
(6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6), (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6),
(7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7), (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7),
(8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10); (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10),
(10, DATE_ADD(util.VN_CURDATE(), INTERVAL + 5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10);
INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `isRaid`, `evaNotes`) INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `isRaid`, `evaNotes`)
VALUES VALUES
@ -1511,25 +1512,27 @@ INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed
(5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 0, 'observation five'), (5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 0, 'observation five'),
(6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 0, 'observation six'), (6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 0, 'observation six'),
(7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 0, 'observation seven'), (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 0, 'observation seven'),
(8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, 1, ''); (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, 1, ''),
(9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, 1, ''),
(10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, 1, '');
INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleWaste`, `rate`) INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleQuantity`, `saleInternalWaste`, `saleExternalWaste`)
VALUES VALUES
('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Carnation', 1, 1, '1062', '51', '4.8'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 1, 1, '1062', '51', '56.20', '56.20'),
('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Carnation Colombia', 2, 1, '35074', '687', '2.0'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '35074', '687', '53.12', '89.69'),
('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Carnation Mini', 3, 1, '1777', '13', '0.7'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 3, 1, '1777', '13', '12.02', '53.12'),
('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Carnation Short', 4, 1, '3182', '59', '0.6'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 4, 1, '3182', '59', '51', '56.20'),
('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Crisantemo', 5, 1, '1747', '13', '0.7'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 5, 1, '1747', '13', '53.12', '53.12'),
('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Lilium Oriental', 6, 1, '7182', '59', '0.6'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 6, 1, '7182', '59', '51', '53.12'),
('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Alstroemeria', 7, 1, '1777', '13', '0.7'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 7, 1, '1777', '13', '89.69', '89.69'),
('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Cymbidium', 1, 1, '4181', '59', '0.6'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 8, 1, '4181', '59', '53.12', '53.12'),
('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Cymbidium', 2, 1, '7268', '59', '0.6'), ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 9, 1, '7268', '59', '12.02', '56.20'),
('DavidCharlesHaller', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Containers', 2, 1, '-74', '0', '0.0'), ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '-74', '0', '51', '89.69'),
('DavidCharlesHaller', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Packagings', 3, 1, '-7', '0', '0.0'), ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 3, 1, '-7', '0', '12.02', '53.12'),
('DavidCharlesHaller', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Freight', 4, 1, '1100', '0', '0.0'), ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 4, 1, '1100', '0', '51', '56.20'),
('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Funeral Accessories', 5, 1, '848', '-187', '-22.1'), ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 5, 1, '848', '-187', '12.02', '89.69'),
('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Miscellaneous Accessories', 6, 1, '186', '0', '0.0'), ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 6, 1, '186', '0', '51', '53.12'),
('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Adhesives', 7, 1, '277', '0', '0.0'); ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 7, 1, '277', '0', '53.12', '56.20');
INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packagingFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packagingFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`)
VALUES VALUES
@ -1965,7 +1968,7 @@ INSERT INTO `vn`.`orderTicket`(`orderFk`, `ticketFk`)
(21, 21), (21, 21),
(22, 22); (22, 22);
INSERT INTO `vn`.`userConfig` (`userFk`, `warehouseFk`, `companyFk`) INSERT INTO `vn`.`userMultiConfig` (`userFk`, `warehouseFk`, `companyFk`)
VALUES VALUES
(1, 1, 69), (1, 1, 69),
(5, 1, 442), (5, 1, 442),

View File

@ -1,31 +1,50 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`() CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`()
BEGIN BEGIN
DECLARE vWeek INT; DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY;
DECLARE vYear INT; DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY;
SELECT week, year CALL cache.last_buy_refresh(FALSE);
INTO vWeek, vYear
FROM vn.time
WHERE dated = util.VN_CURDATE();
REPLACE bs.waste REPLACE bs.waste
SELECT *, 100 * mermas / total as porcentaje SELECT YEAR(t.shipped),
FROM ( WEEK(t.shipped, 4),
SELECT buyer, it.workerFk,
year, it.id,
week, s.itemFk,
family, SUM(s.quantity),
itemFk, SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) `value`,
itemTypeFk, SUM (
floor(sum(value)) as total, IF(
floor(sum(IF(typeFk = 'loses', value, 0))) as mermas aw.`type` = 'internal',
FROM vn.saleValue (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
where year = vYear and week = vWeek 0
)
GROUP BY family, itemFk ) internalWaste,
SUM (
) sub IF(
ORDER BY mermas DESC; aw.`type` = 'external',
(b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity,
IF(c.code = 'manaClaim',
sc.value * s.quantity,
0
)
)
) externalWaste
FROM vn.sale s
JOIN vn.item i ON i.id = s.itemFk
JOIN vn.itemType it ON it.id = i.typeFk
JOIN vn.ticket t ON t.id = s.ticketFk
JOIN vn.address a FORCE INDEX (PRIMARY) ON a.id = t.addressFk
LEFT JOIN vn.addressWaste aw ON aw.addressFk = a.id
JOIN vn.warehouse w ON w.id = t.warehouseFk
JOIN cache.last_buy lb ON lb.item_id = i.id
AND lb.warehouse_id = w.id
JOIN vn.buy b ON b.id = lb.buy_id
LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id
LEFT JOIN vn.component c ON c.id = sc.componentFk
WHERE t.shipped BETWEEN vDateFrom AND vDateTo
AND w.isManaged
GROUP BY it.id, i.id;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -56,13 +56,21 @@ BEGIN
CALL util.throw ('ORDER_ROW_UNAVAILABLE'); CALL util.throw ('ORDER_ROW_UNAVAILABLE');
END IF; END IF;
SELECT quantity INTO vMinQuantity WITH itemMinQuantityPriority AS (
SELECT quantity,
ROW_NUMBER() OVER (
PARTITION BY itemFk
ORDER BY warehouseFk IS NULL
) priority
FROM vn.itemMinimumQuantity FROM vn.itemMinimumQuantity
WHERE itemFk = vItem WHERE itemFk = vItem
AND `started` <= vShipment AND `started` <= vShipment
AND (`ended` >= vShipment OR `ended` IS NULL) AND (`ended` >= vShipment OR `ended` IS NULL)
AND (warehouseFk = vWarehouse OR warehouseFk IS NULL) AND (warehouseFk = vWarehouse OR warehouseFk IS NULL)
LIMIT 1; )
SELECT quantity INTO vMinQuantity
FROM itemMinQuantityPriority
WHERE priority = 1;
IF vAmount < LEAST(IFNULL(vMinQuantity, 0), vAvailable) THEN IF vAmount < LEAST(IFNULL(vMinQuantity, 0), vAvailable) THEN
CALL util.throw ('quantityLessThanMin'); CALL util.throw ('quantityLessThanMin');

View File

@ -10,5 +10,5 @@ AS SELECT `q`.`name` AS `name`,
`c`.`ringInUse` AS `ringinuse` `c`.`ringInUse` AS `ringinuse`
FROM ( FROM (
`pbx`.`queue` `q` `pbx`.`queue` `q`
JOIN `pbx`.`queueConfig` `c` ON(`q`.`config` = `c`.`id`) JOIN `pbx`.`queueMultiConfig` `c` ON(`q`.`config` = `c`.`id`)
) )

View File

@ -0,0 +1,27 @@
DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_isProblemCalcNeeded`(
vSelf INT
)
RETURNS BOOL
DETERMINISTIC
BEGIN
/**
* Check if the ticket requires to update column vn.ticket.problem
*
* @param vSelf Id ticket
* @return BOOL
*/
DECLARE vIsProblemCalcNeeded BOOL;
SELECT COUNT(*) INTO vIsProblemCalcNeeded
FROM ticket t
JOIN client c ON c.id = t.clientFk
JOIN agencyMode am ON am.id = t.agencyModeFk
JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE t.id = vSelf
AND dm.code IN ('AGENCY','DELIVERY','PICKUP')
AND c.typeFk = 'normal';
RETURN vIsProblemCalcNeeded;
END$$
DELIMITER ;

View File

@ -1,5 +1,8 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`(vWarehouseFk SMALLINT, vDated DATE) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`(
vWarehouseFk SMALLINT,
vDated DATE
)
BEGIN BEGIN
/** /**
* Calcula las últimas compras realizadas hasta una fecha * Calcula las últimas compras realizadas hasta una fecha
@ -19,6 +22,7 @@ BEGIN
FROM cache.last_buy FROM cache.last_buy
WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL;
IF vDated >= util.VN_CURDATE() THEN
CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated); CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated);
REPLACE INTO tmp.buyUltimate REPLACE INTO tmp.buyUltimate
@ -34,6 +38,6 @@ BEGIN
WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL)
AND landed > vDated AND landed > vDated
ORDER BY isIgnored = FALSE DESC; ORDER BY isIgnored = FALSE DESC;
END IF;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -1,5 +1,9 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInterval`(vWarehouseFk SMALLINT, vStarted DATE, vEnded DATE) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInterval`(
vWarehouseFk SMALLINT,
vStarted DATE,
vEnded DATE
)
BEGIN BEGIN
/** /**
* Calcula las últimas compras realizadas * Calcula las últimas compras realizadas
@ -21,12 +25,13 @@ BEGIN
-- Item -- Item
DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval; DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval;
CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval
(PRIMARY KEY (itemFk, warehouseFk), INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk)) (PRIMARY KEY (itemFk, warehouseFk),
INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk))
ENGINE = MEMORY ENGINE = MEMORY
SELECT itemFk, SELECT itemFk,
warehouseFk, warehouseFk,
buyFk, buyFk,
MAX(landed) landed, landed,
isIgnored isIgnored
FROM (SELECT b.itemFk, FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk, t.warehouseInFk warehouseFk,
@ -45,8 +50,12 @@ BEGIN
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT SELECT itemFk,
b.itemFk, warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk, t.warehouseInFk warehouseFk,
b.id buyFk, b.id buyFk,
t.landed, t.landed,
@ -58,11 +67,17 @@ BEGIN
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.price2 > 0 AND b.price2 > 0
AND NOT b.isIgnored AND NOT b.isIgnored
GROUP BY itemFk, warehouseInFk; ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT SELECT itemFk,
b.itemFk, warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk, t.warehouseInFk warehouseFk,
b.id buyFk, b.id buyFk,
t.landed, t.landed,
@ -73,14 +88,16 @@ BEGIN
WHERE t.landed BETWEEN vStarted AND vEnded WHERE t.landed BETWEEN vStarted AND vEnded
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.quantity = 0 AND b.quantity = 0
GROUP BY itemFk, warehouseInFk; ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
-- ItemOriginal -- ItemOriginal
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT itemFk, SELECT itemFk,
warehouseFk, warehouseFk,
buyFk, buyFk,
MAX(landed) landed, landed,
isIgnored isIgnored
FROM (SELECT b.itemFk, FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk, t.warehouseInFk warehouseFk,
@ -99,11 +116,14 @@ BEGIN
AND itemOriginalFk AND itemOriginalFk
ORDER BY t.landed DESC, b.id DESC ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub LIMIT 10000000000000000000) sub
GROUP BY itemOriginalFk, warehouseFk; GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT SELECT itemFk,
b.itemFk, warehouseFk,
buyFk,
landed,
isIgnored
FROM (SELECT b.itemFk,
t.warehouseInFk warehouseFk, t.warehouseInFk warehouseFk,
b.id buyFk, b.id buyFk,
t.landed, t.landed,
@ -116,11 +136,18 @@ BEGIN
AND b.price2 > 0 AND b.price2 > 0
AND NOT b.isIgnored AND NOT b.isIgnored
AND itemOriginalFk AND itemOriginalFk
GROUP BY itemOriginalFk, warehouseInFk; ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored)
SELECT SELECT itemFk,
b.itemFk, warehouseFk,
buyFk,
landed,
isIgnored
FROM
(SELECT b.itemFk,
t.warehouseInFk warehouseFk, t.warehouseInFk warehouseFk,
b.id buyFk, b.id buyFk,
t.landed, t.landed,
@ -132,6 +159,8 @@ BEGIN
AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk)
AND b.quantity = 0 AND b.quantity = 0
AND itemOriginalFk AND itemOriginalFk
GROUP BY itemOriginalFk, warehouseInFk; ORDER BY t.landed DESC, b.id DESC
LIMIT 10000000000000000000) sub
GROUP BY itemFk, warehouseFk;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -180,15 +180,24 @@ BEGIN
GROUP BY itemFk GROUP BY itemFk
) bl ON bl.itemFk = tl.itemFk ) bl ON bl.itemFk = tl.itemFk
LEFT JOIN ( LEFT JOIN (
SELECT itemFk, quantity, warehouseFk WITH itemMinQuantityPriority AS (
FROM itemMinimumQuantity SELECT itemFk,
quantity,
ROW_NUMBER() OVER (
PARTITION BY itemFk
ORDER BY warehouseFk IS NULL
) priority
FROM vn.itemMinimumQuantity
WHERE `started` <= vShipped WHERE `started` <= vShipped
AND (`ended` >= vShipped OR `ended` IS NULL) AND (`ended` >= vShipped OR `ended` IS NULL)
GROUP BY itemFk, warehouseFk AND (warehouseFk = vWarehouseFk OR warehouseFk IS NULL)
ORDER BY warehouseFk DESC )
SELECT itemFk, quantity
FROM itemMinQuantityPriority
WHERE priority = 1
) mq ON mq.itemFk = tl.itemFk ) mq ON mq.itemFk = tl.itemFk
AND (mq.warehouseFk = tl.warehouseFk OR mq.warehouseFk IS NULL) WHERE tl.zoneFk = vZoneFk
WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk AND tl.warehouseFk = vWarehouseFk
GROUP BY tl.itemFk GROUP BY tl.itemFk
ON DUPLICATE KEY UPDATE available = available + VALUES(available); ON DUPLICATE KEY UPDATE available = available + VALUES(available);
END LOOP; END LOOP;

View File

@ -34,20 +34,25 @@ BEGIN
DECLARE vIsTaxDataChecked TINYINT(1); DECLARE vIsTaxDataChecked TINYINT(1);
DECLARE vHasCoreVnl BOOLEAN; DECLARE vHasCoreVnl BOOLEAN;
DECLARE vMandateTypeFk INT; DECLARE vMandateTypeFk INT;
DECLARE vHasDailyInvoice BOOLEAN;
SELECT defaultPayMethodFk, SELECT cc.defaultPayMethodFk,
defaultDueDay, cc.defaultDueDay,
defaultCredit, cc.defaultCredit,
defaultIsTaxDataChecked, cc.defaultIsTaxDataChecked,
defaultHasCoreVnl, cc.defaultHasCoreVnl,
defaultMandateTypeFk cc.defaultMandateTypeFk,
c.hasDailyInvoice
INTO vPayMethodFk, INTO vPayMethodFk,
vDueDay, vDueDay,
vDefaultCredit, vDefaultCredit,
vIsTaxDataChecked, vIsTaxDataChecked,
vHasCoreVnl, vHasCoreVnl,
vMandateTypeFk vMandateTypeFk,
FROM clientConfig; vHasDailyInvoice
FROM clientConfig cc
LEFT JOIN province p ON p.id = vProvinceFk
LEFT JOIN country c ON c.id = p.countryFk;
INSERT INTO `client` INSERT INTO `client`
SET id = vUserFk, SET id = vUserFk,
@ -65,7 +70,8 @@ BEGIN
credit = vDefaultCredit, credit = vDefaultCredit,
isTaxDataChecked = vIsTaxDataChecked, isTaxDataChecked = vIsTaxDataChecked,
hasCoreVnl = vHasCoreVnl, hasCoreVnl = vHasCoreVnl,
isEqualizated = FALSE isEqualizated = FALSE,
hasDailyInvoice = vHasDailyInvoice
ON duplicate KEY UPDATE ON duplicate KEY UPDATE
payMethodFk = vPayMethodFk, payMethodFk = vPayMethodFk,
dueDay = vDueDay, dueDay = vDueDay,

View File

@ -7,7 +7,7 @@ DECLARE vCompanyFk INT;
SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk)
INTO vCompanyFk INTO vCompanyFk
FROM vn.routeConfig rc FROM vn.routeConfig rc
LEFT JOIN userConfig uc ON uc.userFk = workerFk; LEFT JOIN userMultiConfig uc ON uc.userFk = workerFk;
SELECT SELECT

View File

@ -216,7 +216,7 @@ BEGIN
i.transactionTypeSageFk, i.transactionTypeSageFk,
@vTaxCodeGeneral := i.taxClassCodeFk @vTaxCodeGeneral := i.taxClassCodeFk
FROM tmp.ticketServiceTax tst FROM tmp.ticketServiceTax tst
JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code JOIN invoiceOutTaxMultiConfig i ON i.taxClassCodeFk = tst.code
WHERE i.isService WHERE i.isService
HAVING taxableBase HAVING taxableBase
) sub; ) sub;
@ -229,7 +229,7 @@ BEGIN
i.taxTypeSageFk , i.taxTypeSageFk ,
i.transactionTypeSageFk i.transactionTypeSageFk
FROM tmp.ticketTax tt FROM tmp.ticketTax tt
JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code JOIN invoiceOutTaxMultiConfig i ON i.taxClassCodeFk = tt.code
WHERE !i.isService WHERE !i.isService
GROUP BY tt.pgcFk GROUP BY tt.pgcFk
HAVING taxableBase HAVING taxableBase

View File

@ -16,6 +16,8 @@ proc: BEGIN
DECLARE vReservedQuantity INT; DECLARE vReservedQuantity INT;
DECLARE vOutStanding INT; DECLARE vOutStanding INT;
DECLARE vUserFk INT; DECLARE vUserFk INT;
DECLARE vTotalReservedQuantity INT;
DECLARE vSaleQuantity INT;
DECLARE vItemShelvingAvailable CURSOR FOR DECLARE vItemShelvingAvailable CURSOR FOR
SELECT ish.id itemShelvingFk, SELECT ish.id itemShelvingFk,
@ -43,8 +45,8 @@ proc: BEGIN
RESIGNAL; RESIGNAL;
END; END;
SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)) SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)), s.quantity
INTO vLastPickingOrder, vOutStanding INTO vLastPickingOrder, vOutStanding, vSaleQuantity
FROM sale s FROM sale s
LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id
LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk
@ -64,6 +66,16 @@ proc: BEGIN
FETCH vItemShelvingAvailable INTO vItemShelvingFk, vAvailable; FETCH vItemShelvingAvailable INTO vItemShelvingFk, vAvailable;
IF vOutStanding <= 0 OR vDone THEN IF vOutStanding <= 0 OR vDone THEN
SELECT SUM(IFNULL(quantity, 0))
INTO vTotalReservedQuantity
FROM itemShelvingSale
WHERE saleFk = vSaleFk;
IF vTotalReservedQuantity <> vSaleQuantity THEN
UPDATE sale
SET quantity = vTotalReservedQuantity
WHERE id = vSaleFk;
END IF;
LEAVE l; LEAVE l;
END IF; END IF;

View File

@ -21,6 +21,7 @@ BEGIN
DECLARE vRemainingQuantity INT; DECLARE vRemainingQuantity INT;
DECLARE vItemFk INT; DECLARE vItemFk INT;
DECLARE vTotalQuantity INT; DECLARE vTotalQuantity INT;
DECLARE vStateCode VARCHAR(45);
DECLARE EXIT HANDLER FOR SQLEXCEPTION DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN BEGIN
@ -32,10 +33,19 @@ BEGIN
CALL util.throw('Reservation completed'); CALL util.throw('Reservation completed');
END IF; END IF;
SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk, SUM(IFNULL(iss.quantity,0)) SELECT s.itemFk,
INTO vItemFk, vSaleFk, vItemShelvingFk, vReservedQuantity iss.saleFk,
iss.itemShelvingFk,
SUM(IFNULL(iss.quantity,0)),
IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED')
INTO vItemFk,
vSaleFk,
vItemShelvingFk,
vReservedQuantity,
vStateCode
FROM itemShelvingSale iss FROM itemShelvingSale iss
JOIN sale s ON s.id = iss.saleFk JOIN sale s ON s.id = iss.saleFk
LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk
WHERE iss.id = vItemShelvingSaleFk WHERE iss.id = vItemShelvingSaleFk
AND NOT iss.isPicked; AND NOT iss.isPicked;
@ -74,7 +84,7 @@ BEGIN
vTotalQuantity, vTotalQuantity,
`account`.`myUser_getId`(), `account`.`myUser_getId`(),
NULL, NULL,
'PREPARED', vStateCode,
TRUE); TRUE);
UPDATE sale s UPDATE sale s

View File

@ -10,19 +10,20 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_comparative`(
) )
proc: BEGIN proc: BEGIN
/** /**
* Genera una tabla de comparativa de artículos por itemType/comprador/fecha. * Generates a comparison table of items by itemType/buyer/date.
* Los datos se calculan en función de los parámetros proporcionados. * The data is calculated based on the provided parameters.
* *
* @param vDate La fecha para la cual se generará la comparativa. * @param vDate The date for which the comparison will be generated.
* @param vDayRange El rango de días a considerar para la comparativa. * @param vDayRange The range of days to consider for the comparison.
* @param vWarehouseFk El identificador del almacén para filtrar los artículos. * @param vWarehouseFk The warehouse identifier to filter the items.
* @param vAvailableSince La fecha de disponibilidad desde la cual se consideran los artículos disponibles. * @param vAvailableSince The availability date from which the items are considered available.
* @param vBuyerFk El identificador del comprador para filtrar los artículos. * @param vBuyerFk The buyer identifier to filter the items.
* @param vIsFloramondo Indica si se deben incluir solo los artículos de Floramondo (opcional). * @param vIsFloramondo Indicates whether only Floramondo items should be included (optional).
* @param vCountryFk El identificador del país. * @param vCountryFk The country identifier.
* @param tmp.comparativeFilterType(filterFk INT ,itemTypeFk INT) * @param tmp.comparativeFilterType(filterFk INT, itemTypeFk INT)
* @return tmp.comparative * @return tmp.comparative
*/ */
DECLARE vDayRangeStart DATE; DECLARE vDayRangeStart DATE;
DECLARE vDayRangeEnd DATE; DECLARE vDayRangeEnd DATE;
DECLARE w1, w2, w3, w4, w5, w6, w7 INT; DECLARE w1, w2, w3, w4, w5, w6, w7 INT;

View File

@ -42,7 +42,7 @@ BEGIN
END IF; END IF;
SELECT warehouseFk INTO vWarehouseFk SELECT warehouseFk INTO vWarehouseFk
FROM userConfig FROM userMultiConfig
WHERE userFk = account.myUser_getId(); WHERE userFk = account.myUser_getId();
IF NOT vWarehouseFk OR vWarehouseFk IS NULL THEN IF NOT vWarehouseFk OR vWarehouseFk IS NULL THEN

View File

@ -46,12 +46,18 @@ BEGIN
i.tag8 = JSON_VALUE(vTags, '$.8'), i.tag8 = JSON_VALUE(vTags, '$.8'),
i.tag9 = JSON_VALUE(vTags, '$.9'), i.tag9 = JSON_VALUE(vTags, '$.9'),
i.tag10 = JSON_VALUE(vTags, '$.10'), i.tag10 = JSON_VALUE(vTags, '$.10'),
i.tag11 = JSON_VALUE(vTags, '$.11'),
i.tag12 = JSON_VALUE(vTags, '$.12'),
i.tag13 = JSON_VALUE(vTags, '$.13'),
i.value5 = JSON_VALUE(vValues, '$.5'), i.value5 = JSON_VALUE(vValues, '$.5'),
i.value6 = JSON_VALUE(vValues, '$.6'), i.value6 = JSON_VALUE(vValues, '$.6'),
i.value7 = JSON_VALUE(vValues, '$.7'), i.value7 = JSON_VALUE(vValues, '$.7'),
i.value8 = JSON_VALUE(vValues, '$.8'), i.value8 = JSON_VALUE(vValues, '$.8'),
i.value9 = JSON_VALUE(vValues, '$.9'), i.value9 = JSON_VALUE(vValues, '$.9'),
i.value10 = JSON_VALUE(vValues, '$.10'), i.value10 = JSON_VALUE(vValues, '$.10'),
i.value11 = JSON_VALUE(vValues, '$.11'),
i.value12 = JSON_VALUE(vValues, '$.12'),
i.value13 = JSON_VALUE(vValues, '$.13'),
i.producerFk = p.id, i.producerFk = p.id,
i.inkFk = k.id, i.inkFk = k.id,
i.originFk = IFNULL(o.id, i.originFk) i.originFk = IFNULL(o.id, i.originFk)

View File

@ -1,14 +1,18 @@
DELIMITER $$ DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_updateM3`(vRoute INT) CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`route_updateM3`(
vSelf INT
)
BEGIN BEGIN
/**
* Actualiza el volumen de la ruta.
*
* @param vSelf Id ruta
*/
DECLARE vVolume DECIMAL(10,1)
DEFAULT (SELECT SUM(volume) FROM saleVolume WHERE routeFk = vSelf);
UPDATE vn.route r UPDATE `route`
LEFT JOIN ( SET m3 = IFNULL(vVolume, 0)
SELECT routeFk, SUM(volume) AS m3 WHERE id = vSelf;
FROM saleVolume
WHERE routeFk = vRoute
) v ON v.routeFk = r.id
SET r.m3 = IFNULL(v.m3,0)
WHERE r.id =vRoute;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -19,8 +19,7 @@ BEGIN
CREATE OR REPLACE TEMPORARY TABLE tmp.sale CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(saleFk INT PRIMARY KEY) (saleFk INT PRIMARY KEY)
SELECT SELECT s.ticketFk,
s.ticketFk,
s.id saleFk, s.id saleFk,
s.itemFk, s.itemFk,
s.concept, s.concept,
@ -29,7 +28,7 @@ BEGIN
pb.routeFk, pb.routeFk,
FLOOR(s.quantity / IF(i.isBoxPickingMode, ish.packing, i.packingOut)) stickers, FLOOR(s.quantity / IF(i.isBoxPickingMode, ish.packing, i.packingOut)) stickers,
IF(i.isBoxPickingMode, ish.packing, i.packingOut) packing, IF(i.isBoxPickingMode, ish.packing, i.packingOut) packing,
b.packagingFk IF(pa.isPackageReturnable, pc.defaultBigPackageFk, b.packagingFk) packagingFk
FROM sale s FROM sale s
JOIN item i ON i.id = s.itemFk JOIN item i ON i.id = s.itemFk
JOIN itemShelving ish ON ish.itemFk = s.itemFk JOIN itemShelving ish ON ish.itemFk = s.itemFk
@ -52,6 +51,8 @@ BEGIN
LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk
LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk
LEFT JOIN buy b ON b.id = lb.buy_id LEFT JOIN buy b ON b.id = lb.buy_id
LEFT JOIN packaging pa ON pa.id = b.packagingFk
JOIN packagingConfig pc
WHERE IF(i.isBoxPickingMode, ish.packing, i.packingOut) WHERE IF(i.isBoxPickingMode, ish.packing, i.packingOut)
<= LEAST(s.quantity, ish.visible - IFNULL(tISS.reserve,0)) <= LEAST(s.quantity, ish.visible - IFNULL(tISS.reserve,0))
AND NOT pb.problem AND NOT pb.problem

View File

@ -7,7 +7,7 @@ BEGIN
* Update column sale.problem with a problem code * Update column sale.problem with a problem code
* *
* @param vProblemCode Code to set or unset * @param vProblemCode Code to set or unset
* @table tmp.sale(saleFk, hasProblem) * @table tmp.sale(saleFk, hasProblem, isProblemCalcNeeded)
*/ */
DECLARE vSaleFk INT; DECLARE vSaleFk INT;
DECLARE vHasProblem INT; DECLARE vHasProblem INT;

View File

@ -10,9 +10,13 @@ BEGIN
* @param vSelf Id del sale * @param vSelf Id del sale
*/ */
CREATE OR REPLACE TEMPORARY TABLE tmp.sale CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(INDEX(saleFk)) (INDEX(saleFk, isProblemCalcNeeded))
ENGINE = MEMORY ENGINE = MEMORY
SELECT vSelf saleFk, sale_hasComponentLack(vSelf) hasProblem; SELECT vSelf saleFk,
sale_hasComponentLack(vSelf) hasProblem,
ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded
FROM sale
WHERE id = vSelf;
CALL sale_setProblem('hasComponentLack'); CALL sale_setProblem('hasComponentLack');

View File

@ -10,11 +10,13 @@ BEGIN
* @param vComponentFk Id component * @param vComponentFk Id component
*/ */
CREATE OR REPLACE TEMPORARY TABLE tmp.sale CREATE OR REPLACE TEMPORARY TABLE tmp.sale
(INDEX(saleFk)) (INDEX(saleFk, isProblemCalcNeeded))
ENGINE = MEMORY ENGINE = MEMORY
SELECT saleFk, sale_hasComponentLack(saleFk)hasProblem SELECT saleFk,
sale_hasComponentLack(saleFk) hasProblem,
ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded
FROM ( FROM (
SELECT s.id saleFk SELECT s.id saleFk, s.ticketFk
FROM ticket t FROM ticket t
JOIN sale s ON s.ticketFk = t.id JOIN sale s ON s.ticketFk = t.id
LEFT JOIN saleComponent sc ON sc.saleFk = s.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id

View File

@ -11,9 +11,10 @@ BEGIN
DECLARE vWarehouseFk INT; DECLARE vWarehouseFk INT;
DECLARE vShipped DATE; DECLARE vShipped DATE;
DECLARE vQuantity INT; DECLARE vQuantity INT;
DECLARE vIsProblemCalcNeeded BOOL;
SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity, ticket_isProblemCalcNeeded(t.id)
INTO vItemFk, vWarehouseFk, vShipped, vQuantity INTO vItemFk, vWarehouseFk, vShipped, vQuantity, vIsProblemCalcNeeded
FROM sale s FROM sale s
JOIN ticket t ON t.id = s.ticketFk JOIN ticket t ON t.id = s.ticketFk
WHERE s.id = vSelf; WHERE s.id = vSelf;
@ -21,7 +22,9 @@ BEGIN
CALL buyUltimate(vWarehouseFk, vShipped); CALL buyUltimate(vWarehouseFk, vShipped);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale CREATE OR REPLACE TEMPORARY TABLE tmp.sale
SELECT vSelf saleFk, MOD(vQuantity, b.`grouping`) hasProblem SELECT vSelf saleFk,
MOD(vQuantity, b.`grouping`) hasProblem,
vIsProblemCalcNeeded isProblemCalcNeeded
FROM tmp.buyUltimate bu FROM tmp.buyUltimate bu
JOIN buy b ON b.id = bu.buyFk JOIN buy b ON b.id = bu.buyFk
WHERE bu.itemFk = vItemFk; WHERE bu.itemFk = vItemFk;

View File

@ -64,8 +64,12 @@ BEGIN
(SELECT vCurTicketFk, p.id, COUNT(*) (SELECT vCurTicketFk, p.id, COUNT(*)
FROM expedition e FROM expedition e
JOIN packaging p ON p.id = e.packagingFk JOIN packaging p ON p.id = e.packagingFk
JOIN ticket t ON t.id = e.ticketFk
LEFT JOIN agencyMode am ON am.id = t.agencyModeFk
LEFT JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk
WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable
AND vWithPackage AND vWithPackage
AND NOT dm.`code`= 'PICKUP'
GROUP BY p.itemFk); GROUP BY p.itemFk);
-- No retornables o no catalogados -- No retornables o no catalogados

View File

@ -4,10 +4,11 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setProblem`(
) )
BEGIN BEGIN
/** /**
* Update column ticket.problem with a problem code * Update column ticket.problem with a problem code and SET NULL when
* the problem is not requiered
* *
* @param vProblemCode Code to set or unset * @param vProblemCode Code to set or unset
* @table tmp.ticket(ticketFk, hasProblem) * @table tmp.ticket(ticketFk, hasProblem, isProblemCalcNeeded)
*/ */
DECLARE vTicketFk INT; DECLARE vTicketFk INT;
DECLARE vHasProblem INT; DECLARE vHasProblem INT;

View File

@ -9,9 +9,11 @@ BEGIN
* @param vClientFk Id Cliente, if NULL all clients * @param vClientFk Id Cliente, if NULL all clients
*/ */
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
(INDEX(ticketFk)) (INDEX(ticketFk, isProblemCalcNeeded))
ENGINE = MEMORY ENGINE = MEMORY
SELECT t.id ticketFk, FALSE hasProblem SELECT t.id ticketFk,
FALSE hasProblem,
ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
FROM ticket t FROM ticket t
WHERE t.shipped >= util.VN_CURDATE() WHERE t.shipped >= util.VN_CURDATE()
AND (vClientFk IS NULL OR t.clientFk = vClientFk); AND (vClientFk IS NULL OR t.clientFk = vClientFk);

View File

@ -9,9 +9,11 @@ BEGIN
* @param vSelf Id ticket, if NULL ALL tickets * @param vSelf Id ticket, if NULL ALL tickets
*/ */
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
(INDEX(ticketFk)) (INDEX(ticketFk, isProblemCalcNeeded))
ENGINE = MEMORY ENGINE = MEMORY
SELECT t.id ticketFk, FALSE hasProblem SELECT t.id ticketFk,
FALSE hasProblem,
ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
FROM ticket t FROM ticket t
WHERE t.shipped >= util.VN_CURDATE() WHERE t.shipped >= util.VN_CURDATE()
AND (vSelf IS NULL OR t.id = vSelf); AND (vSelf IS NULL OR t.id = vSelf);

View File

@ -10,21 +10,30 @@ BEGIN
*/ */
DECLARE vHasRisk BOOL; DECLARE vHasRisk BOOL;
DECLARE vHasHighRisk BOOL; DECLARE vHasHighRisk BOOL;
DECLARE vIsProblemCalcNeeded BOOL;
SELECT t.risk > (c.credit + 10), ((t.risk - cc.riskTolerance) > (c.credit + 10)) SELECT t.risk > (c.credit + 10),
INTO vHasRisk, vHasHighRisk (t.risk - cc.riskTolerance) > (c.credit + 10),
ticket_isProblemCalcNeeded(t.id)
INTO vHasRisk, vHasHighRisk, vIsProblemCalcNeeded
FROM client c FROM client c
JOIN ticket t ON t.clientFk = c.id JOIN ticket t ON t.clientFk = c.id
JOIN clientConfig cc JOIN clientConfig cc
WHERE t.id = vSelf; WHERE t.id = vSelf;
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
SELECT vSelf ticketFk, vHasRisk hasProblem; ENGINE = MEMORY
SELECT vSelf ticketFk,
vHasRisk hasProblem,
vIsProblemCalcNeeded isProblemCalcNeeded;
CALL ticket_setProblem('hasRisk'); CALL ticket_setProblem('hasRisk');
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
SELECT vSelf ticketFk, vHasHighRisk hasProblem; ENGINE = MEMORY
SELECT vSelf ticketFk,
vHasHighRisk hasProblem,
vIsProblemCalcNeeded isProblemCalcNeeded;
CALL ticket_setProblem('hasHighRisk'); CALL ticket_setProblem('hasHighRisk');

View File

@ -19,7 +19,10 @@ BEGIN
CALL buyUltimate(vWarehouseFk, vDated); CALL buyUltimate(vWarehouseFk, vDated);
CREATE OR REPLACE TEMPORARY TABLE tmp.sale CREATE OR REPLACE TEMPORARY TABLE tmp.sale
SELECT s.id saleFk , MOD(s.quantity, b.`grouping`) hasProblem (INDEX(saleFk, isProblemCalcNeeded))
SELECT s.id saleFk ,
MOD(s.quantity, b.`grouping`) hasProblem,
ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
FROM ticket t FROM ticket t
JOIN sale s ON s.ticketFk = t.id JOIN sale s ON s.ticketFk = t.id
JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk

View File

@ -9,9 +9,11 @@ BEGIN
* @param vClientFk Id cliente, if NULL all clients * @param vClientFk Id cliente, if NULL all clients
*/ */
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
(INDEX(ticketFk)) (INDEX(ticketFk, isProblemCalcNeeded))
ENGINE = MEMORY ENGINE = MEMORY
SELECT t.id ticketFk, IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem SELECT t.id ticketFk,
IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem,
ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded
FROM ticket t FROM ticket t
JOIN client c ON c.id = t.clientFk JOIN client c ON c.id = t.clientFk
WHERE t.shipped >= util.VN_CURDATE() WHERE t.shipped >= util.VN_CURDATE()

View File

@ -8,13 +8,17 @@ BEGIN
* *
* @param vSelf Id del ticket * @param vSelf Id del ticket
*/ */
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
(INDEX(ticketFk)) (INDEX(ticketFk, isProblemCalcNeeded))
ENGINE = MEMORY ENGINE = MEMORY
SELECT vSelf ticketFk, ticket_isTooLittle(vSelf) hasProblem; SELECT vSelf ticketFk,
ticket_isTooLittle(vSelf) hasProblem,
ticket_isProblemCalcNeeded(vSelf) isProblemCalcNeeded;
CALL ticket_setProblem('isTooLittle'); CALL ticket_setProblem('isTooLittle');
DROP TEMPORARY TABLE tmp.ticket; DROP TEMPORARY TABLE tmp.ticket;
END$$ END$$
DELIMITER ; DELIMITER ;

View File

@ -10,7 +10,7 @@ BEGIN
* @param vItemFk Id del item, NULL ALL items * @param vItemFk Id del item, NULL ALL items
*/ */
CREATE OR REPLACE TEMPORARY TABLE tmp.ticket CREATE OR REPLACE TEMPORARY TABLE tmp.ticket
(INDEX(ticketFk)) (INDEX(ticketFk, isProblemCalcNeeded))
ENGINE = MEMORY ENGINE = MEMORY
WITH tickets AS( WITH tickets AS(
SELECT t.id ticketFk SELECT t.id ticketFk
@ -19,7 +19,9 @@ BEGIN
WHERE t.shipped >= util.VN_CURDATE() WHERE t.shipped >= util.VN_CURDATE()
AND (s.itemFk = vItemFk OR vItemFk IS NULL) AND (s.itemFk = vItemFk OR vItemFk IS NULL)
GROUP BY t.id GROUP BY t.id
)SELECT ticketFk, ticket_isTooLittle(ticketFk) hasProblem )SELECT ticketFk,
ticket_isTooLittle(ticketFk) hasProblem,
ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded
FROM tickets; FROM tickets;
CALL ticket_setProblem('isTooLittle'); CALL ticket_setProblem('isTooLittle');

View File

@ -8,6 +8,7 @@ BEGIN
* @param vClientFk Id cliente * @param vClientFk Id cliente
*/ */
DECLARE vHasDebt BOOL; DECLARE vHasDebt BOOL;
DECLARE vStarted DATETIME;
SELECT COUNT(*) INTO vHasDebt SELECT COUNT(*) INTO vHasDebt
FROM `client` FROM `client`
@ -16,22 +17,24 @@ BEGIN
IF vHasDebt THEN IF vHasDebt THEN
SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted
FROM clientConfig;
CREATE OR REPLACE TEMPORARY TABLE tTicketRisk CREATE OR REPLACE TEMPORARY TABLE tTicketRisk
(KEY (ticketFk)) (KEY (ticketFk))
ENGINE = MEMORY ENGINE = MEMORY
WITH ticket AS( WITH ticket AS(
SELECT id ticketFk, companyFk, DATE(shipped) dated SELECT id ticketFk,
FROM vn.ticket t companyFk,
DATE(shipped) dated,
totalWithVat,
ticket_isProblemCalcNeeded(id) isProblemCalcNeeded
FROM vn.ticket
WHERE clientFk = vClientFk WHERE clientFk = vClientFk
AND refFk IS NULL AND refFk IS NULL
AND NOT isDeleted AND NOT isDeleted
AND totalWithoutVat <> 0 AND IFNULL(totalWithVat, 0) <> 0
), dated AS( AND shipped > vStarted
SELECT t.companyFk, MIN(DATE(t.dated) - INTERVAL cc.riskScope MONTH) started,
MAX(DATE(t.dated)) ended
FROM ticket t
JOIN vn.clientConfig cc
GROUP BY t.companyFk
), balance AS( ), balance AS(
SELECT SUM(amount)amount, companyFk SELECT SUM(amount)amount, companyFk
FROM ( FROM (
@ -49,15 +52,11 @@ BEGIN
WHERE companyFk WHERE companyFk
GROUP BY companyFk GROUP BY companyFk
), uninvoiced AS( ), uninvoiced AS(
SELECT t.companyFk, DATE(t.shipped) dated, SUM(IFNULL(t.totalWithVat, 0)) amount SELECT companyFk, dated, SUM(totalWithVat) amount
FROM vn.ticket t FROM ticket
JOIN dated d GROUP BY companyFk, dated
WHERE t.clientFk = vClientFk
AND t.refFk IS NULL
AND t.shipped BETWEEN d.started AND d.ended
GROUP BY t.companyFk, DATE(t.shipped)
), receipt AS( ), receipt AS(
SELECT companyFk,DATE(payed) dated, SUM(amountPaid) amount SELECT companyFk, DATE(payed) dated, SUM(amountPaid) amount
FROM vn.receipt FROM vn.receipt
WHERE clientFk = vClientFk WHERE clientFk = vClientFk
AND payed > util.VN_CURDATE() AND payed > util.VN_CURDATE()
@ -73,13 +72,21 @@ BEGIN
LEFT JOIN receipt r ON r.dated > ui.dated AND r.companyFk = ui.companyFk LEFT JOIN receipt r ON r.dated > ui.dated AND r.companyFk = ui.companyFk
GROUP BY b.companyFk, ui.dated GROUP BY b.companyFk, ui.dated
) )
SELECT ti.ticketFk, r.amount SELECT ti.ticketFk, r.amount, ti.isProblemCalcNeeded
FROM ticket ti FROM ticket ti
JOIN risk r ON r.dated = ti.dated AND r.companyFk = ti.companyFk; JOIN risk r ON r.dated = ti.dated AND r.companyFk = ti.companyFk;
UPDATE ticket t UPDATE ticket t
JOIN tTicketRisk tr ON tr.ticketFk = t.id JOIN tTicketRisk tr ON tr.ticketFk = t.id
SET t.risk = tr.amount; SET t.risk = tr.amount
WHERE tr.isProblemCalcNeeded
ORDER BY t.id;
UPDATE ticket t
JOIN tTicketRisk tr ON tr.ticketFk = t.id
SET t.risk = NULL
WHERE tr.isProblemCalcNeeded
ORDER BY t.id;
DROP TEMPORARY TABLE tTicketRisk; DROP TEMPORARY TABLE tTicketRisk;
END IF; END IF;

View File

@ -0,0 +1,22 @@
ALTER TABLE bs.waste ADD buyerFk int(10) unsigned NOT NULL;
UPDATE bs.waste w
JOIN account.`user` u ON u.name = w.buyer COLLATE utf8mb3_unicode_ci
SET w.buyerFk = u.id;
ALTER TABLE bs.waste
DROP PRIMARY KEY,
DROP COLUMN family,
DROP COLUMN rate,
DROP COLUMN buyer;
ALTER TABLE bs.waste CHANGE buyerFk buyerFk int(10) unsigned NOT NULL AFTER `week`;
ALTER TABLE bs.waste ADD CONSTRAINT waste_user_FK FOREIGN KEY (buyerFk) REFERENCES account.user(id) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE bs.waste ADD saleQuantity int(11) DEFAULT NULL NULL;
ALTER TABLE bs.waste MODIFY COLUMN saleTotal decimal(10,2) DEFAULT NULL NULL;
ALTER TABLE bs.waste MODIFY COLUMN saleWaste decimal(10,2) DEFAULT NULL NULL;
ALTER TABLE bs.waste CHANGE saleWaste saleInternalWaste decimal(10,2) DEFAULT NULL NULL;
ALTER TABLE bs.waste ADD saleExternalWaste decimal(10,2) DEFAULT NULL NULL;
ALTER TABLE bs.waste CHANGE saleQuantity saleQuantity decimal(10,2) DEFAULT NULL NULL AFTER itemTypeFk;
ALTER TABLE bs.waste CHANGE itemFk itemFk int(11) DEFAULT 0 NOT NULL AFTER itemTypeFk;
ALTER TABLE bs.waste ADD CONSTRAINT waste_pk PRIMARY KEY (`year`, `week`, buyerFk, itemTypeFk, itemFk);

View File

@ -0,0 +1,2 @@
ALTER TABLE `vn`.`client`
ADD COLUMN `hasDailyInvoice` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el cliente requiere facturación diaria por defecto se copiará lo que tenga country.hasDailyInvoice';

View File

@ -0,0 +1,11 @@
RENAME TABLE hedera.shelfConfig TO hedera.shelfMultiConfig ;
RENAME TABLE pbx.queueConfig TO pbx.queueMultiConfig ;
RENAME TABLE salix.defaultViewConfig TO salix.defaultViewMultiConfig;
RENAME TABLE edi.fileConfig TO edi.fileMultiConfig;
RENAME TABLE edi.imapConfig TO edi.imapMultiConfig;
RENAME TABLE edi.tableConfig TO edi.tableMultiConfig;
RENAME TABLE vn.invoiceOutTaxConfig TO vn.invoiceOutTaxMultiConfig;
RENAME TABLE vn.userConfig TO vn.userMultiConfig;
RENAME TABLE vn.conveyorConfig TO vn.conveyorMultiConfig;
GRANT SELECT ON TABLE hedera.shelfMultiConfig TO employee;

View File

@ -0,0 +1,2 @@
ALTER TABLE vn.itemMinimumQuantity
ADD CONSTRAINT itemMinimumQuantity_check CHECK (quantity > 0);

View File

@ -0,0 +1,2 @@
ALTER TABLE vn.ticketLastState MODIFY COLUMN name varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL;

View File

@ -0,0 +1,2 @@
INSERT INTO vn.state ( name, `order`, alertLevel, code, sectorProdPriority, nextStateFk, isPreviousPreparable, isPicked, isPreparable, semaphore, isPrintable, isOK, graphCategory, isNotValidated, classColor) VALUES('Entregado en parte', 13, 3, 'PARTIAL_DELIVERED', NULL, 16, 0, 1, 0, 0, 0, 0, 0, 0, NULL);

View File

@ -0,0 +1,8 @@
ALTER TABLE vn.item ADD IF NOT EXISTS tag11 varchar(20) DEFAULT NULL NULL;
ALTER TABLE vn.item ADD IF NOT EXISTS value11 varchar(50) DEFAULT NULL NULL;
ALTER TABLE vn.item ADD IF NOT EXISTS tag12 varchar(20) DEFAULT NULL NULL;
ALTER TABLE vn.item ADD IF NOT EXISTS value12 varchar(50) DEFAULT NULL NULL;
ALTER TABLE vn.item ADD IF NOT EXISTS tag13 varchar(20) DEFAULT NULL NULL;
ALTER TABLE vn.item ADD IF NOT EXISTS value13 varchar(50) DEFAULT NULL NULL;

View File

@ -57,7 +57,7 @@ describe('Ticket List sale path', () => {
let searchValue = 'Melee weapon heavy shield 100cm'; let searchValue = 'Melee weapon heavy shield 100cm';
await page.autocompleteSearch(selectors.ticketSales.secondSaleIdAutocomplete, searchValue); await page.autocompleteSearch(selectors.ticketSales.secondSaleIdAutocomplete, searchValue);
await page.waitToClick(selectors.ticketSales.secondSaleQuantityCell); await page.waitToClick(selectors.ticketSales.secondSaleQuantityCell);
await page.type(selectors.ticketSales.secondSaleQuantity, '1'); await page.type(selectors.ticketSales.secondSaleQuantity, '8');
await page.keyboard.press('Enter'); await page.keyboard.press('Enter');
const message = await page.waitForSnackbar(); const message = await page.waitForSnackbar();

View File

@ -99,6 +99,10 @@ module.exports = Self => {
{ {
arg: 'hasElectronicInvoice', arg: 'hasElectronicInvoice',
type: 'boolean' type: 'boolean'
},
{
arg: 'hasDailyInvoice',
type: 'boolean'
} }
], ],
returns: { returns: {
@ -117,8 +121,6 @@ module.exports = Self => {
const myOptions = {}; const myOptions = {};
const models = Self.app.models; const models = Self.app.models;
const args = ctx.args; const args = ctx.args;
const userId = ctx.req.accessToken.userId;
const $t = ctx.req.__;
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);

View File

@ -60,7 +60,7 @@ module.exports = Self => {
DISTINCT c.id clientFk, DISTINCT c.id clientFk,
c.name clientName, c.name clientName,
c.salesPersonFk, c.salesPersonFk,
c.businessTypeFk, c.businessTypeFk = 'worker' isWorker,
u.name salesPersonName, u.name salesPersonName,
d.amount, d.amount,
co.created, co.created,
@ -71,14 +71,23 @@ module.exports = Self => {
d.defaulterSinced, d.defaulterSinced,
cn.name country, cn.name country,
c.countryFk, c.countryFk,
pm.name payMethod pm.name payMethod,
FROM vn.defaulter d r.finished IS NULL hasRecovery,
JOIN vn.client c ON c.id = d.clientFk dp.id departmentFk,
JOIN vn.country cn ON cn.id = c.countryFk dp.name departmentName
JOIN vn.payMethod pm ON pm.id = c.payMethodFk FROM defaulter d
LEFT JOIN vn.clientObservation co ON co.clientFk = c.id JOIN client c ON c.id = d.clientFk
JOIN country cn ON cn.id = c.countryFk
JOIN payMethod pm ON pm.id = c.payMethodFk
LEFT JOIN clientObservation co ON co.clientFk = c.id
LEFT JOIN account.user u ON u.id = c.salesPersonFk LEFT JOIN account.user u ON u.id = c.salesPersonFk
LEFT JOIN account.user uw ON uw.id = co.workerFk LEFT JOIN account.user uw ON uw.id = co.workerFk
LEFT JOIN (
SELECT MAX(started), clientFk, finished
FROM recovery
) r ON r.clientFk = c.id
LEFT JOIN workerDepartment wd ON wd.workerFk = u.id
JOIN department dp ON dp.id = wd.departmentFk
WHERE WHERE
d.created = ? d.created = ?
AND d.amount > 0 AND d.amount > 0

View File

@ -144,6 +144,9 @@
}, },
"recommendedCredit": { "recommendedCredit": {
"type": "number" "type": "number"
},
"hasDailyInvoice": {
"type": "boolean"
} }
}, },

View File

@ -53,7 +53,7 @@
<vn-autocomplete vn-one <vn-autocomplete vn-one
ng-model="$ctrl.location.countryFk" ng-model="$ctrl.location.countryFk"
url="Countries" url="Countries"
show-field="country" show-field="name"
value-field="id" value-field="id"
label="Country"> label="Country">
</vn-autocomplete> </vn-autocomplete>

View File

@ -1,4 +1,3 @@
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const buildFilter = require('vn-loopback/util/filter').buildFilter; const buildFilter = require('vn-loopback/util/filter').buildFilter;
const mergeFilters = require('vn-loopback/util/filter').mergeFilters; const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
@ -95,6 +94,11 @@ module.exports = Self => {
arg: 'to', arg: 'to',
type: 'date', type: 'date',
description: `The to date filter` description: `The to date filter`
},
{
arg: 'days',
type: 'number',
description: `N days interval`
} }
], ],
returns: { returns: {
@ -192,6 +196,15 @@ module.exports = Self => {
JOIN vn.currency cu ON cu.id = e.currencyFk` JOIN vn.currency cu ON cu.id = e.currencyFk`
); );
if (ctx.args.days) {
stmt.merge({
sql: `
AND t.shipped <= util.VN_CURDATE() + INTERVAL ? DAY
AND t.shipped >= util.VN_CURDATE()
`,
params: [ctx.args.days]
});
}
stmt.merge(conn.makeSuffix(filter)); stmt.merge(conn.makeSuffix(filter));
const itemsIndex = stmts.push(stmt) - 1; const itemsIndex = stmts.push(stmt) - 1;

View File

@ -51,6 +51,7 @@ module.exports = Self => {
'stickers', 'stickers',
'packing', 'packing',
'grouping', 'grouping',
'packing',
'groupingMode', 'groupingMode',
'quantity', 'quantity',
'packagingFk', 'packagingFk',
@ -80,7 +81,9 @@ module.exports = Self => {
fields: [ fields: [
'id', 'id',
'typeFk', 'typeFk',
'stems',
'name', 'name',
'category',
'subName', 'subName',
'size', 'size',
'minPrice', 'minPrice',
@ -96,14 +99,31 @@ module.exports = Self => {
'value9', 'value9',
'tag10', 'tag10',
'value10', 'value10',
'groupingMode' 'groupingMode',
'inkFk',
'originFk',
'producerFk'
], ],
include: { include: [
{
relation: 'itemType', relation: 'itemType',
scope: { scope: {
fields: ['code', 'description'] fields: ['code', 'description']
} }
},
{
relation: 'origin',
scope: {
fields: ['code']
} }
},
{
relation: 'producer',
scope: {
fields: ['name']
}
}
]
} }
}] }]
}; };

View File

@ -39,7 +39,7 @@ describe('Entry filter()', () => {
const result = await models.Entry.filter(ctx, options); const result = await models.Entry.filter(ctx, options);
expect(result.length).toEqual(9); expect(result.length).toEqual(11);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -55,13 +55,13 @@ describe('Entry filter()', () => {
try { try {
const ctx = { const ctx = {
args: {}, args: {days: 6},
req: {accessToken: {userId: 1102}} req: {accessToken: {userId: 1102}}
}; };
const result = await models.Entry.filter(ctx, options); const result = await models.Entry.filter(ctx, options);
expect(result.length).toEqual(6); expect(result.length).toEqual(2);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -84,7 +84,7 @@ describe('Entry filter()', () => {
const result = await models.Entry.filter(ctx, options); const result = await models.Entry.filter(ctx, options);
expect(result.length).toEqual(6); expect(result.length).toEqual(8);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -107,7 +107,7 @@ describe('Entry filter()', () => {
const result = await models.Entry.filter(ctx, options); const result = await models.Entry.filter(ctx, options);
expect(result.length).toEqual(6); expect(result.length).toEqual(8);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {
@ -131,7 +131,7 @@ describe('Entry filter()', () => {
const result = await models.Entry.filter(ctx, options); const result = await models.Entry.filter(ctx, options);
expect(result.length).toEqual(8); expect(result.length).toEqual(10);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {

View File

@ -27,28 +27,42 @@ module.exports = Self => {
}); });
Self.getWasteByItem = async(buyer, family, options) => { Self.getWasteByItem = async(buyer, family, options) => {
const models = Self.app.models;
const myOptions = {}; const myOptions = {};
if (typeof options == 'object') if (typeof options == 'object')
Object.assign(myOptions, options); Object.assign(myOptions, options);
const user = await models.VnUser.findOne({
fields: ['id'],
where: {name: buyer}
});
const itemType = await models.ItemType.findOne({
fields: ['id'],
where: {name: family}
}, options);
const date = Date.vnNew(); const date = Date.vnNew();
date.setHours(0, 0, 0, 0); date.setHours(0, 0, 0, 0);
const wastes = await Self.rawSql(` const wastes = await Self.rawSql(`
SELECT *, 100 * dwindle / total AS percentage SELECT *, 100 * dwindle / total percentage
FROM ( FROM (
SELECT buyer, SELECT u.name buyer,
ws.family, it.name family,
ws.itemFk, w.itemFk,
sum(ws.saleTotal) AS total, SUM(w.saleTotal) total,
sum(ws.saleWaste) AS dwindle SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle
FROM bs.waste ws FROM bs.waste w
WHERE buyer = ? AND family = ? JOIN account.user u ON u.id = w.buyerFk
AND year = YEAR(TIMESTAMPADD(WEEK,-1, ?)) JOIN vn.itemType it ON it.id = w.itemTypeFk
AND week = WEEK(TIMESTAMPADD(WEEK,-1, ?), 1) WHERE w.buyerFk = ? AND w.itemTypeFk = ?
GROUP BY buyer, itemFk AND w.year = YEAR(TIMESTAMPADD(WEEK, -1, ?))
AND w.week = WEEK(TIMESTAMPADD(WEEK, -1, ?), 1)
GROUP BY w.buyerFk, w.itemFk
) sub ) sub
ORDER BY family, percentage DESC`, [buyer, family, date, date], myOptions); ORDER BY family, percentage DESC
`, [user.id, itemType.id, date, date], myOptions);
const details = []; const details = [];

View File

@ -22,31 +22,37 @@ module.exports = Self => {
const date = Date.vnNew(); const date = Date.vnNew();
date.setHours(0, 0, 0, 0); date.setHours(0, 0, 0, 0);
const wastes = await Self.rawSql(` const wastes = await Self.rawSql(`
SELECT *, 100 * dwindle / total AS percentage SELECT *, 100 * dwindle / total percentage
FROM ( FROM (
SELECT buyer, SELECT u.name buyer,
ws.family, it.name family,
sum(ws.saleTotal) AS total, w.itemFk,
sum(ws.saleWaste) AS dwindle SUM(w.saleTotal) total,
FROM bs.waste ws SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle
WHERE year = YEAR(TIMESTAMPADD(WEEK,-1, ?)) FROM bs.waste w
AND week = WEEK(TIMESTAMPADD(WEEK,-1, ?), 1) JOIN account.user u ON u.id = w.buyerFk
GROUP BY buyer, family JOIN vn.itemType it ON it.id = w.itemTypeFk
WHERE year = YEAR(TIMESTAMPADD(WEEK, -1, ?))
AND week = WEEK(TIMESTAMPADD(WEEK, -1, ?), 1)
GROUP BY buyerFk, itemTypeFk
) sub ) sub
ORDER BY percentage DESC`, [date, date], myOptions); ORDER BY percentage DESC
`, [date, date], myOptions);
const wastesTotal = await Self.rawSql(` const wastesTotal = await Self.rawSql(`
SELECT *, 100 * dwindle / total AS percentage SELECT *, 100 * dwindle / total percentage
FROM ( FROM (
SELECT buyer, SELECT u.name buyer,
sum(ws.saleTotal) AS total, SUM(w.saleTotal) total,
sum(ws.saleWaste) AS dwindle SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle
FROM bs.waste ws FROM bs.waste w
WHERE year = YEAR(TIMESTAMPADD(WEEK,-1, ?)) JOIN account.user u ON u.id = w.buyerFk
AND week = WEEK(TIMESTAMPADD(WEEK,-1, ?), 1) WHERE w.year = YEAR(TIMESTAMPADD(WEEK, -1, ?))
GROUP BY buyer AND w.week = WEEK(TIMESTAMPADD(WEEK, -1, ?), 1)
GROUP BY w.buyerFk
) sub ) sub
ORDER BY percentage DESC`, [date, date], myOptions); ORDER BY percentage DESC
`, [date, date], myOptions);
const details = []; const details = [];

View File

@ -6,13 +6,13 @@ describe('Item getWasteByItem()', () => {
const options = {transaction: tx}; const options = {transaction: tx};
try { try {
const result = await models.Item.getWasteByItem('CharlesXavier', 'Cymbidium', options); const result = await models.Item.getWasteByItem('buyer', 'Crisantemo', options);
const length = result.length; const length = result.length;
const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; const anyResult = result[Math.floor(Math.random() * Math.floor(length))];
expect(anyResult.buyer).toEqual('CharlesXavier'); expect(anyResult.buyer).toEqual('buyer');
expect(anyResult.family).toEqual('Cymbidium'); expect(anyResult.family).toEqual('Crisantemo');
expect(anyResult.lines.length).toBeGreaterThanOrEqual(2); expect(anyResult.lines.length).toBeGreaterThanOrEqual(2);
await tx.rollback(); await tx.rollback();

View File

@ -11,9 +11,9 @@ describe('Item getWasteByWorker()', () => {
const length = result.length; const length = result.length;
const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; const anyResult = result[Math.floor(Math.random() * Math.floor(length))];
expect(anyResult.buyer).toMatch(/(CharlesXavier|HankPym|DavidCharlesHaller)/); expect(anyResult.buyer).toMatch(/(buyer|it)/);
expect(anyResult.total).toBeGreaterThanOrEqual(1000); expect(anyResult.total).toBeGreaterThanOrEqual(1000);
expect(anyResult.lines.length).toBeGreaterThanOrEqual(3); expect(anyResult.lines.length).toBeGreaterThanOrEqual(1);
await tx.rollback(); await tx.rollback();
} catch (e) { } catch (e) {

View File

@ -48,7 +48,7 @@ module.exports = Self => {
LEFT JOIN vn.expeditionStateType est ON est.id = e.stateTypeFk LEFT JOIN vn.expeditionStateType est ON est.id = e.stateTypeFk
JOIN vn.agencyMode am ON am.id = r.agencyModeFk JOIN vn.agencyMode am ON am.id = r.agencyModeFk
JOIN vn.agency ag ON ag.id = am.agencyFk JOIN vn.agency ag ON ag.id = am.agencyFk
LEFT JOIN vn.userConfig uc ON uc.userFk = account.myUser_getId() LEFT JOIN vn.userMultiConfig uc ON uc.userFk = account.myUser_getId()
WHERE t.routeFk = ? WHERE t.routeFk = ?
GROUP BY t.addressFk, e.itemPackingTypeFk GROUP BY t.addressFk, e.itemPackingTypeFk
) sub ) sub

View File

@ -35,10 +35,10 @@
</vn-one> </vn-one>
<vn-one> <vn-one>
<vn-label-value label="Starting time" <vn-label-value label="Starting time"
value="{{$ctrl.summary.route.time | date: 'HH:MM'}}"> value="{{$ctrl.summary.route.started | date: 'HH:mm'}}">
</vn-label-value> </vn-label-value>
<vn-label-value label="Finishing time" <vn-label-value label="Finishing time"
value="{{$ctrl.summary.route.finished | date: 'HH:MM'}}"> value="{{$ctrl.summary.route.finished | date: 'HH:mm'}}">
</vn-label-value> </vn-label-value>
<vn-label-value label="Km Start" <vn-label-value label="Km Start"
value="{{$ctrl.summary.route.kmStart}}"> value="{{$ctrl.summary.route.kmStart}}">

View File

@ -44,15 +44,21 @@ module.exports = Self => {
const expedition = await models.Expedition.findOne(filter); const expedition = await models.Expedition.findOne(filter);
const {code} = expedition.agencyMode(); const {code} = expedition.agencyMode();
let isDeleted = true;
if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') { if (code?.toLowerCase()?.includes('mrw')) {
const isDeleted = await models.ViaexpressConfig.deleteExpedition(expeditionId); const result = await models.MrwConfig.cancelShipment(expeditionId);
isDeleted = result;
}
if (isDeleted === 'true') { if (code?.toLowerCase()?.substring(0, 10) == 'viaexpress') {
const deletedExpedition = await models.Expedition.destroyById(expeditionId); const result = await models.ViaexpressConfig.deleteExpedition(expeditionId);
deletedExpeditions.push(deletedExpedition); if (result !== 'true') isDeleted = false;
} else notDeletedExpeditions.push(expeditionId); }
} else {
if (!isDeleted)
notDeletedExpeditions.push(expeditionId);
else {
const deletedExpedition = await models.Expedition.destroyById(expeditionId); const deletedExpedition = await models.Expedition.destroyById(expeditionId);
deletedExpeditions.push(deletedExpedition); deletedExpeditions.push(deletedExpedition);
} }

View File

@ -53,13 +53,22 @@ module.exports = Self => {
const stmts = []; const stmts = [];
const stmt = new ParameterizedSQL( const stmt = new ParameterizedSQL(
`SELECT t.id AS ticketFk, c.id AS clientFk, c.name AS clientName, tw.weekDay, `SELECT t.id AS ticketFk,
wh.name AS warehouseName, u.id AS workerFk, u.name AS userName, u.nickName, tw.agencyModeFk c.id AS clientFk,
c.name AS clientName,
tw.weekDay,
wh.name AS warehouseName,
u.id AS workerFk,
u.name AS userName,
u.nickName,
tw.agencyModeFk,
am.name agencyModeName
FROM ticketWeekly tw FROM ticketWeekly tw
JOIN ticket t ON t.id = tw.ticketFk JOIN ticket t ON t.id = tw.ticketFk
JOIN client c ON c.id = t.clientFk JOIN client c ON c.id = t.clientFk
JOIN account.user u ON u.id = c.salesPersonFk JOIN account.user u ON u.id = c.salesPersonFk
JOIN warehouse wh ON wh.id = t.warehouseFk` JOIN warehouse wh ON wh.id = t.warehouseFk
LEFT JOIN agencyMode am ON am.id = tw.agencyModeFk`
); );
stmt.merge(conn.makeSuffix(filter)); stmt.merge(conn.makeSuffix(filter));

View File

@ -71,7 +71,8 @@ module.exports = Self => {
JSON_ARRAYAGG( JSON_ARRAYAGG(
JSON_OBJECT( JSON_OBJECT(
'ticketId', ticketFk, 'ticketId', ticketFk,
'reason', reason 'reason', reason,
'clientId', clientFk
) )
) )
)errors )errors
@ -83,7 +84,8 @@ module.exports = Self => {
IF(hasErrorDeleted, 'Eliminado', NULL), IF(hasErrorDeleted, 'Eliminado', NULL),
IF(hasErrorItemTaxCountry, 'Impuesto no informado', NULL), IF(hasErrorItemTaxCountry, 'Impuesto no informado', NULL),
IF(hasErrorAddress, 'Sin dirección', NULL), IF(hasErrorAddress, 'Sin dirección', NULL),
IF(hasErrorInfoTaxAreaWorld, 'Datos exportaciones', NULL)) reason IF(hasErrorInfoTaxAreaWorld, 'Datos exportaciones', NULL)) reason,
clientFk
FROM ( FROM (
SELECT t.id ticketFk, SELECT t.id ticketFk,
SUM(NOT c.hasToInvoice) hasErrorToInvoice, SUM(NOT c.hasToInvoice) hasErrorToInvoice,
@ -93,7 +95,8 @@ module.exports = Self => {
SUM(a.id IS NULL) hasErrorAddress, SUM(a.id IS NULL) hasErrorAddress,
SUM(ios.code IS NOT NULL SUM(ios.code IS NOT NULL
AND(ad.customsAgentFk IS NULL AND(ad.customsAgentFk IS NULL
OR ad.incotermsFk IS NULL)) hasErrorInfoTaxAreaWorld OR ad.incotermsFk IS NULL)) hasErrorInfoTaxAreaWorld,
t.clientFk clientFk
FROM ticket t FROM ticket t
LEFT JOIN address ad ON ad.id = t.addressFk LEFT JOIN address ad ON ad.id = t.addressFk
JOIN sale s ON s.ticketFk = t.id JOIN sale s ON s.ticketFk = t.id

View File

@ -140,7 +140,16 @@ module.exports = Self => {
await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions);
await ticket.updateAttribute('isSigned', true, myOptions); await ticket.updateAttribute('isSigned', true, myOptions);
await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticketId, 'DELIVERED'], myOptions); const [{stateCode}] = await Self.rawSql(`
SELECT
IF((SUM(CASE WHEN est.code = 'DELIVERED' THEN 1 ELSE 0 END) = COUNT(*)),
'DELIVERED','PARTIAL_DELIVERED') stateCode
FROM vn.expedition e
JOIN vn.expeditionStateType est ON est.id = e.stateTypeFk
WHERE e.ticketFk = ?;
`, [ticketId], myOptions);
await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticketId, stateCode], myOptions);
if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) { if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) {
await models.Ticket.saveCmr(ctx, [ticketId], myOptions); await models.Ticket.saveCmr(ctx, [ticketId], myOptions);

View File

@ -26,4 +26,36 @@ describe('Ticket saveSign()', () => {
expect(error).toBeDefined(); expect(error).toBeDefined();
}); });
it('should change state for ticket', async() => {
const tx = await models.Ticket.beginTransaction({});
const ticketWithPackedState = 7;
const ticketStateId = 16;
const ticketCode = 'PARTIAL_DELIVERED';
spyOn(models.Dms, 'uploadFile').and.returnValue([{id: 1}]);
let ticketTrackingAfter;
try {
const options = {transaction: tx};
const tickets = [ticketWithPackedState];
const state = await models.State.findById(ticketStateId, null, options);
await state.updateAttributes({
code: ticketCode,
name: ticketCode
}, options);
await models.Ticket.saveSign(ctx, tickets, null, null, options);
ticketTrackingAfter = await models.TicketLastState.findOne({
where: {ticketFk: ticketWithPackedState}
}, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
expect(ticketTrackingAfter.name).toBe('PARTIAL_DELIVERED');
});
}); });

View File

@ -88,8 +88,8 @@ module.exports = Self => {
if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return;
const minQuantity = await models.ItemMinimumQuantity.findOne({ const itemMinimalQuantity = await models.ItemMinimumQuantity.find({
fields: ['quantity'], fields: ['quantity', 'warehouseFk'],
where: { where: {
itemFk: itemId, itemFk: itemId,
started: {lte: ticket.shipped}, started: {lte: ticket.shipped},
@ -103,9 +103,14 @@ module.exports = Self => {
{warehouseFk: null} {warehouseFk: null}
] ]
}, },
limit: 1
}, ctx.options); }, ctx.options);
const minQuantity = itemMinimalQuantity.reduce((selected, item) => {
if (item.warehouseFk === ticket.warehouseFk) return item;
if (item.warehouseFk === null && !selected) return item;
return selected;
}, null);
if (newQuantity < minQuantity?.quantity && newQuantity != available) if (newQuantity < minQuantity?.quantity && newQuantity != available)
throw new UserError('The amount cannot be less than the minimum'); throw new UserError('The amount cannot be less than the minimum');

View File

@ -79,7 +79,7 @@ describe('Travel extraCommunityFilter()', () => {
const result = await app.models.Travel.extraCommunityFilter(ctx, filter); const result = await app.models.Travel.extraCommunityFilter(ctx, filter);
expect(result.length).toEqual(8); expect(result.length).toEqual(9);
}); });
it('should return the travel matching "cargoSupplierFk"', async() => { it('should return the travel matching "cargoSupplierFk"', async() => {
@ -110,6 +110,6 @@ describe('Travel extraCommunityFilter()', () => {
const result = await app.models.Travel.extraCommunityFilter(ctx, filter); const result = await app.models.Travel.extraCommunityFilter(ctx, filter);
expect(result.length).toEqual(1); expect(result.length).toEqual(2);
}); });
}); });

View File

@ -50,7 +50,7 @@ describe('Travel filter()', () => {
const result = await app.models.Travel.filter(ctx); const result = await app.models.Travel.filter(ctx);
expect(result.length).toEqual(5); expect(result.length).toEqual(6);
}); });
it('should return the routes matching "shipped from" and "shipped to"', async() => { it('should return the routes matching "shipped from" and "shipped to"', async() => {
@ -80,6 +80,6 @@ describe('Travel filter()', () => {
const result = await app.models.Travel.filter(ctx); const result = await app.models.Travel.filter(ctx);
expect(result.length).toEqual(5); expect(result.length).toEqual(6);
}); });
}); });

View File

@ -171,8 +171,8 @@ module.exports = Self => {
const address = await models.Address.create({ const address = await models.Address.create({
clientFk: user.id, clientFk: user.id,
street: street, street: street,
city: city, city,
provinceFk: provinceFk, provinceFk,
postalCode: postcode, postalCode: postcode,
mobile: phone, mobile: phone,
nickname: nickname, nickname: nickname,
@ -193,7 +193,13 @@ module.exports = Self => {
} }
await user.updateAttribute('email', email, myOptions); await user.updateAttribute('email', email, myOptions);
let countryFk;
if (provinceFk) {
const province = await Self.app.models.Province.findById(provinceFk, {
fields: ['countryFk']
});
countryFk = province.countryFk;
}
await models.Worker.create({ await models.Worker.create({
id: user.id, id: user.id,
firstName, firstName,
@ -202,7 +208,7 @@ module.exports = Self => {
bossFk, bossFk,
fi, fi,
birth, birth,
originCountryFk: countryFk
}, myOptions); }, myOptions);
if (tx) await tx.commit(); if (tx) await tx.commit();
@ -212,11 +218,8 @@ module.exports = Self => {
const message = e.sqlMessage; const message = e.sqlMessage;
if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`); if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`); if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`); if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`);
throw e; throw e;
} }

View File

@ -27,11 +27,10 @@ module.exports = Self => {
}); });
async function tinIsValid(err, done) { async function tinIsValid(err, done) {
const filter = { const country = await Self.app.models.Country.findOne({
fields: ['code'], fields: ['code'],
where: {id: this.countryFk} where: {id: this.originCountryFk}
}; });
const country = await Self.app.models.Country.findOne(filter);
const code = country ? country.code.toLowerCase() : null; const code = country ? country.code.toLowerCase() : null;
if (!this.fi || !validateTin(this.fi, code)) if (!this.fi || !validateTin(this.fi, code))

View File

@ -60,6 +60,11 @@
"type": "hasMany", "type": "hasMany",
"model": "Zone", "model": "Zone",
"foreignKey": "agencyModeFk" "foreignKey": "agencyModeFk"
},
"mrwService": {
"type": "belongsTo",
"model": "MrwService",
"foreignKey": "code"
} }
}, },
"acls": [ "acls": [

View File

@ -42,7 +42,7 @@ fixtures:
- ACL - ACL
- fieldAcl - fieldAcl
- module - module
- defaultViewConfig - defaultViewMultiConfig
vn: vn:
- alertLevel - alertLevel
- bookingPlanner - bookingPlanner
@ -363,7 +363,7 @@ localFixtures:
- travelConfig - travelConfig
- travelRecalc - travelRecalc
- travelThermograph - travelThermograph
- userConfig - userMultiConfig
- vehicle - vehicle
- wagonConfig - wagonConfig
- wagonType - wagonType

View File

@ -1,6 +1,6 @@
{ {
"name": "salix-back", "name": "salix-back",
"version": "24.30.0", "version": "24.32.0",
"author": "Verdnatura Levante SL", "author": "Verdnatura Levante SL",
"description": "Salix backend", "description": "Salix backend",
"license": "GPL-3.0", "license": "GPL-3.0",

View File

@ -1,11 +1,13 @@
SELECT *, 100 * dwindle / total AS percentage SELECT *, 100 * dwindle / total `percentage`
FROM ( FROM (
SELECT buyer, SELECT u.name buyer,
sum(saleTotal) as total, SUM(saleTotal) total,
sum(saleWaste) as dwindle SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle
FROM bs.waste w FROM bs.waste w
JOIN vn.time t ON w.year = t.year AND w.week = t.week JOIN account.user u ON u.id = w.buyerFk
WHERE t.dated = DATE_ADD(CURDATE(), INTERVAL -1 WEEK) JOIN vn.itemType it ON it.id = w.itemTypeFk
GROUP BY buyer WHERE w.year = YEAR(util.VN_CURDATE() - INTERVAL 1 WEEK)
AND w.week = WEEK(util.VN_CURDATE() - INTERVAL 1 WEEK, 4)
GROUP BY buyerFk
) sub ) sub
ORDER BY percentage DESC; ORDER BY `percentage` DESC;

View File

@ -7,6 +7,7 @@
<div v-for="ticket in tickets" class="grid-block vn-px-ml"> <div v-for="ticket in tickets" class="grid-block vn-px-ml">
<p v-if="ticket.ticketId"><b>{{ $t('ticketId') }}:</b> {{ticket.ticketId}}</p> <p v-if="ticket.ticketId"><b>{{ $t('ticketId') }}:</b> {{ticket.ticketId}}</p>
<p v-if="ticket.reason"><b>{{ $t('reason') }}:</b> {{ticket.reason}}</p> <p v-if="ticket.reason"><b>{{ $t('reason') }}:</b> {{ticket.reason}}</p>
<p v-if="ticket.clientId"><b>{{ $t('clientId')}}</b>{{ticket.clientId}}</p>
<hr> <hr>
</div> </div>
</div> </div>

View File

@ -2,3 +2,4 @@ subject: Nightly ticket closing process report
title: Nightly ticket closing process report title: Nightly ticket closing process report
reason: Reason reason: Reason
ticketId: Ticket ticketId: Ticket
clientId: Client

View File

@ -2,3 +2,4 @@ subject: Informe proceso de cierre de tickets nocturno
title: Informe proceso de cierre de tickets nocturno title: Informe proceso de cierre de tickets nocturno
reason: Motivo reason: Motivo
ticketId: Ticket ticketId: Ticket
clientId: Cliente