Compare commits

..

No commits in common. "db06620d7c0c9477b7db345279abf15fef1db732" and "4383ebd7f1ad7f0430488f92ba4cd131a0e61e8f" have entirely different histories.

108 changed files with 556 additions and 758 deletions

View File

@ -5,22 +5,15 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2350.01] - 2023-12-14
### Added
### Changed
### Fixed
## [2348.01] - 2023-11-30
### Características Añadidas 🆕
- **Tickets → Adelantar:** Permite mover lineas sin generar negativos
- **Tickets → Adelantar:** Permite modificar la fecha de los tickets
- **Trabajadores → Notificaciones:** Nueva sección (lilium)
### Added
- (Ticket -> Adelantar) Permite mover lineas sin generar negativos
- (Ticket -> Adelantar) Permite modificar la fecha de los tickets
### Correcciones 🛠️
- **Tickets → RocketChat:** Arreglada detección de cambios
### Changed
### Fixed
- (Ticket -> RocketChat) Arreglada detección de cambios
## [2346.01] - 2023-11-16

View File

@ -49,7 +49,7 @@ module.exports = Self => {
ish.packing,
ish.grouping,
s.isAdded,
s.originalQuantity,
s.originalQuantity,
s.quantity saleQuantity,
iss.quantity reservedQuantity,
SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id) accumulatedQuantity,
@ -75,7 +75,7 @@ module.exports = Self => {
LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk
LEFT JOIN origin o ON o.id = i.originFk
WHERE tc.collectionFk = ?
GROUP BY s.id, ish.id, p.code, p2.code
GROUP BY ish.id, p.code, p2.code
ORDER BY pickingOrder;`, [id], myOptions);
if (print)
@ -105,7 +105,7 @@ module.exports = Self => {
LEFT JOIN vn.buy c ON c.itemFk = s.itemFk
LEFT JOIN vn.entry e ON e.id = c.entryFk
LEFT JOIN vn.travel tr ON tr.id = e.travelFk
WHERE s.ticketFk = ?
WHERE s.ticketFk = ?
AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`,
[ticketId], myOptions);
ticket.sales = [];

View File

@ -0,0 +1,133 @@
module.exports = Self => {
Self.remoteMethodCtx('newCollection', {
description: 'Make a new collection of tickets',
accessType: 'WRITE',
accepts: [{
arg: 'collectionFk',
type: 'Number',
required: false,
description: 'The collection id'
}, {
arg: 'sectorFk',
type: 'Number',
required: true,
description: 'The sector of worker'
}, {
arg: 'vWagons',
type: 'Number',
required: true,
description: 'The number of wagons'
}],
returns: {
type: 'Object',
root: true
},
http: {
path: `/newCollection`,
verb: 'POST'
}
});
Self.newCollection = async(ctx, collectionFk, sectorFk, vWagons) => {
let query = '';
const userId = ctx.req.accessToken.userId;
if (!collectionFk) {
query = `CALL vn.collectionTrain_newBeta(?,?,?)`;
const [result] = await Self.rawSql(query, [sectorFk, vWagons, userId], {userId});
if (result.length == 0)
throw new Error(`No collections for today`);
collectionFk = result[0].vCollectionFk;
}
query = `CALL vn.collectionTicket_get(?)`;
const [tickets] = await Self.rawSql(query, [collectionFk], {userId});
query = `CALL vn.collectionSale_get(?)`;
const [sales] = await Self.rawSql(query, [collectionFk], {userId});
query = `CALL vn.collectionPlacement_get(?)`;
const [placements] = await Self.rawSql(query, [collectionFk], {userId});
query = `CALL vn.collectionSticker_print(?,?)`;
await Self.rawSql(query, [collectionFk, sectorFk], {userId});
return makeCollection(tickets, sales, placements, collectionFk);
};
/**
* Returns a collection json
* @param {*} tickets - Request tickets
* @param {*} sales - Request sales
* @param {*} placements - Request placements
* @param {*} collectionFk - Request placements
* @return {Object} Collection JSON
*/
async function makeCollection(tickets, sales, placements, collectionFk) {
let collection = [];
for (let i = 0; i < tickets.length; i++) {
let ticket = {};
ticket['ticketFk'] = tickets[i]['ticketFk'];
ticket['level'] = tickets[i]['level'];
ticket['agencyName'] = tickets[i]['agencyName'];
ticket['warehouseFk'] = tickets[i]['warehouseFk'];
ticket['salesPersonFk'] = tickets[i]['salesPersonFk'];
let ticketSales = [];
for (let x = 0; x < sales.length; x++) {
if (sales[x]['ticketFk'] == ticket['ticketFk']) {
let sale = {};
sale['collectionFk'] = collectionFk;
sale['ticketFk'] = sales[x]['ticketFk'];
sale['saleFk'] = sales[x]['saleFk'];
sale['itemFk'] = sales[x]['itemFk'];
sale['quantity'] = sales[x]['quantity'];
if (sales[x]['quantityPicked'] != null)
sale['quantityPicked'] = sales[x]['quantityPicked'];
else
sale['quantityPicked'] = 0;
sale['longName'] = sales[x]['longName'];
sale['size'] = sales[x]['size'];
sale['color'] = sales[x]['color'];
sale['discount'] = sales[x]['discount'];
sale['price'] = sales[x]['price'];
sale['stems'] = sales[x]['stems'];
sale['category'] = sales[x]['category'];
sale['origin'] = sales[x]['origin'];
sale['clientFk'] = sales[x]['clientFk'];
sale['productor'] = sales[x]['productor'];
sale['reserved'] = sales[x]['reserved'];
sale['isPreviousPrepared'] = sales[x]['isPreviousPrepared'];
sale['isPrepared'] = sales[x]['isPrepared'];
sale['isControlled'] = sales[x]['isControlled'];
let salePlacements = [];
for (let z = 0; z < placements.length; z++) {
if (placements[z]['saleFk'] == sale['saleFk']) {
let placement = {};
placement['saleFk'] = placements[z]['saleFk'];
placement['itemFk'] = placements[z]['itemFk'];
placement['placement'] = placements[z]['placement'];
placement['shelving'] = placements[z]['shelving'];
placement['created'] = placements[z]['created'];
placement['visible'] = placements[z]['visible'];
placement['order'] = placements[z]['order'];
placement['grouping'] = placements[z]['grouping'];
salePlacements.push(placement);
}
}
sale['placements'] = salePlacements;
ticketSales.push(sale);
}
}
ticket['sales'] = ticketSales;
collection.push(ticket);
}
return collection;
}
};

View File

@ -0,0 +1,12 @@
const {models} = require('vn-loopback/server/server');
describe('newCollection()', () => {
it('should return a new collection', async() => {
pending('#3400 analizar que hacer con rutas de back collection');
let ctx = {req: {accessToken: {userId: 1106}}};
let response = await models.Collection.newCollection(ctx, 1, 1, 1);
expect(response.length).toBeGreaterThan(0);
expect(response[0].ticketFk).toEqual(2);
});
});

View File

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<DeleteEnvio xmlns="http://82.223.6.71:82">
<IdCliente><%= viaexpressConfig.client %></IdCliente>
<Usuario><%= viaexpressConfig.user %></Usuario>
<Password><%= viaexpressConfig.password %></Password>
<etiqueta><%= externalId %></etiqueta>
</DeleteEnvio>
</soap12:Body>
</soap12:Envelope>

View File

@ -1,45 +0,0 @@
const axios = require('axios');
const {DOMParser} = require('xmldom');
module.exports = Self => {
Self.remoteMethod('deleteExpedition', {
description: 'Delete a shipment by providing the expedition ID, interacting with Viaexpress API',
accessType: 'WRITE',
accepts: [{
arg: 'expeditionFk',
type: 'number',
required: true
}],
returns: {
type: ['object'],
root: true
},
http: {
path: `/deleteExpedition`,
verb: 'POST'
}
});
Self.deleteExpedition = async expeditionFk => {
const models = Self.app.models;
const viaexpressConfig = await models.ViaexpressConfig.findOne({
fields: ['url']
});
const renderedXml = await models.ViaexpressConfig.deleteExpeditionRenderer(expeditionFk);
const response = await axios.post(`${viaexpressConfig.url}ServicioVxClientes.asmx`, renderedXml, {
headers: {
'Content-Type': 'application/soap+xml; charset=utf-8'
}
});
const xmlString = response.data;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
const resultElement = xmlDoc.getElementsByTagName('DeleteEnvioResult')[0];
const result = resultElement.textContent;
return result;
};
};

View File

@ -1,44 +0,0 @@
const fs = require('fs');
const ejs = require('ejs');
module.exports = Self => {
Self.remoteMethod('deleteExpeditionRenderer', {
description: 'Renders the data from an XML',
accessType: 'READ',
accepts: [{
arg: 'expeditionFk',
type: 'number',
required: true
}],
returns: {
type: ['object'],
root: true
},
http: {
path: `/deleteExpeditionRenderer`,
verb: 'GET'
}
});
Self.deleteExpeditionRenderer = async expeditionFk => {
const models = Self.app.models;
const viaexpressConfig = await models.ViaexpressConfig.findOne({
fields: ['client', 'user', 'password']
});
const expedition = await models.Expedition.findOne({
fields: ['id', 'externalId'],
where: {id: expeditionFk}
});
const data = {
viaexpressConfig,
externalId: expedition.externalId
};
const template = fs.readFileSync(__dirname + '/deleteExpedition.ejs', 'utf-8');
const renderedXml = ejs.render(template, data);
return renderedXml;
};
};

View File

@ -49,7 +49,13 @@ module.exports = Self => {
if (vnUser.twoFactor)
throw new ForbiddenError(null, 'REQUIRES_2FA');
}
return Self.validateLogin(user, password, ctx);
const validateLogin = await Self.validateLogin(user, password);
await Self.app.models.SignInLog.create({
token: validateLogin.token,
userFk: vnUser.id,
ip: ctx.req.ip
});
return validateLogin;
};
Self.passExpired = async vnUser => {

View File

@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server');
describe('VnUser Sign-in()', () => {
const employeeId = 1;
const unAuthCtx = {
const unauthCtx = {
req: {
headers: {},
connection: {
@ -15,21 +15,20 @@ describe('VnUser Sign-in()', () => {
const {VnUser, AccessToken, SignInLog} = models;
describe('when credentials are correct', () => {
it('should return the token if user uses email', async() => {
let login = await VnUser.signIn(unAuthCtx, 'salesAssistant@mydomain.com', 'nightmare');
let login = await VnUser.signIn(unauthCtx, 'salesAssistant@mydomain.com', 'nightmare');
let accessToken = await AccessToken.findById(login.token);
let ctx = {req: {accessToken: accessToken}};
let signInLog = await SignInLog.find({where: {token: accessToken.id}});
expect(signInLog.length).toEqual(1);
expect(signInLog[0].userFk).toEqual(accessToken.userId);
expect(signInLog[0].owner).toEqual(true);
expect(login.token).toBeDefined();
await VnUser.logout(ctx.req.accessToken.id);
});
it('should return the token', async() => {
let login = await VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare');
let login = await VnUser.signIn(unauthCtx, 'salesAssistant', 'nightmare');
let accessToken = await AccessToken.findById(login.token);
let ctx = {req: {accessToken: accessToken}};
@ -39,7 +38,7 @@ describe('VnUser Sign-in()', () => {
});
it('should return the token if the user doesnt exist but the client does', async() => {
let login = await VnUser.signIn(unAuthCtx, 'PetterParker', 'nightmare');
let login = await VnUser.signIn(unauthCtx, 'PetterParker', 'nightmare');
let accessToken = await AccessToken.findById(login.token);
let ctx = {req: {accessToken: accessToken}};
@ -54,7 +53,7 @@ describe('VnUser Sign-in()', () => {
let error;
try {
await VnUser.signIn(unAuthCtx, 'IDontExist', 'TotallyWrongPassword');
await VnUser.signIn(unauthCtx, 'IDontExist', 'TotallyWrongPassword');
} catch (e) {
error = e;
}
@ -75,7 +74,7 @@ describe('VnUser Sign-in()', () => {
const options = {transaction: tx};
await employee.updateAttribute('twoFactor', 'email', options);
await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options);
await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options);
await tx.rollback();
} catch (e) {
await tx.rollback();
@ -100,7 +99,7 @@ describe('VnUser Sign-in()', () => {
const options = {transaction: tx};
await employee.updateAttribute('passExpired', yesterday, options);
await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options);
await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options);
await tx.rollback();
} catch (e) {
await tx.rollback();

View File

@ -1,5 +1,6 @@
module.exports = Self => {
require('../methods/collection/getCollection')(Self);
require('../methods/collection/newCollection')(Self);
require('../methods/collection/getSectors')(Self);
require('../methods/collection/setSaleQuantity')(Self);
require('../methods/collection/previousLabel')(Self);

View File

@ -1,6 +1,4 @@
module.exports = Self => {
require('../methods/viaexpress-config/internationalExpedition')(Self);
require('../methods/viaexpress-config/renderer')(Self);
require('../methods/viaexpress-config/deleteExpedition')(Self);
require('../methods/viaexpress-config/deleteExpeditionRenderer')(Self);
};

View File

@ -124,42 +124,20 @@ module.exports = function(Self) {
return email.send();
});
/**
* Sign-in validate
* @param {String} user The user
* @param {Object} userToken Options
* @param {Object} token accessToken
* @param {Object} ctx context
*/
Self.signInValidate = async(user, userToken, token, ctx) => {
Self.signInValidate = (user, userToken) => {
const [[key, value]] = Object.entries(Self.userUses(user));
const isOwner = Self.rawSql(`SELECT ? = ? `, [userToken[key], value]);
await Self.app.models.SignInLog.create({
userName: user,
token: token.id,
userFk: userToken.id,
ip: ctx.req.ip,
owner: isOwner
});
if (!isOwner)
if (userToken[key].toLowerCase().trim() !== value.toLowerCase().trim()) {
console.error('ERROR!!! - Signin with other user', userToken, user);
throw new UserError('Try again');
}
};
/**
* Validate login params
* @param {String} user The user
* @param {String} password
* @param {Object} ctx context
*/
Self.validateLogin = async function(user, password, ctx) {
Self.validateLogin = async function(user, password) {
const loginInfo = Object.assign({password}, Self.userUses(user));
const token = await Self.login(loginInfo, 'user');
const userToken = await token.user.get();
if (ctx)
await Self.signInValidate(user, userToken, token, ctx);
Self.signInValidate(user, userToken);
try {
await Self.app.models.Account.sync(userToken.name, password);
@ -209,8 +187,8 @@ module.exports = function(Self) {
};
Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls =
Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls
.filter(acl => acl.property != 'changePassword');
Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls
.filter(acl => acl.property != 'changePassword');
Self.userSecurity = async(ctx, userId, options) => {
const models = Self.app.models;
@ -248,12 +226,10 @@ module.exports = function(Self) {
const env = process.env.NODE_ENV;
const liliumUrl = await Self.app.models.Url.findOne({
where: {
and: [
{appName: 'lilium'},
{environment: env}
]
}
where: {and: [
{appName: 'lilium'},
{environment: env}
]}
});
class Mailer {

View File

@ -118,13 +118,13 @@ BEGIN
SELECT 'UPDATE', account.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef)
FROM tmp.ticketToInvoice ti;
CALL invoiceExpenseMake(vNewInvoiceId);
CALL invoiceExpenceMake(vNewInvoiceId);
CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) AS total
FROM invoiceOutExpense
FROM invoiceOutExpence
WHERE invoiceOutFk = vNewInvoiceId
) base
JOIN (
@ -166,18 +166,18 @@ BEGIN
SET @vTaxableBaseServices := 0.00;
SET @vTaxCodeGeneral := NULL;
INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenseFk, sub.taxTypeSageFk , sub.transactionTypeSageFk
INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInId, @vTaxableBaseServices, sub.expenceFk, sub.taxTypeSageFk , sub.transactionTypeSageFk
FROM (
SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk
SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk
FROM tmp.ticketServiceTax tst
JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code
WHERE i.isService
HAVING taxableBase
) sub;
INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenseFk, i.taxTypeSageFk , i.transactionTypeSageFk
INSERT INTO vn.invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInId, SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral, @vTaxableBaseServices, 0) taxableBase, i.expenceFk, i.taxTypeSageFk , i.transactionTypeSageFk
FROM tmp.ticketTax tt
JOIN vn.invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code
WHERE !i.isService

View File

@ -139,13 +139,13 @@ BEGIN
SELECT 'UPDATE', account.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef)
FROM tmp.ticketToInvoice ti;
CALL invoiceExpenseMake(vNewInvoiceId);
CALL invoiceExpenceMake(vNewInvoiceId);
CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) total
FROM invoiceOutExpense
FROM invoiceOutExpence
WHERE invoiceOutFk = vNewInvoiceId
) base
JOIN (
@ -182,15 +182,15 @@ BEGIN
SET @vTaxableBaseServices := 0.00;
SET @vTaxCodeGeneral := NULL;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
@vTaxableBaseServices,
sub.expenseFk,
sub.expenceFk,
sub.taxTypeSageFk,
sub.transactionTypeSageFk
FROM (
SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase,
i.expenseFk,
i.expenceFk,
i.taxTypeSageFk,
i.transactionTypeSageFk,
@vTaxCodeGeneral := i.taxClassCodeFk
@ -200,11 +200,11 @@ BEGIN
HAVING taxableBase
) sub;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral,
@vTaxableBaseServices, 0) taxableBase,
i.expenseFk,
i.expenceFk,
i.taxTypeSageFk ,
i.transactionTypeSageFk
FROM tmp.ticketTax tt

View File

@ -135,13 +135,13 @@ BEGIN
INSERT INTO ticketTracking(stateFk,ticketFk,workerFk)
SELECT * FROM tmp.updateInter;
CALL invoiceExpenseMake(vNewInvoiceId);
CALL invoiceExpenceMake(vNewInvoiceId);
CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) total
FROM invoiceOutExpense
FROM invoiceOutExpence
WHERE invoiceOutFk = vNewInvoiceId
) base
JOIN (
@ -178,15 +178,15 @@ BEGIN
SET @vTaxableBaseServices := 0.00;
SET @vTaxCodeGeneral := NULL;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
@vTaxableBaseServices,
sub.expenseFk,
sub.expenceFk,
sub.taxTypeSageFk,
sub.transactionTypeSageFk
FROM (
SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase,
i.expenseFk,
i.expenceFk,
i.taxTypeSageFk,
i.transactionTypeSageFk,
@vTaxCodeGeneral := i.taxClassCodeFk
@ -196,11 +196,11 @@ BEGIN
HAVING taxableBase
) sub;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral,
@vTaxableBaseServices, 0) taxableBase,
i.expenseFk,
i.expenceFk,
i.taxTypeSageFk ,
i.transactionTypeSageFk
FROM tmp.ticketTax tt

View File

@ -1,4 +1,5 @@
--
-- Table structure for table `signInLog`
-- Description: log to debug cross-login error
@ -12,9 +13,7 @@ CREATE TABLE `account`.`signInLog` (
`token` varchar(255) NOT NULL ,
`userFk` int(10) unsigned DEFAULT NULL,
`creationDate` timestamp NULL DEFAULT current_timestamp(),
`userName` varchar(30) NOT NULL,
`ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`owner` tinyint(1) DEFAULT 1,
KEY `userFk` (`userFk`),
CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
);

View File

@ -1,60 +1,33 @@
DROP PROCEDURE IF EXISTS vn.zoneIncluded_checkCollisions;
DROP PROCEDURE IF EXISTS `vn`.`zoneIncluded_checkCollisions`;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneIncluded_checkCollisions`()
CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`zoneIncluded_checkCollisions`(IN zi_zone INT, IN zi_geo INT)
BEGIN
DECLARE zic_id, zic_zone, zic_geoFk, zic_action, zic_zoneFk, zic_userFk INT;
DECLARE zic2_geoFk, zic2_zoneFk INT;
DECLARE z_name VARCHAR(255);
DECLARE g_name VARCHAR(255);
DECLARE vDone boolean;
DECLARE done INT DEFAULT 0;
DECLARE zic_id, zic_zone, zic_geo, zic_action, zic_userFk INT;
DECLARE z_name VARCHAR(255);
DECLARE g_name VARCHAR(255);
DECLARE my_cur CURSOR FOR
SELECT zic.id, z.name , zg.name , zic.geoFk ,zic.`action` , zic.userFK FROM vn.zoneIncludedCheck zic, vn.`zone` z, vn.zoneGeo zg WHERE zic.zoneFK =z.id AND zic.geoFK = zg.id ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN my_cur;
my_cur_loop:
LOOP FETCH my_cur INTO zic_id, z_name,g_name, zic_geo, zic_action, zic_userFk ;
IF done = 1 THEN
select concat('NO REDCORDS' ) AS '** DEBUG:';
LEAVE my_cur_loop;
END IF;
SELECT concat('** ', zic_id, '** ',z_name, '** ',g_name,'**',zic_geo,'** ', zic_action,'** ', zic_userFk ) AS '** DEBUG:';
DELETE FROM vn.zoneIncludedCheck WHERE id =zic_id;
SELECT util.notification_send('zone-included',
JSON_OBJECT('zoneSelected', z_name, 'geoSelected', g_name),
account.myUser_getId()
);
END LOOP my_cur_loop;
CLOSE my_cur;
DECLARE cur CURSOR FOR
SELECT zic.id, z.name , zg.name ,zic.zoneFK, zic.geoFk ,zic.`action` , zic.userFK
FROM vn.zoneIncludedCheck zic, vn.`zone` z, vn.zoneGeo zg
WHERE zic.zoneFK =z.id AND zic.geoFK = zg.id and zic.action ='insert';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vDone := FALSE;
OPEN cur;
LOOP1: LOOP
SET vDone := FALSE;
FETCH cur INTO zic_id, z_name, g_name, zic_zoneFk, zic_geoFk, zic_action, zic_userFk ;
IF vDone THEN
select concat('NO RECORDS LOOP 1' ) AS '** DEBUG:';
CLOSE cur;
LEAVE LOOP1;
END IF;
-- SELECT concat('** ', zic_id, '** ',z_name, '** ',g_name,'**',zic_zoneFk,'**',zic_geoFk,'** ', zic_action,'** ', zic_userFk ) AS '** DEBUG:';
DELETE FROM vn.zoneIncludedCheck WHERE id =zic_id;
BLOCK2: BEGIN
DECLARE vDone2 boolean;
DECLARE cur2 CURSOR FOR
SELECT zi.zoneFk,zi.geoFk
FROM vn.zoneIncluded zi, vn.zone z
where z.id = zi.zoneFk and zi.zoneFk=zic_zoneFk and zi.geoFk=zic_geoFk and zi.isIncluded = 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE;
SET vDone2 := FALSE;
OPEN cur2;
LOOP2: LOOP
FETCH cur2 INTO zic2_zoneFk, zic2_geoFk ;
IF vDone2 THEN
select concat('NO RECORDS LOOP 2' ) AS '** DEBUG:';
CLOSE cur2;
LEAVE LOOP2;
END IF;
SELECT concat('COLLISION DETECTED', zic2_zoneFk, zic2_geoFk ) AS '** DEBUG:';
SELECT util.notification_send('zone-included',
JSON_OBJECT('zoneSelected', z_name, 'geoSelected', g_name),
account.myUser_getId()
);
END LOOP LOOP2;
END BLOCK2;
END LOOP LOOP1;
END
$$
END$$
DELIMITER ;

View File

@ -1,9 +1,11 @@
-- Auto-generated SQL script #202311241021
INSERT INTO util.notification (name,description)
VALUES ('zone-included','An email to notify zoneCollisions');
-- Auto-generated SQL script #202311241051
INSERT INTO util.notificationSubscription (notificationFk,userFk)
SELECT id, account.myUser_getId() FROM util.notification WHERE name= "zone-included";
SELECT id, account.myUser_getId() FROM util.notification WHERE name= "zone-included"
INSERT INTO util.notificationAcl (notificationFk,roleFk)
SELECT id, (SELECT id from `account`.`role` where name = "system") FROM util.notification WHERE name= "zone-included";
SELECT id, account.role FROM util.notification WHERE name= "zone-included"

View File

@ -1,26 +0,0 @@
DELETE FROM `salix`.`ACL`
WHERE
model = 'Route'
AND property = '*'
AND accessType = 'READ';
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES
('Route', 'find', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'findById', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'findOne', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'getRoutesByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'canViewAllRoute', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'),
('Route', 'cmr', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'downloadCmrsZip', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'downloadZip', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'filter', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'getByWorker', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'getExternalCmrs', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'getSuggestedTickets', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'getTickets', 'READ', 'ALLOW', 'ROLE', 'employee'),
('Route', 'guessPriority', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Route', 'insertTicket', 'WRITE', 'ALLOW', 'ROLE', 'employee'),
('Route', 'getDeliveryPoint', 'READ', 'ALLOW', 'ROLE', 'deliveryBoss'),
('Route', 'summary', 'READ', 'ALLOW', 'ROLE', 'employee');

View File

@ -1,14 +1,6 @@
CREATE ROLE 'salix';
GRANT 'salix' TO 'root'@'%';
SET DEFAULT ROLE 'salix' FOR 'root'@'%';
CREATE SCHEMA IF NOT EXISTS `vn2008`;
CREATE SCHEMA IF NOT EXISTS `tmp`;
CREATE ROLE 'salix';
GRANT 'salix' TO 'root'@'%';
SET DEFAULT ROLE 'salix' FOR 'root'@'%';
UPDATE `util`.`config`
SET `environment`= 'development';
@ -370,7 +362,7 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`)
INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`, `hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`, `businessTypeFk`,`typeFk`)
VALUES
(1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'),
(1101, 'Bruce Wayne', '84612325V', 'BATMAN', 'Alfred', '1007 MOUNTAIN DRIVE, GOTHAM', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','loses'),
(1102, 'Petter Parker', '87945234L', 'SPIDER MAN', 'Aunt May', '20 INGRAM STREET, QUEENS, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'),
(1103, 'Clark Kent', '06815934E', 'SUPER MAN', 'lois lane', '344 CLINTON STREET, APARTAMENT 3-D', 'Gotham', 46460, 1111111111, 222222222, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 3, 1, 0, 19, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'),
(1104, 'Tony Stark', '06089160W', 'IRON MAN', 'Pepper Potts', '10880 MALIBU POINT, 90265', 'Gotham', 46460, 1111111111, 222222222, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 2, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1, 'florist','normal'),
@ -380,8 +372,8 @@ INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city
(1108, 'Charles Xavier', '22641921P', 'PROFESSOR X', 'Beast', '3800 VICTORY PKWY, CINCINNATI, OH 45207, USA', 'Gotham', 46460, 1111111111, 222222222, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 5, 1, 300, 13, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1, 'florist','normal'),
(1109, 'Bruce Banner', '16104829E', 'HULK', 'Black widow', 'SOMEWHERE IN NEW YORK', 'Gotham', 46460, 1111111111, 222222222, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, 9, 0, 1, 'florist','normal'),
(1110, 'Jessica Jones', '58282869H', 'JESSICA JONES', 'Luke Cage', 'NYCC 2015 POSTER', 'Gotham', 46460, 1111111111, 222222222, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1, 'florist','normal'),
(1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','loses'),
(1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','loses');
(1111, 'Missing', NULL, 'MISSING MAN', 'Anton', 'THE SPACE, UNIVERSE FAR AWAY', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','normal'),
(1112, 'Trash', NULL, 'GARBAGE MAN', 'Unknown name', 'NEW YORK CITY, UNDERGROUND', 'Gotham', 46460, 1111111111, 222222222, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5, util.VN_CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, 0, 1, 0, NULL, 1, 0, NULL, 0, 1, 'others','normal');
INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`)
SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'GOTHAM', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, util.VN_CURDATE(), 1
@ -638,7 +630,7 @@ INSERT INTO `vn`.`invoiceOutTax` (`invoiceOutFk`, `taxableBase`, `vat`, `pgcFk`)
(4, 8.07, 0.81, 4770000010),
(5, 8.07, 0.81, 4770000010);
INSERT INTO `vn`.`expense`(`id`, `name`, `isWithheld`)
INSERT INTO `vn`.`expence`(`id`, `name`, `isWithheld`)
VALUES
(2000000000, 'Inmovilizado pendiente', 0),
(2000000001, 'Compra de bienes de inmovilizado', 0),
@ -650,7 +642,7 @@ INSERT INTO `vn`.`expense`(`id`, `name`, `isWithheld`)
(7050000000, 'Prestacion de servicios', 1);
INSERT INTO `vn`.`invoiceOutExpense`(`id`, `invoiceOutFk`, `amount`, `expenseFk`, `created`)
INSERT INTO `vn`.`invoiceOutExpence`(`id`, `invoiceOutFk`, `amount`, `expenceFk`, `created`)
VALUES
(1, 1, 813.06, 2000000000, util.VN_CURDATE()),
(2, 1, 33.80, 4751000000, util.VN_CURDATE()),
@ -930,7 +922,7 @@ INSERT INTO `vn`.`itemFamily`(`code`, `description`)
('SER', 'Services'),
('VT', 'Sales');
INSERT INTO `vn`.`item`(`id`, `typeFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `expenseFk`,
INSERT INTO `vn`.`item`(`id`, `typeFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `expenceFk`,
`comment`, `relevancy`, `image`, `subName`, `minPrice`, `stars`, `family`, `isFloramondo`, `genericFk`, `itemPackingTypeFk`, `hasMinPrice`, `packingShelve`, `weightByPiece`)
VALUES
(1, 2, 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '1', NULL, 0, 1, 'EMB', 0, NULL, 'V', 0, 15,3),
@ -1947,7 +1939,7 @@ INSERT INTO `vn`.`ticketRequest`(`id`, `description`, `requesterFk`, `attenderFk
(4, 'Melee weapon combat first 15cm', 18, 35, 15, NULL, 1.30, NULL, NULL, 11, util.VN_CURDATE()),
(5, 'Melee weapon combat first 15cm', 18, 35, 15, 4, 1.30, 0, NULL, 18, util.VN_CURDATE());
INSERT INTO `vn`.`ticketServiceType`(`id`, `name`, `expenseFk`)
INSERT INTO `vn`.`ticketServiceType`(`id`, `name`, `expenceFk`)
VALUES
(1, 'Porte Agencia', 7001000000),
(2, 'Portes Retorno', 7001000000),
@ -2569,7 +2561,7 @@ INSERT INTO `vn`.`duaInvoiceIn`(`id`, `duaFk`, `invoiceInFk`)
(9, 9, 9),
(10, 10, 10);
INSERT INTO `vn`.`invoiceInTax` (`invoiceInFk`, `taxableBase`, `expenseFk`, `foreignValue`, `taxTypeSageFk`, `transactionTypeSageFk`)
INSERT INTO `vn`.`invoiceInTax` (`invoiceInFk`, `taxableBase`, `expenceFk`, `foreignValue`, `taxTypeSageFk`, `transactionTypeSageFk`)
VALUES
(1, 99.99, '2000000000', NULL, NULL, NULL),
(2, 999.99, '2000000000', NULL, NULL, NULL),

View File

@ -9692,7 +9692,7 @@ proc: BEGIN
`name`,
longName,
subName,
expenseFk,
expenceFk,
typeFk,
intrastatFk,
originFk,
@ -10080,7 +10080,7 @@ BEGIN
`name`,
longName,
subName,
expenseFk,
expenceFk,
typeFk,
intrastatFk,
originFk,
@ -17338,7 +17338,7 @@ BEGIN
JOIN vn.XDiario x ON x.id = mci.id
JOIN vn.supplier s ON s.id = supplierFk
JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id
JOIN vn.expense e ON e.id = iit.expenseFk
JOIN vn.expence e ON e.id = iit.expenceFk
JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk
LEFT JOIN tmp.invoiceDua id ON id.id = mci.id
JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase
@ -17441,7 +17441,7 @@ BEGIN
i.serial COLLATE utf8mb3_unicode_ci serial,
i.supplierFk,
i.issued,
IF(expenseFkDeductible, FALSE, i.isVatDeductible) isVatDeductible,
IF(expenceFkDeductible, FALSE, i.isVatDeductible) isVatDeductible,
IF(c.code = 'EUR', '',c.`code`) currencyFk
FROM vn.invoiceIn i
JOIN vn.currency c ON c.id = i.currencyFk
@ -17949,7 +17949,7 @@ BEGIN
e.id accountFk,
UCASE(e.name),
''
FROM vn.expense e
FROM vn.expence e
UNION
SELECT company_getCode(vCompanyFk),
b.account,
@ -22010,7 +22010,7 @@ DROP TABLE IF EXISTS `agencyTermConfig`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `agencyTermConfig` (
`expenseFk` varchar(10) DEFAULT NULL,
`expenceFk` varchar(10) DEFAULT NULL,
`vatAccountSupported` varchar(15) DEFAULT NULL,
`vatPercentage` decimal(28,10) DEFAULT NULL,
`transaction` varchar(50) DEFAULT NULL
@ -29097,19 +29097,19 @@ SET character_set_client = utf8;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `expense`
-- Table structure for table `expence`
--
DROP TABLE IF EXISTS `expense`;
DROP TABLE IF EXISTS `expence`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expense` (
CREATE TABLE `expence` (
`id` varchar(10) NOT NULL,
`name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL,
`isWithheld` tinyint(4) NOT NULL DEFAULT 0,
`code` varchar(25) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `expense_UN` (`code`)
UNIQUE KEY `expence_UN` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
@ -29862,7 +29862,7 @@ CREATE TABLE `invoiceIn` (
`bookEntried` date DEFAULT NULL COMMENT 'Fecha Asiento',
`isVatDeductible` tinyint(1) NOT NULL DEFAULT 1,
`withholdingSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipos de retención SAGE',
`expenseFkDeductible` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`expenceFkDeductible` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`editorFk` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `proveedor_id` (`supplierFk`),
@ -29877,12 +29877,12 @@ CREATE TABLE `invoiceIn` (
KEY `recibida_ibfk_6` (`cplusRectificationTypeFk`),
KEY `recibida_ibfk_7` (`siiTrascendencyInvoiceInFk`),
KEY `invoiceIn_withholdingFk_idx` (`withholdingSageFk`),
KEY `invoiceIn_expenseFkDeductible_idx` (`expenseFkDeductible`),
KEY `invoiceIn_expenceFkDeductible_idx` (`expenceFkDeductible`),
KEY `invoiceIn_fk_editor` (`editorFk`),
KEY `invoiceIn_FK` (`currencyFk`),
CONSTRAINT `invoiceInCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_FK` FOREIGN KEY (`currencyFk`) REFERENCES `currency` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_expenseFkDeductible` FOREIGN KEY (`expenseFkDeductible`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_expenceFkDeductible` FOREIGN KEY (`expenceFkDeductible`) REFERENCES `expence` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `invoiceIn_ibfk_3` FOREIGN KEY (`cplusSubjectOpFk`) REFERENCES `cplusSubjectOp` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceIn_ibfk_4` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE,
@ -30283,7 +30283,7 @@ CREATE TABLE `invoiceInSage` (
`taxTypeSageFk` smallint(6) NOT NULL,
`transactionTypeSageFk` tinyint(4) NOT NULL,
`isService` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Para diferenciar producto de servicio',
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`withholdingSageFk` smallint(6) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `invoiceInSafe_unique` (`taxClassFk`,`invoiceInSerialFk`,`isService`,`withholdingSageFk`),
@ -30292,8 +30292,8 @@ CREATE TABLE `invoiceInSage` (
KEY `invoiceInSage_invoiceInSerialFk` (`invoiceInSerialFk`),
KEY `invoiceInSage_taxTypeSageFk` (`taxTypeSageFk`),
KEY `invoiceInSage_transactionTypeSageFk` (`transactionTypeSageFk`),
KEY `invoiceInSage_idx` (`expenseFk`),
CONSTRAINT `invoiceInSage_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
KEY `invoiceInSage_idx` (`expenceFk`),
CONSTRAINT `invoiceInSage_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_invoiceInSerialFk` FOREIGN KEY (`invoiceInSerialFk`) REFERENCES `invoiceInSerial` (`code`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_taxClassFk` FOREIGN KEY (`taxClassFk`) REFERENCES `taxClass` (`code`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInSage_taxTypeSageFk` FOREIGN KEY (`taxTypeSageFk`) REFERENCES `sage`.`TiposIva` (`CodigoIva`) ON UPDATE CASCADE,
@ -30334,7 +30334,7 @@ CREATE TABLE `invoiceInTax` (
`invoiceInFk` mediumint(8) unsigned NOT NULL,
`taxCodeFk` int(10) DEFAULT NULL,
`taxableBase` decimal(10,2) NOT NULL,
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`foreignValue` decimal(10,2) DEFAULT NULL,
`taxTypeSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipo de IVA SAGE',
`transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Tipo de transacción SAGE',
@ -30345,9 +30345,9 @@ CREATE TABLE `invoiceInTax` (
KEY `recibida_iva_ibfk_2` (`taxCodeFk`),
KEY `recibida_iva_taxTypeSageFk` (`taxTypeSageFk`),
KEY `invoiceInTax_transactionTypeSageFk_idx` (`transactionTypeSageFk`),
KEY `invoiceInTax_idx` (`expenseFk`),
KEY `invoiceInTax_idx` (`expenceFk`),
KEY `invoiceInTax_fk_editor` (`editorFk`),
CONSTRAINT `invoiceInTax_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInTax_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE,
CONSTRAINT `invoiceInTax_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `invoiceInTax_ibfk_5` FOREIGN KEY (`invoiceInFk`) REFERENCES `invoiceIn` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceInTax_transactionTypeSageFk` FOREIGN KEY (`transactionTypeSageFk`) REFERENCES `sage`.`TiposTransacciones` (`CodigoTransaccion`) ON UPDATE CASCADE,
@ -30615,23 +30615,23 @@ CREATE TABLE `invoiceOutConfig` (
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `invoiceOutExpense`
-- Table structure for table `invoiceOutExpence`
--
DROP TABLE IF EXISTS `invoiceOutExpense`;
DROP TABLE IF EXISTS `invoiceOutExpence`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceOutExpense` (
CREATE TABLE `invoiceOutExpence` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoiceOutFk` int(10) unsigned NOT NULL,
`amount` decimal(10,2) NOT NULL DEFAULT 0.00,
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`created` timestamp NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
KEY `invoiceOutExpense_FK_1_idx` (`invoiceOutFk`),
KEY `invoiceOutExpense_expenseFk_idx` (`expenseFk`),
CONSTRAINT `invoiceOutExpense_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceOutExpense_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
KEY `invoiceOutExpence_FK_1_idx` (`invoiceOutFk`),
KEY `invoiceOutExpence_expenceFk_idx` (`expenceFk`),
CONSTRAINT `invoiceOutExpence_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `invoiceOut` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `invoiceOutExpence_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Desglosa la base imponible de una factura en funcion del tipo de gasto/venta';
/*!40101 SET character_set_client = @saved_cs_client */;
@ -30694,7 +30694,7 @@ CREATE TABLE `invoiceOutTaxConfig` (
`taxTypeSageFk` smallint(6) DEFAULT NULL,
`transactionTypeSageFk` tinyint(4) DEFAULT NULL,
`isService` tinyint(1) DEFAULT 0,
`expenseFk` varchar(10) DEFAULT NULL,
`expenceFk` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `invoiceOutTaxConfig_FK` (`taxClassCodeFk`),
KEY `invoiceOutTaxConfig_FK_1` (`taxTypeSageFk`),
@ -30737,7 +30737,7 @@ CREATE TABLE `item` (
`description` varchar(1000) DEFAULT NULL,
`density` int(11) NOT NULL DEFAULT 167 COMMENT 'Almacena la densidad en kg/m3 para el calculo de los portes, si no se especifica se pone por defecto la del tipo en un trigger',
`relevancy` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'La web ordena de forma descendiente por este campo para mostrar los artículos',
`expenseFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '7001000000',
`expenceFk` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL DEFAULT '7001000000',
`isActive` tinyint(1) NOT NULL DEFAULT 1,
`longName` varchar(50) DEFAULT NULL,
`subName` varchar(50) DEFAULT NULL,
@ -30792,11 +30792,11 @@ CREATE TABLE `item` (
KEY `item_size_IDX` (`size`) USING BTREE,
KEY `item_size_IDX2` (`longName`) USING BTREE,
KEY `item_lastUsed_IDX` (`lastUsed`) USING BTREE,
KEY `item_expenseFk_idx` (`expenseFk`),
KEY `item_expenceFk_idx` (`expenceFk`),
KEY `item_fk_editor` (`editorFk`),
CONSTRAINT `item_FK` FOREIGN KEY (`genericFk`) REFERENCES `item` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `item_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `itemType` (`id`),
CONSTRAINT `item_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE,
CONSTRAINT `item_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE,
CONSTRAINT `item_family` FOREIGN KEY (`family`) REFERENCES `itemFamily` (`code`) ON UPDATE CASCADE,
CONSTRAINT `item_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`),
CONSTRAINT `item_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `origin` (`id`) ON UPDATE CASCADE,
@ -40606,10 +40606,10 @@ DROP TABLE IF EXISTS `ticketServiceType`;
CREATE TABLE `ticketServiceType` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
`expenseFk` varchar(10) NOT NULL DEFAULT '7050000000',
`expenceFk` varchar(10) NOT NULL DEFAULT '7050000000',
PRIMARY KEY (`id`),
KEY `ticketServiceType_expenseFk_idx` (`expenseFk`),
CONSTRAINT `ticketServiceType_expenseFk` FOREIGN KEY (`expenseFk`) REFERENCES `expense` (`id`) ON UPDATE CASCADE
KEY `ticketServiceType_expenceFk_idx` (`expenceFk`),
CONSTRAINT `ticketServiceType_expenceFk` FOREIGN KEY (`expenceFk`) REFERENCES `expence` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDBDEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Lista de los posibles servicios a elegir';
/*!40101 SET character_set_client = @saved_cs_client */;
@ -46533,7 +46533,7 @@ BEGIN
WHERE io.ref = vInvoiceRef
UNION ALL
SELECT ioe.amount
FROM invoiceOutExpense ioe
FROM invoiceOutExpence ioe
JOIN invoiceOut io ON io.id = ioe.invoiceOutFk
WHERE io.ref = vInvoiceRef
) t1;
@ -57741,7 +57741,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenseMake` */;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@ -57749,28 +57749,28 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceExpenseMake`(IN vInvoice INT)
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceExpenceMake`(IN vInvoice INT)
BEGIN
/* Inserta las partidas de gasto correspondientes a la factura
* REQUIERE tabla tmp.ticketToInvoice
* @param vInvoice Numero de factura
*/
DELETE FROM invoiceOutExpense
DELETE FROM invoiceOutExpence
WHERE invoiceOutFk = vInvoice;
INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount)
INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount)
SELECT vInvoice,
expenseFk,
expenceFk,
SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount
FROM tmp.ticketToInvoice t
JOIN sale s ON s.ticketFk = t.id
JOIN item i ON i.id = s.itemFk
GROUP BY i.expenseFk
GROUP BY i.expenceFk
HAVING amount != 0;
INSERT INTO invoiceOutExpense(invoiceOutFk, expenseFk, amount)
INSERT INTO invoiceOutExpence(invoiceOutFk, expenceFk, amount)
SELECT vInvoice,
tst.expenseFk,
tst.expenceFk,
SUM(ROUND(ts.quantity * ts.price ,2)) amount
FROM tmp.ticketToInvoice t
JOIN ticketService ts ON ts.ticketFk = t.id
@ -58125,7 +58125,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInTax_getFromEntries`(IN vId
BEGIN
DECLARE vRate DOUBLE DEFAULT 1;
DECLARE vDated DATE;
DECLARE vExpenseFk VARCHAR(10);
DECLARE vExpenceFk VARCHAR(10);
SELECT MAX(rr.dated) INTO vDated
FROM referenceRate rr
@ -58139,8 +58139,8 @@ BEGIN
WHERE dated = vDated;
END IF;
SELECT id INTO vExpenseFk
FROM vn.expense
SELECT id INTO vExpenceFk
FROM vn.expence
WHERE `name` = 'Adquisición mercancia Extracomunitaria'
GROUP BY id
LIMIT 1;
@ -58148,10 +58148,10 @@ BEGIN
DELETE FROM invoiceInTax
WHERE invoiceInFk = vId;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, foreignValue, taxTypeSageFk, transactionTypeSageFk)
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, foreignValue, taxTypeSageFk, transactionTypeSageFk)
SELECT ii.id,
SUM(b.buyingValue * b.quantity) / IFNULL(vRate,1) taxableBase,
vExpenseFk,
vExpenceFk,
IF(ii.currencyFk = 1,NULL,SUM(b.buyingValue * b.quantity )) divisa,
taxTypeSageFk,
transactionTypeSageFk
@ -58188,7 +58188,7 @@ BEGIN
SELECT ii.bookEntried,
iit.foreignValue,
ii.companyFk,
ii.expenseFkDeductible,
ii.expenceFkDeductible,
iit.taxableBase,
iit.transactionTypeSageFk,
ii.serial,
@ -58218,8 +58218,8 @@ BEGIN
cit.id invoicesCount,
e.code,
e.isWithheld,
e.id expenseFk,
e.name expenseName
e.id expenceFk,
e.name expenceName
FROM invoiceIn ii
JOIN supplier s ON s.id = ii.supplierFk
LEFT JOIN province p ON p.id = s.provinceFk
@ -58231,7 +58231,7 @@ BEGIN
JOIN siiTypeInvoiceIn cit ON cit.id = ii.siiTypeInvoiceInFk
LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id
LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk
LEFT JOIN expense e ON e.id = iit.expenseFk
LEFT JOIN expence e ON e.id = iit.expenceFk
LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
LEFT JOIN sage.taxType tt ON tt.id = ti.CodigoIva
WHERE ii.id = vSelf;
@ -58286,7 +58286,7 @@ BEGIN
empresa_id)
SELECT vBookNumber ASIEN,
tii.bookEntried FECHA,
IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenseFk),tii.expenseFk) SUBCTA,
IF(tii.isWithheld, LPAD(RIGHT(tii.supplierAccount, 5), 10, tii.expenceFk),tii.expenceFk) SUBCTA,
tii.supplierAccount CONTRA,
IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE,
IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER,
@ -58301,7 +58301,7 @@ BEGIN
tii.companyFk empresa_id
FROM tInvoiceIn tii
WHERE tii.code IS NULL OR tii.code <> 'suplido'
GROUP BY tii.expenseFk;
GROUP BY tii.expenceFk;
-- Líneas de IVA
INSERT INTO XDiario(
@ -58335,11 +58335,11 @@ BEGIN
empresa_id)
SELECT vBookNumber ASIEN,
tii.bookEntried FECHA,
IF(tii.expenseFkDeductible>0, tii.expenseFkDeductible, tii.CuentaIvaSoportado) SUBCTA,
IF(tii.expenceFkDeductible>0, tii.expenceFkDeductible, tii.CuentaIvaSoportado) SUBCTA,
tii.supplierAccount CONTRA,
SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100, 2)) EURODEBE,
SUM(tii.taxableBase) BASEEURO,
GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO,
GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO,
vSelf FACTURA,
tii.PorcentajeIva IVA,
IF(tii.isUeeMember AND eWithheld.id IS NULL, '', '*') AUXILIAR,
@ -58365,13 +58365,13 @@ BEGIN
LEFT JOIN (
SELECT e.id
FROM tInvoiceIn tii
JOIN expense e ON e.id = tii.expenseFk
JOIN expence e ON e.id = tii.expenceFk
WHERE e.isWithheld
LIMIT 1
) eWithheld ON TRUE
WHERE tii.taxTypeSageFk IS NOT NULL
AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21'))
GROUP BY tii.PorcentajeIva, tii.expenseFk;
GROUP BY tii.PorcentajeIva, tii.expenceFk;
-- Línea iva inversor sujeto pasivo
INSERT INTO XDiario(
@ -58408,7 +58408,7 @@ BEGIN
tii.supplierAccount CONTRA,
SUM(ROUND(tii.PorcentajeIva * tii.taxableBase / 100,2)) EUROHABER,
ROUND(SUM(tii.taxableBase),2) BASEEURO,
GROUP_CONCAT(DISTINCT tii.expenseName SEPARATOR ', ') CONCEPTO,
GROUP_CONCAT(DISTINCT tii.expenceName SEPARATOR ', ') CONCEPTO,
vSelf FACTURA,
tii.PorcentajeIva IVA,
'*' AUXILIAR,
@ -58436,7 +58436,7 @@ BEGIN
AND NOT(tii.isVies
AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk
AND tii.taxCode = 'nonTaxable')
GROUP BY tii.PorcentajeIva, tii.expenseFk;
GROUP BY tii.PorcentajeIva, tii.expenceFk;
-- Actualización del registro original
UPDATE invoiceIn ii
@ -58509,14 +58509,14 @@ BEGIN
FROM ticket
WHERE refFk = vInvoiceRef;
CALL invoiceExpenseMake(vInvoiceFk);
CALL invoiceExpenceMake(vInvoiceFk);
CALL invoiceTaxMake(vInvoiceFk,vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) AS total
FROM invoiceOutExpense
FROM invoiceOutExpence
WHERE invoiceOutFk = vInvoiceFk
) base
JOIN (
@ -58552,7 +58552,7 @@ BEGIN
* param vInvoice factura_id
*/
DECLARE vBookNumber INT;
DECLARE vExpenseConcept VARCHAR(50);
DECLARE vExpenceConcept VARCHAR(50);
DECLARE vSpainCountryFk INT;
DECLARE vOldBookNumber INT;
@ -58644,7 +58644,7 @@ BEGIN
SELECT
vBookNumber AS ASIEN,
rs.FECHA,
ioe.expenseFk AS SUBCTA,
ioe.expenceFk AS SUBCTA,
rs.clientBookingAccount AS CONTRA,
ioe.amount AS EUROHABER,
rs.Concept AS CONCEPTO,
@ -58652,13 +58652,13 @@ BEGIN
rs.FECHA_OP,
rs.companyFk AS empresa_id
FROM rs
JOIN invoiceOutExpense ioe
JOIN invoiceOutExpence ioe
WHERE ioe.invoiceOutFk = vInvoice;
SELECT GROUP_CONCAT(`name` SEPARATOR ',')
INTO vExpenseConcept
FROM expense e
JOIN invoiceOutExpense ioe ON ioe.expenseFk = e.id
INTO vExpenceConcept
FROM expence e
JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id
WHERE ioe.invoiceOutFk = vInvoice;
-- Lineas de IVA
@ -58701,7 +58701,7 @@ BEGIN
rs.clientBookingAccount AS CONTRA,
iot.vat AS EUROHABER,
iot.taxableBase AS BASEEURO,
CONCAT(vExpenseConcept,' : ',rs.Concept) AS CONCEPTO,
CONCAT(vExpenceConcept,' : ',rs.Concept) AS CONCEPTO,
rs.invoiceNum AS FACTURA,
IF(pe2.equFk,0,pgc.rate) AS IVA,
IF(pe2.equFk,0,pgce.rate) AS RECEQUIV,
@ -58844,7 +58844,7 @@ DELIMITER ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpense` */;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutTaxAndExpence` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
@ -58852,7 +58852,7 @@ DELIMITER ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutTaxAndExpense`()
CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutTaxAndExpence`()
BEGIN
/* Para tickets ya facturados, vuelve a repetir el proceso de facturación.
@ -58906,7 +58906,7 @@ BEGIN
FROM ticket
WHERE refFk = vInvoiceRef;
CALL invoiceExpenseMake(vInvoice);
CALL invoiceExpenceMake(vInvoice);
CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea);
FETCH rs INTO vInvoice ,vInvoiceRef;
@ -59140,13 +59140,13 @@ BEGIN
INSERT INTO ticketTracking(stateFk,ticketFk,workerFk)
SELECT * FROM tmp.updateInter;
CALL invoiceExpenseMake(vNewInvoiceId);
CALL invoiceExpenceMake(vNewInvoiceId);
CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
UPDATE invoiceOut io
JOIN (
SELECT SUM(amount) total
FROM invoiceOutExpense
FROM invoiceOutExpence
WHERE invoiceOutFk = vNewInvoiceId
) base
JOIN (
@ -59183,15 +59183,15 @@ BEGIN
SET @vTaxableBaseServices := 0.00;
SET @vTaxCodeGeneral := NULL;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
@vTaxableBaseServices,
sub.expenseFk,
sub.expenceFk,
sub.taxTypeSageFk,
sub.transactionTypeSageFk
FROM (
SELECT @vTaxableBaseServices := SUM(tst.taxableBase) taxableBase,
i.expenseFk,
i.expenceFk,
i.taxTypeSageFk,
i.transactionTypeSageFk,
@vTaxCodeGeneral := i.taxClassCodeFk
@ -59201,11 +59201,11 @@ BEGIN
HAVING taxableBase
) sub;
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenseFk, taxTypeSageFk, transactionTypeSageFk)
INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, taxTypeSageFk, transactionTypeSageFk)
SELECT vNewInvoiceInFk,
SUM(tt.taxableBase) - IF(tt.code = @vTaxCodeGeneral,
@vTaxableBaseServices, 0) taxableBase,
i.expenseFk,
i.expenceFk,
i.taxTypeSageFk ,
i.transactionTypeSageFk
FROM tmp.ticketTax tt

View File

@ -199,6 +199,5 @@
"You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets",
"Try again": "Try again",
"keepPrice": "keepPrice",
"Cannot past travels with entries": "Cannot past travels with entries",
"It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}"
"Cannot past travels with entries": "Cannot past travels with entries"
}

View File

@ -328,6 +328,5 @@
"User disabled": "Usuario desactivado",
"The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima",
"quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima",
"Cannot past travels with entries": "No se pueden pasar envíos con entradas",
"It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}"
}
"Cannot past travels with entries": "No se pueden pasar envíos con entradas"
}

View File

@ -1,4 +1,3 @@
const NotFoundError = require('vn-loopback/util/not-found-error');
module.exports = Self => {
Self.remoteMethod('test', {
@ -10,8 +9,7 @@ module.exports = Self => {
});
Self.test = async function() {
const connector = await Self.getLinker();
if (!connector) throw new NotFoundError('Linker not configured');
let connector = await Self.getSynchronizer();
await connector.test();
};
};

View File

@ -26,46 +26,24 @@ module.exports = Self => {
});
Self.sync = async function(userName, password, force, options) {
const models = Self.app.models;
const myOptions = {};
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
};
const models = Self.app.models;
const user = await models.VnUser.findOne({
fields: ['id', 'password'],
where: {name: userName}
}, myOptions);
try {
const user = await models.VnUser.findOne({
fields: ['id', 'password'],
where: {name: userName}
}, myOptions);
if (user && password && !await user.hasPassword(password))
throw new ForbiddenError('Wrong password');
if (user && password && !await user.hasPassword(password))
throw new ForbiddenError('Wrong password');
const isSync = !await models.UserSync.exists(userName, myOptions);
const isSync = !await models.UserSync.exists(userName, myOptions);
if (!force && isSync && user) {
if (tx) await tx.rollback();
return;
}
await Self.rawSql(`
SELECT id
FROM account.user
WHERE id = ?
FOR UPDATE`, [user.id], myOptions);
await models.AccountConfig.syncUser(userName, password);
await models.UserSync.destroyById(userName, myOptions);
if (tx) await tx.commit();
} catch (err) {
if (tx) await tx.rollback();
throw err;
}
if (!force && isSync && user) return;
await models.AccountConfig.syncUser(userName, password);
await models.UserSync.destroyById(userName, myOptions);
};
};

View File

@ -3,14 +3,14 @@ const app = require('vn-loopback/server/server');
const UserError = require('vn-loopback/util/user-error');
module.exports = function(Self, options) {
require('../methods/account-linker/test')(Self);
require('../methods/account-synchronizer/test')(Self);
Self.once('attached', function() {
app.models.AccountConfig.addLinker(Self);
app.models.AccountConfig.addSynchronizer(Self);
});
/**
* Mixin for account linkers.
* Mixin for user synchronizers.
*
* @property {Array<Model>} $
* @property {Object} accountConfig
@ -18,12 +18,12 @@ module.exports = function(Self, options) {
*/
let Mixin = {
/**
* Initalizes the linker.
* Initalizes the synchronizer.
*/
async init() {},
/**
* Deinitalizes the linker.
* Deinitalizes the synchronizer.
*/
async deinit() {},
@ -57,7 +57,7 @@ module.exports = function(Self, options) {
async syncRoles() {},
/**
* Tests linker configuration.
* Tests synchronizer configuration.
*/
async test() {
try {

View File

@ -3,85 +3,94 @@ const models = require('vn-loopback/server/server').models;
module.exports = Self => {
Object.assign(Self, {
linkers: [],
synchronizers: [],
addLinker(linker) {
this.linkers.push(linker);
addSynchronizer(synchronizer) {
this.synchronizers.push(synchronizer);
},
async initEngine() {
const accountConfig = await Self.findOne({
async getInstance() {
let instance = await Self.findOne({
fields: ['homedir', 'shell', 'idBase']
});
const mailConfig = await models.MailConfig.findOne({
fields: ['domain']
});
const linkers = [];
for (const Linker of Self.linkers) {
const linker = await Linker.getLinker();
if (!linker) continue;
Object.assign(linker, {accountConfig});
await linker.init();
linkers.push(linker);
}
Object.assign(accountConfig, {
linkers,
domain: mailConfig.domain
});
return {
accountConfig,
linkers
};
},
async deinitEngine(engine) {
for (const linker of engine.linkers)
await linker.deinit();
},
async syncUser(userName, password) {
const engine = await Self.initEngine();
try {
await Self.syncUserBase(engine, userName, password, true);
} finally {
await Self.deinitEngine(engine);
}
await instance.synchronizerInit();
return instance;
},
async syncUsers() {
const engine = await Self.initEngine();
let usersToSync = new Set();
for (const linker of engine.linkers)
await linker.getUsers(usersToSync);
let instance = await Self.getInstance();
let usersToSync = await instance.synchronizerGetUsers();
usersToSync = Array.from(usersToSync.values())
.sort((a, b) => a.localeCompare(b));
for (let userName of usersToSync) {
try {
// eslint-disable-next-line no-console
console.log(`Synchronizing user '${userName}'`);
await Self.syncUserBase(engine, userName);
// eslint-disable-next-line no-console
await instance.synchronizerSyncUser(userName);
console.log(` -> User '${userName}' sinchronized`);
} catch (err) {
// eslint-disable-next-line no-console
console.error(` -> User '${userName}' synchronization error:`, err.message);
}
}
await Self.deinitEngine(engine);
await instance.synchronizerDeinit();
await Self.syncRoles();
},
async syncUserBase(engine, userName, password, syncGroups) {
async syncUser(userName, password) {
let instance = await Self.getInstance();
try {
await instance.synchronizerSyncUser(userName, password, true);
} finally {
await instance.synchronizerDeinit();
}
},
async syncRoles() {
let instance = await Self.getInstance();
try {
await instance.synchronizerSyncRoles();
} finally {
await instance.synchronizerDeinit();
}
},
async getSynchronizer() {
return await Self.findOne();
}
});
Object.assign(Self.prototype, {
async synchronizerInit() {
let mailConfig = await models.MailConfig.findOne({
fields: ['domain']
});
let synchronizers = [];
for (let Synchronizer of Self.synchronizers) {
let synchronizer = await Synchronizer.getSynchronizer();
if (!synchronizer) continue;
Object.assign(synchronizer, {
accountConfig: this
});
await synchronizer.init();
synchronizers.push(synchronizer);
}
Object.assign(this, {
synchronizers,
domain: mailConfig.domain
});
},
async synchronizerDeinit() {
for (let synchronizer of this.synchronizers)
await synchronizer.deinit();
},
async synchronizerSyncUser(userName, password, syncGroups) {
if (!userName) return;
userName = userName.toLowerCase();
@ -89,7 +98,7 @@ module.exports = Self => {
if (['administrator', 'root'].indexOf(userName) >= 0)
return;
const user = await models.VnUser.findOne({
let user = await models.VnUser.findOne({
where: {name: userName},
fields: [
'id',
@ -121,28 +130,27 @@ module.exports = Self => {
]
});
const info = {
let info = {
user,
hasAccount: false
};
if (user) {
const exists = await models.Account.exists(user.id);
const {accountConfig} = engine;
let exists = await models.Account.exists(user.id);
Object.assign(info, {
hasAccount: user.active && exists,
corporateMail: `${userName}@${accountConfig.domain}`,
uidNumber: accountConfig.idBase + user.id
corporateMail: `${userName}@${this.domain}`,
uidNumber: this.idBase + user.id
});
}
const errs = [];
let errs = [];
for (const linker of engine.linkers) {
for (let synchronizer of this.synchronizers) {
try {
await linker.syncUser(userName, info, password);
await synchronizer.syncUser(userName, info, password);
if (syncGroups)
await linker.syncUserGroups(userName, info);
await synchronizer.syncUserGroups(userName, info);
} catch (err) {
errs.push(err);
}
@ -151,16 +159,18 @@ module.exports = Self => {
if (errs.length) throw errs[0];
},
async syncRoles() {
const engine = await Self.initEngine();
try {
await Self.rawSql(`CALL account.role_sync`);
async synchronizerGetUsers() {
let usersToSync = new Set();
for (const linker of engine.linkers)
await linker.syncRoles();
} finally {
await Self.deinitEngine(engine);
}
for (let synchronizer of this.synchronizers)
await synchronizer.getUsers(usersToSync);
return usersToSync;
},
async synchronizerSyncRoles() {
for (let synchronizer of this.synchronizers)
await synchronizer.syncRoles();
}
});
};

View File

@ -7,7 +7,7 @@ const nthash = require('smbhash').nthash;
module.exports = Self => {
const shouldSync = process.env.NODE_ENV !== 'test';
Self.getLinker = async function() {
Self.getSynchronizer = async function() {
return await Self.findOne({
fields: [
'server',
@ -24,7 +24,6 @@ module.exports = Self => {
this.client = ldap.createClient({
url: this.server
});
this.client.on('error', () => {});
await this.client.bind(this.rdn, this.password);
},

View File

@ -7,7 +7,7 @@
}
},
"mixins": {
"AccountLinker": {}
"AccountSynchronizer": {}
},
"properties": {
"id": {

View File

@ -1,6 +1,6 @@
module.exports = Self => {
Self.getLinker = async function() {
Self.getSynchronizer = async function() {
let NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV || NODE_ENV == 'development')
return null;
@ -45,7 +45,6 @@ module.exports = Self => {
}
if (!isUpdatable) {
// eslint-disable-next-line no-console
console.warn(`RoleConfig.syncUser(): User '${userName}' cannot be updated, not managed by me`);
return;
}
@ -83,7 +82,6 @@ module.exports = Self => {
[mysqlUser, this.userHost]);
} catch (err) {
if (err.code == 'ER_REVOKE_GRANTS')
// eslint-disable-next-line no-console
console.warn(`${err.code}: ${err.sqlMessage}: ${err.sql}`);
else
throw err;

View File

@ -7,7 +7,7 @@
}
},
"mixins": {
"AccountLinker": {}
"AccountSynchronizer": {}
},
"properties": {
"id": {

View File

@ -9,7 +9,7 @@ module.exports = Self => {
Self.observe(hook, async() => {
try {
await Self.rawSql(`
CREATE DEFINER = CURRENT_ROLE EVENT account.role_sync
CREATE EVENT account.role_sync
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 SECOND
DO CALL role_sync;
`);

View File

@ -13,7 +13,7 @@ const UserAccountControlFlags = {
module.exports = Self => {
const shouldSync = process.env.NODE_ENV !== 'test';
Self.getLinker = async function() {
Self.getSynchronizer = async function() {
return await Self.findOne({
fields: [
'host',
@ -39,7 +39,6 @@ module.exports = Self => {
url: `ldaps://${this.adController}:636`,
tlsOptions: {rejectUnauthorized: this.verifyCert}
});
adClient.on('error', () => {});
await adClient.bind(bindDn, this.adPassword);
Object.assign(this, {
adClient,

View File

@ -7,7 +7,7 @@
}
},
"mixins": {
"AccountLinker": {}
"AccountSynchronizer": {}
},
"properties": {
"id": {

View File

@ -25,15 +25,7 @@
"type": "number"
},
"ip": {
"type": "string"
},
"userName": {
"type": "string"
},
"owner": {
"type": "boolean",
"required": true,
"default": true
"type": "string"
}
},
"relations": {

View File

@ -2,7 +2,7 @@
const app = require('vn-loopback/server/server');
module.exports = Self => {
Self.getLinker = async function() {
Self.getSynchronizer = async function() {
return await Self.findOne({fields: ['id']});
};

View File

@ -7,7 +7,7 @@
}
},
"mixins": {
"AccountLinker": {}
"AccountSynchronizer": {}
},
"properties": {
"id": {
@ -16,3 +16,4 @@
}
}
}

View File

@ -68,6 +68,7 @@
Deactivate user
</vn-item>
<vn-item
ng-if="$ctrl.user.active"
ng-click="syncUser.show()"
name="synchronizeUser"
vn-acl="it"
@ -165,7 +166,7 @@
vn-id="syncUser"
on-accept="$ctrl.onSync()"
on-close="$ctrl.onSyncClose()">
<tpl-title translate>
<tpl-title ng-translate>
Do you want to synchronize user?
</tpl-title>
<tpl-body>

View File

@ -16,5 +16,5 @@ columns:
bookEntried: book entried
isVatDeductible: is VAT deductible
withholdingSageFk: withholding
expenseFkDeductible: expense deductible
expenceFkDeductible: expence deductible
editorFk: editor

View File

@ -16,5 +16,5 @@ columns:
bookEntried: fecha asiento
isVatDeductible: impuesto deducible
withholdingSageFk: código de retención
expenseFkDeductible: gasto deducible
expenceFkDeductible: gasto deducible
editorFk: editor

View File

@ -4,7 +4,7 @@ columns:
invoiceInFk: invoice in
taxCodeFk: tax
taxableBase: taxable base
expenseFk: expense
expenceFk: expence
foreignValue: foreign amount
taxTypeSageFk: tax type
transactionTypeSageFk: transaction type

View File

@ -4,7 +4,7 @@ columns:
invoiceInFk: factura recibida
taxCodeFk: código IVA
taxableBase: base imponible
expenseFk: código gasto
expenceFk: código gasto
foreignValue: importe divisa
taxTypeSageFk: código impuesto
transactionTypeSageFk: código transacción

View File

@ -146,7 +146,7 @@ module.exports = Self => {
ii.docFk AS dmsFk,
dm.file,
ii.supplierFk,
ii.expenseFkDeductible deductibleExpenseFk,
ii.expenceFkDeductible deductibleExpenseFk,
s.name AS supplierName,
s.account,
SUM(iid.amount) AS amount,

View File

@ -29,18 +29,15 @@ module.exports = Self => {
SELECT iit.*,
SUM(iidd.amount) totalDueDay
FROM vn.invoiceIn ii
LEFT JOIN (
SELECT SUM(iit.taxableBase) totalTaxableBase,
CAST(
SUM(IFNULL(iit.taxableBase * (1 + (ti.PorcentajeIva / 100)), iit.taxableBase))
AS DECIMAL(10, 2)
) totalVat
LEFT JOIN (SELECT SUM(iit.taxableBase) totalTaxableBase,
CAST(SUM(iit.taxableBase * (1 + (ti.PorcentajeIva / 100))) AS DECIMAL(10,2)) totalVat
FROM vn.invoiceInTax iit
LEFT JOIN sage.TiposIva ti ON ti.CodigoIva = iit.taxTypeSageFk
WHERE iit.invoiceInFk = ?
) iit ON TRUE
WHERE iit.invoiceInFk = ?) iit ON TRUE
LEFT JOIN vn.invoiceInDueDay iidd ON iidd.invoiceInFk = ii.id
WHERE ii.id = ?`, [id, id]);
WHERE
ii.id = ?`, [id, id]);
return result;
};
};

View File

@ -112,7 +112,7 @@ module.exports = Self => {
{
relation: 'taxTypeSage',
scope: {
fields: ['vat', 'rate']
fields: ['vat']
}
}]
}

View File

@ -19,7 +19,10 @@
"type": "number"
},
"expenseFk": {
"type": "number"
"type": "number",
"mysql": {
"columnName": "expenceFk"
}
},
"created": {
"type": "date"

View File

@ -51,7 +51,7 @@
"deductibleExpenseFk": {
"type": "number",
"mysql": {
"columnName": "expenseFkDeductible"
"columnName": "expenceFkDeductible"
}
}
},

View File

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

View File

@ -117,7 +117,10 @@
"description": "The item family"
},
"expenseFk": {
"type": "number"
"type": "number",
"mysql": {
"columnName": "expenceFk"
}
},
"minPrice": {
"type": "number"
@ -128,6 +131,9 @@
"nonRecycledPlastic": {
"type": "number"
},
"minQuantity": {
"type": "number"
},
"packingOut": {
"type": "number"
},

View File

@ -105,7 +105,7 @@
url="Expenses"
label="Expense"
ng-model="$ctrl.item.expenseFk"
vn-name="expense"
vn-name="expence"
initial-data="$ctrl.item.expense">
</vn-autocomplete>
</vn-horizontal>

View File

@ -151,7 +151,7 @@ describe('SalesMonitor salesFilter()', () => {
const result = await models.SalesMonitor.salesFilter(ctx, filter, options);
const firstRow = result[0];
expect(result.length).toEqual(12);
expect(result.length).toEqual(15);
expect(firstRow.alertLevel).not.toEqual(0);
await tx.rollback();

View File

@ -139,8 +139,6 @@ module.exports = Self => {
filter = mergeFilters(filter, {where});
const stmts = [];
let stmt;
stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`);
stmts.push(`SET SESSION optimizer_search_depth = 0`);
stmt = new ParameterizedSQL(`
CREATE OR REPLACE TEMPORARY TABLE tmp.filter
@ -197,7 +195,6 @@ module.exports = Self => {
stmt.merge(`GROUP BY id`);
stmt.merge(conn.makePagination(filter));
stmts.push(stmt);
stmts.push(`SET SESSION optimizer_search_depth = @_optimizer_search_depth`);
stmt = new ParameterizedSQL(`SELECT * FROM tmp.filter`);
stmt.merge(conn.makeOrderBy(filter.order));

View File

@ -54,7 +54,7 @@ module.exports = Self => {
dmsFk: firstDms.id,
}, myOptions);
const expense = await models.AgencyTermConfig.findOne(null, myOptions);
const expence = await models.AgencyTermConfig.findOne(null, myOptions);
const [taxTypeSage] = await Self.rawSql(`
SELECT IFNULL(s.taxTypeSageFk, CodigoIva) value
@ -78,7 +78,7 @@ module.exports = Self => {
await models.InvoiceInTax.create({
invoiceInFk: newInvoiceIn.id,
taxableBase: firstRow.totalPrice,
expenseFk: expense.expenseFk,
expenseFk: expence.expenceFk,
taxTypeSageFk: taxTypeSage.value,
transactionTypeSageFk: transactionTypeSage.value
}, myOptions);

View File

@ -105,7 +105,7 @@ module.exports = Self => {
}
});
filter = mergeFilters(filter, {where});
filter = mergeFilters(ctx.args.filter, {where});
let stmts = [];
let stmt;
@ -129,11 +129,9 @@ module.exports = Self => {
r.description,
am.name agencyName,
u.name AS workerUserName,
v.numberPlate AS vehiclePlateNumber,
Date_format(r.time, '%H:%i') hour
v.numberPlate AS vehiclePlateNumber
FROM route r
LEFT JOIN agencyMode am ON am.id = r.agencyModeFk
LEFT JOIN agency a ON a.id = am.agencyFk
LEFT JOIN vehicle v ON v.id = r.vehicleFk
LEFT JOIN worker w ON w.id = r.workerFk
LEFT JOIN account.user u ON u.id = w.id`

View File

@ -1,65 +0,0 @@
const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
module.exports = Self => {
Self.remoteMethodCtx('getByWorker', {
description: 'Return the routes by worker',
accessType: 'READ',
returns: {
type: ['object'],
root: true
},
http: {
path: `/getByWorker`,
verb: 'GET'
}
});
Self.getByWorker = async ctx => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const canViewAll = await models.ACL.checkAccessAcl(ctx, 'Route', 'canViewAllRoute', 'READ');
let filterGrant = {};
if (canViewAll) {
const userConfig = await models.UserConfig.getUserConfig(ctx, myOptions);
filterGrant = {
where: {'a.warehouseFk': userConfig.warehouseFk}
};
} else {
filterGrant = {
where: {'r.workerFk': userId}
};
}
const currentDate = Date.vnNew();
currentDate.setHours(0, 0, 0, 0);
const nextDay = Date.vnNew();
nextDay.setDate(currentDate.getDate() + 1);
const filter = {
where: {
and: [
{
or: [
{'r.created': currentDate},
{'r.created': nextDay}
]
}
]
},
order: [
'r.created ASC',
'r.time ASC',
'am.name ASC'
]
};
const result = await Self.filter(ctx, mergeFilters(filter, filterGrant));
return result;
};
};

View File

@ -1,7 +1,7 @@
module.exports = Self => {
Self.remoteMethod('getDeliveryPoint', {
description: 'get the deliveryPoint address',
accessType: 'READ',
accessType: 'WRITE',
accepts: {
arg: 'vehicleId',
type: 'number',

View File

@ -1,7 +1,7 @@
module.exports = Self => {
Self.remoteMethodCtx('guessPriority', {
description: 'Changes automatically the priority of the tickets in a route',
accessType: 'WRITE',
accessType: 'READ',
accepts: [{
arg: 'id',
type: 'number',
@ -15,7 +15,7 @@ module.exports = Self => {
},
http: {
path: `/:id/guessPriority`,
verb: 'PATCH'
verb: 'GET'
}
});

View File

@ -3,7 +3,7 @@ const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('insertTicket', {
description: 'Check if the ticket can be insert into the route and insert it',
accessType: 'WRITE',
accessType: 'READ',
accepts: [{
arg: 'routeId',
type: 'number',

View File

@ -1,36 +0,0 @@
const app = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('route getByWorker()', () => {
const userId = 56;
const activeCtx = {
accessToken: {userId: userId},
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
const ctx = {req: activeCtx};
beforeAll(() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
it('should return routes assigned to the worker', async() => {
const result = await app.models.Route.getByWorker(ctx);
expect(result.every(route => route.workerFk === userId)).toBe(true);
});
it('should return all routes if user has canViewAllRoute permission', async() => {
// Simular que el usuario tiene permiso para ver todas las rutas
spyOn(app.models.ACL, 'checkAccessAcl').and.returnValue(Promise.resolve(true));
const result = await app.models.Route.getByWorker(ctx);
expect(result.some(route => route.workerFk != userId)).toBe(true);
});
});

View File

@ -7,7 +7,7 @@
}
},
"properties": {
"expenseFk": {
"expenceFk": {
"type": "string",
"id": true
},

View File

@ -17,7 +17,6 @@ module.exports = Self => {
require('../methods/route/cmr')(Self);
require('../methods/route/getExternalCmrs')(Self);
require('../methods/route/downloadCmrsZip')(Self);
require('../methods/route/getByWorker')(Self);
Self.validate('kmStart', validateDistance, {
message: 'Distance must be lesser than 1000'
@ -32,5 +31,5 @@ module.exports = Self => {
const routeMaxKm = 1000;
if (routeTotalKm > routeMaxKm || this.kmStart > this.kmEnd)
err();
}
};
};

View File

@ -120,7 +120,7 @@ class Controller extends Section {
guessPriority() {
let query = `Routes/${this.$params.id}/guessPriority/`;
this.$http.patch(query).then(() => {
this.$http.get(query).then(() => {
this.vnApp.showSuccess(this.$t('Order changed'));
this.$.model.refresh();
});

View File

@ -209,6 +209,22 @@ describe('Route', () => {
});
});
describe('guessPriority()', () => {
it('should perform a GET query then call both refresh and showSuccess methods', () => {
jest.spyOn(controller.$.model, 'refresh');
jest.spyOn(controller.vnApp, 'showSuccess');
controller.$params = {id: 99};
const url = `Routes/${controller.$params.id}/guessPriority/`;
$httpBackend.expectGET(url).respond('ok');
controller.guessPriority();
$httpBackend.flush();
expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Order changed');
expect(controller.$.model.refresh).toHaveBeenCalledWith();
});
});
describe('onDrop()', () => {
it('should call the insert method when dragging a ticket number', () => {
jest.spyOn(controller, 'insert');

View File

@ -1,7 +1,6 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('deleteExpeditions', {
Self.remoteMethod('deleteExpeditions', {
description: 'Delete the selected expeditions',
accessType: 'WRITE',
accepts: [{
@ -10,59 +9,44 @@ module.exports = Self => {
required: true,
description: 'The expeditions ids to delete'
}],
http: {
path: `/deleteExpeditions`,
verb: 'POST'
},
returns: {
type: ['object'],
root: true
},
http: {
path: `/deleteExpeditions`,
verb: 'POST'
}
});
Self.deleteExpeditions = async(ctx, expeditionIds) => {
Self.deleteExpeditions = async(expeditionIds, options) => {
const models = Self.app.models;
const $t = ctx.req.__;
const notDeletedExpeditions = [];
const deletedExpeditions = [];
const myOptions = {};
let tx;
for (let expeditionId of expeditionIds) {
const filter = {
fields: [],
where: {
id: expeditionId
},
include: [
{
relation: 'agencyMode',
scope: {
fields: ['code'],
}
}
]
};
if (typeof options == 'object')
Object.assign(myOptions, options);
const expedition = await models.Expedition.findOne(filter);
const {code} = expedition.agencyMode();
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
if (code && code.toLowerCase().substring(0, 10) == 'viaexpress') {
const isDeleted = await models.ViaexpressConfig.deleteExpedition(expeditionId);
if (isDeleted === 'true') {
const deletedExpedition = await models.Expedition.destroyById(expeditionId);
deletedExpeditions.push(deletedExpedition);
} else notDeletedExpeditions.push(expeditionId);
} else {
const deletedExpedition = await models.Expedition.destroyById(expeditionId);
deletedExpeditions.push(deletedExpedition);
try {
const promises = [];
for (let expeditionId of expeditionIds) {
const deletedExpedition = models.Expedition.destroyById(expeditionId, myOptions);
promises.push(deletedExpedition);
}
}
if (notDeletedExpeditions.length) {
throw new UserError(
$t(`It was not able to remove the next expeditions:`, {expeditions: notDeletedExpeditions.join()})
);
const deletedExpeditions = await Promise.all(promises);
if (tx) await tx.commit();
return deletedExpeditions;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
return deletedExpeditions;
};
};

View File

@ -2,16 +2,17 @@ const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context');
describe('ticket deleteExpeditions()', () => {
let ctx;
beforeAll(async() => {
ctx = {
const activeCtx = {
accessToken: {userId: 9},
req: {
headers: {origin: 'http://localhost'}
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: ctx
active: activeCtx
});
});
@ -22,7 +23,7 @@ describe('ticket deleteExpeditions()', () => {
const options = {transaction: tx};
const expeditionIds = [12, 13];
const result = await models.Expedition.deleteExpeditions(ctx, expeditionIds, options);
const result = await models.Expedition.deleteExpeditions(expeditionIds, options);
expect(result.length).toEqual(2);

View File

@ -68,7 +68,7 @@ describe('ticket filter()', () => {
const filter = {};
const result = await models.Ticket.filter(ctx, filter, options);
expect(result.length).toEqual(6);
expect(result.length).toEqual(9);
await tx.rollback();
} catch (e) {

View File

@ -9,7 +9,7 @@ describe('ticket getSalesPersonMana()', () => {
const mana = await models.Ticket.getSalesPersonMana(1, options);
expect(mana).toEqual(124);
expect(mana).toEqual(73);
await tx.rollback();
} catch (e) {

View File

@ -20,9 +20,6 @@
},
"counter": {
"type": "number"
},
"externalId": {
"type": "string"
}
},
"relations": {
@ -33,7 +30,7 @@
},
"agencyMode": {
"type": "belongsTo",
"model": "AgencyMode",
"model": "agency-mode",
"foreignKey": "agencyModeFk"
},
"worker": {

View File

@ -18,7 +18,7 @@
"expenseFk": {
"type": "number",
"mysql": {
"columnName": "expenseFk"
"columnName": "expenceFk"
}
}
},

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