Merge branch 'dev' into 5836-clientDefaulterisWorker
gitea/salix/pipeline/head Build queued... Details

This commit is contained in:
Carlos Satorres 2023-07-03 09:47:43 +00:00
commit 4d03ef8f09
101 changed files with 1529 additions and 1527 deletions

View File

@ -17,7 +17,7 @@ rules:
camelcase: 0
default-case: 0
no-eq-null: 0
no-console: ["error"]
no-console: ["warn"]
no-warning-comments: 0
no-empty: [error, allowEmptyCatch: true]
complexity: 0

View File

@ -9,11 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- (Entradas -> Correo) Al cambiar el tipo de cambio enviará un correo a las personas designadas
- (General -> Históricos) Botón para ver el estado del registro en cada punto
- (General -> Históricos) Al filtar por registro se muestra todo el histórial desde que fue creado
- (Tickets -> Índice) Permite enviar varios albaranes a Docuware
### Changed
- (General -> Históricos) Los registros se muestran agrupados por usuario y entidad
- (Facturas -> Facturación global) Optimizada, generación de PDFs y notificaciones en paralelo
### Fixed
-
- (General -> Históricos) Duplicidades eliminadas
- (Facturas -> Facturación global) Solucionados fallos que paran el proceso
## [2324.01] - 2023-06-15

View File

@ -3,6 +3,7 @@ const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('renewToken', {
description: 'Checks if the token has more than renewPeriod seconds to live and if so, renews it',
accessType: 'WRITE',
accepts: [],
returns: {
type: 'Object',
@ -16,23 +17,22 @@ module.exports = Self => {
Self.renewToken = async function(ctx) {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const created = ctx.req.accessToken.created;
const tokenId = ctx.req.accessToken.id;
const token = ctx.req.accessToken;
const now = new Date();
const differenceMilliseconds = now - created;
const differenceMilliseconds = now - token.created;
const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
const accessTokenConfig = await models.AccessTokenConfig.findOne({fields: ['renewPeriod']});
const fields = ['renewPeriod', 'courtesyTime'];
const accessTokenConfig = await models.AccessTokenConfig.findOne({fields});
if (differenceSeconds <= accessTokenConfig.renewPeriod)
throw new UserError(`The renew period has not been exceeded`);
if (differenceSeconds < accessTokenConfig.renewPeriod - accessTokenConfig.courtesyTime)
throw new UserError(`The renew period has not been exceeded`, 'periodNotExceeded');
await Self.logout(tokenId);
const user = await Self.findById(userId);
await Self.logout(token.id);
const user = await Self.findById(token.userId);
const accessToken = await user.createAccessToken();
return {token: accessToken.id, created: accessToken.created};
return {id: accessToken.id, ttl: accessToken.ttl};
};
};

View File

@ -76,6 +76,6 @@ module.exports = Self => {
let loginInfo = Object.assign({password}, userInfo);
token = await Self.login(loginInfo, 'user');
return {token: token.id, created: token.created};
return {token: token.id, ttl: token.ttl};
};
};

View File

@ -16,6 +16,10 @@
"type": "number",
"required": true
},
"courtesyTime": {
"type": "number",
"required": true
},
"renewInterval": {
"type": "number",
"required": true

View File

@ -0,0 +1,22 @@
CREATE TABLE `vn`.`travelConfig` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`warehouseInFk` smallint(6) unsigned NOT NULL DEFAULT 8 COMMENT 'Warehouse de origen',
`warehouseOutFk` smallint(6) unsigned NOT NULL DEFAULT 60 COMMENT 'Warehouse destino',
`agencyFk` int(11) NOT NULL DEFAULT 1378 COMMENT 'Agencia por defecto',
`companyFk` int(10) unsigned NOT NULL DEFAULT 442 COMMENT 'Compañía por defecto',
PRIMARY KEY (`id`),
KEY `travelConfig_FK` (`warehouseInFk`),
KEY `travelConfig_FK_1` (`warehouseOutFk`),
KEY `travelConfig_FK_2` (`agencyFk`),
KEY `travelConfig_FK_3` (`companyFk`),
CONSTRAINT `travelConfig_FK` FOREIGN KEY (`warehouseInFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelConfig_FK_1` FOREIGN KEY (`warehouseOutFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelConfig_FK_2` FOREIGN KEY (`agencyFk`) REFERENCES `agencyMode` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `travelConfig_FK_3` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES
('Entry', 'addFromPackaging', 'WRITE', 'ALLOW', 'ROLE', 'production'),
('Entry', 'addFromBuy', 'WRITE', 'ALLOW', 'ROLE', 'production'),
('Supplier', 'getItemsPackaging', 'READ', 'ALLOW', 'ROLE', 'production');

View File

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

View File

@ -1,10 +1,11 @@
CREATE TABLE `salix`.`accessTokenConfig` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`renewPeriod` int(10) unsigned DEFAULT NULL,
`courtesyTime` int(10) unsigned DEFAULT NULL,
`renewInterval` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci;
INSERT IGNORE INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `renewInterval`)
INSERT IGNORE INTO `salix`.`accessTokenConfig` (`id`, `renewPeriod`, `courtesyTime`, `renewInterval`)
VALUES
(1, 21600, 300);
(1, 21600, 5, 300);

View File

@ -0,0 +1,13 @@
INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId)
VALUES
('InvoiceOut','makePdfAndNotify','WRITE','ALLOW','ROLE','invoicing'),
('InvoiceOutConfig','*','READ','ALLOW','ROLE','invoicing');
CREATE OR REPLACE TABLE `vn`.`invoiceOutConfig` (
id INT UNSIGNED auto_increment NOT NULL,
parallelism int UNSIGNED DEFAULT 1 NOT NULL,
PRIMARY KEY (id)
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb3
COLLATE=utf8mb3_unicode_ci;

View File

@ -603,6 +603,9 @@ UPDATE `vn`.`invoiceOut` SET ref = 'T3333333' WHERE id = 3;
UPDATE `vn`.`invoiceOut` SET ref = 'T4444444' WHERE id = 4;
UPDATE `vn`.`invoiceOut` SET ref = 'A1111111' WHERE id = 5;
INSERT INTO vn.invoiceOutConfig
SET parallelism = 8;
INSERT INTO `vn`.`invoiceOutTax` (`invoiceOutFk`, `taxableBase`, `vat`, `pgcFk`)
VALUES
(1, 895.76, 89.58, 4722000010),
@ -696,12 +699,12 @@ INSERT INTO `vn`.`route`(`id`, `time`, `workerFk`, `created`, `vehicleFk`, `agen
INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeFk`, `shipped`, `landed`, `clientFk`,`nickname`, `addressFk`, `refFk`, `isDeleted`, `zoneFk`, `zonePrice`, `zoneBonus`, `created`)
VALUES
(1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, 'T1111111', 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)),
(2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T1111111', 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)),
(3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T2222222', 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)),
(4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T3333333', 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH)),
(5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, 'T4444444', 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH)),
(6 , 1, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Mountain Drive Gotham', 1, 'A1111111', 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)),
(1 , 3, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Bat cave', 121, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)),
(2 , 1, 1, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 1, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)),
(3 , 1, 7, 1, 6, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -2 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)),
(4 , 3, 2, 1, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -3 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 9, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH)),
(5 , 3, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -4 MONTH), INTERVAL +1 DAY), 1104, 'Stark tower', 124, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH)),
(6 , 1, 3, 3, 3, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(DATE_ADD(util.VN_CURDATE(),INTERVAL -1 MONTH), INTERVAL +1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 10, 5, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)),
(7 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Mountain Drive Gotham', 1, NULL, 0, 3, 5, 1, util.VN_CURDATE()),
(8 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1101, 'Bat cave', 121, NULL, 0, 3, 5, 1, util.VN_CURDATE()),
(9 , NULL, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1104, 'Stark tower', 124, NULL, 0, 3, 5, 1, util.VN_CURDATE()),
@ -2569,6 +2572,26 @@ INSERT INTO `vn`.`ticketRecalc`(`ticketFk`)
CALL `vn`.`ticket_doRecalc`();
UPDATE `vn`.`ticket`
SET refFk = 'T1111111'
WHERE id IN (1,2);
UPDATE `vn`.`ticket`
SET refFk = 'T2222222'
WHERE id = 3;
UPDATE `vn`.`ticket`
SET refFk = 'T3333333'
WHERE id = 4;
UPDATE `vn`.`ticket`
SET refFk = 'T4444444'
WHERE id = 5;
UPDATE `vn`.`ticket`
SET refFk = 'A1111111'
WHERE id = 6;
INSERT INTO `vn`.`zoneAgencyMode`(`id`, `agencyModeFk`, `zoneFk`)
VALUES
(1, 1, 1),
@ -2839,7 +2862,8 @@ INSERT INTO `vn`.`workerConfig` (`id`, `businessUpdated`, `roleFk`, `payMethodFk
INSERT INTO `vn`.`ticketRefund`(`refundTicketFk`, `originalTicketFk`)
VALUES
(1, 12);
(1, 12),
(8, 10);
INSERT INTO `vn`.`deviceProductionModels` (`code`)
VALUES

View File

@ -12605,7 +12605,7 @@ BEGIN
FROM myTicket t
WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59');
CALL vn.ticketGetTotal;
CALL vn.ticketGetTotal(NULL);
SELECT v.id, IFNULL(v.landed, v.shipped) landed,
v.shipped, v.companyFk, v.nickname,
@ -47167,7 +47167,7 @@ BEGIN
ENGINE = MEMORY
SELECT vTicketId ticketFk;
CALL ticketGetTotal;
CALL ticketGetTotal(NULL);
SELECT total INTO vTotal FROM tmp.ticketTotal;
@ -58494,6 +58494,13 @@ BEGIN
DECLARE vIsCEESerial BOOL DEFAULT FALSE;
DECLARE vIsCorrectInvoiceDate BOOL;
DECLARE vMaxShipped DATE;
DECLARE vDone BOOL;
DECLARE vTicketFk INT;
DECLARE vCursor CURSOR FOR
SELECT id
FROM ticketToInvoice;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
SET vInvoiceDate = IFNULL(vInvoiceDate, util.VN_CURDATE());
@ -58579,6 +58586,20 @@ BEGIN
FROM invoiceOut
WHERE id = vNewInvoiceId;
OPEN vCursor;
l: LOOP
SET vDone = FALSE;
FETCH vCursor INTO vTicketFk;
IF vDone THEN
LEAVE l;
END IF;
CALL ticket_recalc(vTicketFk, vTaxArea);
END LOOP;
CLOSE vCursor;
UPDATE ticket t
JOIN tmp.ticketToInvoice ti ON ti.id = t.id
SET t.refFk = vNewRef;
@ -58594,10 +58615,6 @@ BEGIN
INSERT INTO ticketTracking(stateFk,ticketFk,workerFk)
SELECT * FROM tmp.updateInter;
INSERT INTO ticketLog (action, userFk, originFk, description)
SELECT 'UPDATE', account.myUser_getId(), ti.id, CONCAT('Crea factura ', vNewRef)
FROM tmp.ticketToInvoice ti;
CALL invoiceExpenceMake(vNewInvoiceId);
CALL invoiceTaxMake(vNewInvoiceId,vTaxArea);
@ -69870,7 +69887,7 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketGetTotal`()
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketGetTotal`(vTaxArea VARCHAR(25))
BEGIN
/**
* Calcula el total con IVA para un conjunto de tickets.
@ -69878,7 +69895,7 @@ BEGIN
* @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
* @return tmp.ticketTotal Total para cada ticket
*/
CALL ticket_getTax(NULL);
CALL ticket_getTax(vTaxArea);
DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal;
CREATE TEMPORARY TABLE tmp.ticketTotal
@ -70029,7 +70046,7 @@ BEGIN
AND clientFk = vClientFk
AND shipped > '2001-01-01';
CALL vn.ticketGetTotal;
CALL vn.ticketGetTotal(NULL);
SELECT c.id,
c.name as Cliente,
@ -71878,7 +71895,7 @@ proc: BEGIN
LEAVE myLoop;
END IF;
CALL ticket_recalc(vTicketFk);
CALL ticket_recalc(vTicketFk, NULL);
END LOOP;
CLOSE cCur;
@ -72334,14 +72351,14 @@ BEGIN
CALL addressTaxArea ();
IF vTaxArea > '' THEN
IF vTaxArea IS NOT NULL THEN
UPDATE tmp.addressTaxArea
SET areaFk = vTaxArea;
END IF;
/* Solo se calcula la base imponible (taxableBase) y el impuesto se calculará posteriormente
* No se debería cambiar el sistema por problemas con los decimales
*/
DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
CREATE TEMPORARY TABLE tmp.ticketTax
(PRIMARY KEY (ticketFk, code, rate))
@ -72349,7 +72366,7 @@ BEGIN
SELECT * FROM (
SELECT tmpTicket.ticketFk,
bp.pgcFk,
SUM(s.quantity * s.price * (100 - s.discount)/100 ) AS taxableBase,
SUM(s.quantity * s.price * (100 - s.discount)/100 ) taxableBase,
pgc.rate,
tc.code,
bp.priority
@ -72369,7 +72386,7 @@ BEGIN
JOIN pgc ON pgc.code = bp.pgcFk
JOIN taxClass tc ON tc.id = bp.taxClassFk
GROUP BY tmpTicket.ticketFk, pgc.code, pgc.rate
HAVING taxableBase != 0) t3
HAVING taxableBase <> 0) t3
ORDER BY priority;
DROP TEMPORARY TABLE IF EXISTS tmp.ticketServiceTax;
@ -72378,7 +72395,7 @@ BEGIN
ENGINE = MEMORY
SELECT tt.ticketFk,
pgc.code pgcFk,
SUM(ts.quantity * ts.price) AS taxableBase,
SUM(ts.quantity * ts.price) taxableBase,
pgc.rate,
tc.code
FROM tmp.ticket tt
@ -72394,7 +72411,7 @@ BEGIN
JOIN pgc ON pgc.code = bp.pgcFk
JOIN taxClass tc ON tc.id = bp.taxClassFk
GROUP BY tt.ticketFk, pgc.code
HAVING taxableBase != 0;
HAVING taxableBase <> 0;
INSERT INTO tmp.ticketTax (ticketFk, pgcFk, taxableBase, rate, code)
SELECT ts.ticketFk, ts.pgcFk, ts.taxableBase, ts.rate, ts.code
@ -72725,20 +72742,31 @@ DELIMITER ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalc`(vTicketId INT)
BEGIN
CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_recalc`(vSelf INT, vTaxArea VARCHAR(25))
proc:BEGIN
/**
* Calcula y guarda el total con/sin IVA en un ticket.
*
* @param vTicketId Identificador del ticket
*/
DECLARE hasInvoice BOOL;
SELECT COUNT(*) INTO hasInvoice
FROM ticket
WHERE id = vSelf
AND refFk IS NOT NULL;
IF hasInvoice THEN
LEAVE proc;
END IF;
DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
CREATE TEMPORARY TABLE tmp.ticket
ENGINE = MEMORY
SELECT vTicketId ticketFk;
SELECT vSelf ticketFk;
CALL ticketGetTotal;
CALL ticketGetTotal(vTaxArea);
UPDATE ticket t
JOIN tmp.ticketTotal tt ON tt.ticketFk = t.id

View File

@ -479,9 +479,6 @@ export default {
fourthBalance: 'vn-item-diary vn-tbody > vn-tr:nth-child(4) > vn-td.balance > span',
firstBalance: 'vn-item-diary vn-tbody > vn-tr:nth-child(1) > vn-td.balance'
},
itemLog: {
anyLineCreated: 'vn-item-log > vn-log vn-tbody > vn-tr',
},
ticketSummary: {
header: 'vn-ticket-summary > vn-card > h5',
state: 'vn-ticket-summary vn-label-value[label="State"] > section > span',
@ -667,15 +664,6 @@ export default {
thirdRemoveRequestButton: 'vn-ticket-request-index vn-tr:nth-child(3) vn-icon[icon="delete"]',
thirdRequestQuantity: 'vn-ticket-request-index vn-table vn-tr:nth-child(3) > vn-td:nth-child(6) vn-input-number',
saveButton: 'vn-ticket-request-create button[type=submit]',
},
ticketLog: {
firstTD: 'vn-ticket-log vn-table vn-td:nth-child(1)',
logButton: 'vn-left-menu a[ui-sref="ticket.card.log"]',
user: 'vn-ticket-log vn-tbody vn-tr vn-td:nth-child(2)',
action: 'vn-ticket-log vn-tbody vn-tr vn-td:nth-child(4)',
changes: 'vn-ticket-log vn-data-viewer vn-tbody vn-tr table tr:nth-child(2) td.after',
id: 'vn-ticket-log vn-tr:nth-child(1) table tr:nth-child(1) td.before'
},
ticketService: {
addServiceButton: 'vn-ticket-service vn-icon-button[vn-tooltip="Add service"] > button',
@ -1179,8 +1167,6 @@ export default {
allBuyCheckbox: 'vn-entry-buy-index thead vn-check',
firstBuyCheckbox: 'vn-entry-buy-index tbody:nth-child(2) vn-check',
deleteBuysButton: 'vn-entry-buy-index vn-button[icon="delete"]',
addBuyButton: 'vn-entry-buy-index vn-icon[icon="add"]',
secondBuyPackingPrice: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.price3"]',
secondBuyGroupingPrice: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.price2"]',
secondBuyPrice: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.buyingValue"]',
secondBuyGrouping: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.grouping"]',

View File

@ -5,8 +5,8 @@ const $ = {
userName: 'vn-client-web-access vn-textfield[ng-model="$ctrl.account.name"]',
email: 'vn-client-web-access vn-textfield[ng-model="$ctrl.account.email"]',
saveButton: 'vn-client-web-access button[type=submit]',
nameValue: 'vn-client-log .change:nth-child(1) .basic-json:nth-child(2) vn-json-value',
activeValue: 'vn-client-log .change:nth-child(2) .basic-json:nth-child(1) vn-json-value'
nameValue: 'vn-client-log .changes-log:nth-child(2) .basic-json:nth-child(2) vn-json-value',
activeValue: 'vn-client-log .changes-log:nth-child(3) .basic-json:nth-child(1) vn-json-value'
};
describe('Client web access path', () => {
@ -39,9 +39,9 @@ describe('Client web access path', () => {
const userName = await page.getValue($.userName);
const email = await page.getValue($.email);
await page.accessToSection('client.card.log');
const logName = await page.innerText($.nameValue);
const logActive = await page.innerText($.activeValue);
// await page.accessToSection('client.card.log');
// const logName = await page.innerText($.nameValue);
// const logActive = await page.innerText($.activeValue);
expect(enableMessage.type).toBe('success');
expect(modifyMessage.type).toBe('success');
@ -50,7 +50,7 @@ describe('Client web access path', () => {
expect(userName).toEqual('Legion');
expect(email).toEqual('legion@marvel.com');
expect(logName).toEqual('Legion');
expect(logActive).toEqual('✗');
// expect(logName).toEqual('Legion');
// expect(logActive).toEqual('✗');
});
});

View File

@ -9,7 +9,7 @@ describe('Travel descriptor path', () => {
browser = await getBrowser();
page = browser.page;
await page.loginAndModule('buyer', 'travel');
await page.write(selectors.travelIndex.generalSearchFilter, '1');
await page.write(selectors.travelIndex.generalSearchFilter, '3');
await page.keyboard.press('Enter');
await page.waitForState('travel.card.summary');
});
@ -23,7 +23,7 @@ describe('Travel descriptor path', () => {
await page.waitForState('travel.index');
const result = await page.countElement(selectors.travelIndex.anySearchResult);
expect(result).toBeGreaterThanOrEqual(7);
expect(result).toBeGreaterThanOrEqual(1);
});
it('should navigate to the first search result', async() => {

View File

@ -66,97 +66,4 @@ describe('Entry import, create and edit buys path', () => {
await page.waitToClick(selectors.globalItems.acceptButton);
await page.waitForNumberOfElements(selectors.entryBuys.anyBuyLine, 1);
});
it('should add a new buy', async() => {
await page.waitToClick(selectors.entryBuys.addBuyButton);
await page.write(selectors.entryBuys.secondBuyPackingPrice, '999');
await page.write(selectors.entryBuys.secondBuyGroupingPrice, '999');
await page.write(selectors.entryBuys.secondBuyPrice, '999');
await page.write(selectors.entryBuys.secondBuyGrouping, '999');
await page.write(selectors.entryBuys.secondBuyPacking, '999');
await page.write(selectors.entryBuys.secondBuyWeight, '999');
await page.write(selectors.entryBuys.secondBuyStickers, '999');
await page.autocompleteSearch(selectors.entryBuys.secondBuyPackage, '1');
await page.write(selectors.entryBuys.secondBuyQuantity, '999');
await page.autocompleteSearch(selectors.entryBuys.secondBuyItem, '1');
const message = await page.waitForSnackbar();
expect(message.text).toContain('Data saved!');
await page.waitForNumberOfElements(selectors.entryBuys.anyBuyLine, 2);
});
it('should edit the newest buy and check data', async() => {
await page.clearInput(selectors.entryBuys.secondBuyPackingPrice);
await page.waitForTimeout(250);
await page.write(selectors.entryBuys.secondBuyPackingPrice, '100');
await page.keyboard.press('Enter');
await page.waitForSnackbar();
await page.clearInput(selectors.entryBuys.secondBuyGroupingPrice);
await page.waitForTimeout(250);
await page.write(selectors.entryBuys.secondBuyGroupingPrice, '200');
await page.keyboard.press('Enter');
await page.waitForSnackbar();
await page.clearInput(selectors.entryBuys.secondBuyPrice);
await page.waitForTimeout(250);
await page.write(selectors.entryBuys.secondBuyPrice, '300');
await page.keyboard.press('Enter');
await page.waitForSnackbar();
await page.clearInput(selectors.entryBuys.secondBuyGrouping);
await page.waitForTimeout(250);
await page.write(selectors.entryBuys.secondBuyGrouping, '400');
await page.keyboard.press('Enter');
await page.waitForSnackbar();
await page.clearInput(selectors.entryBuys.secondBuyPacking);
await page.waitForTimeout(250);
await page.write(selectors.entryBuys.secondBuyPacking, '500');
await page.keyboard.press('Enter');
await page.waitForSnackbar();
await page.clearInput(selectors.entryBuys.secondBuyWeight);
await page.waitForTimeout(250);
await page.write(selectors.entryBuys.secondBuyWeight, '600');
await page.keyboard.press('Enter');
await page.waitForSnackbar();
await page.clearInput(selectors.entryBuys.secondBuyStickers);
await page.waitForTimeout(250);
await page.write(selectors.entryBuys.secondBuyStickers, '700');
await page.keyboard.press('Enter');
await page.waitForSnackbar();
await page.autocompleteSearch(selectors.entryBuys.secondBuyPackage, '94');
await page.waitForSnackbar();
await page.clearInput(selectors.entryBuys.secondBuyQuantity);
await page.waitForTimeout(250);
await page.write(selectors.entryBuys.secondBuyQuantity, '800');
await page.keyboard.press('Enter');
await page.reloadSection('entry.card.buy.index');
const secondBuyPackingPrice = await page.getValue(selectors.entryBuys.secondBuyPackingPrice);
const secondBuyGroupingPrice = await page.getValue(selectors.entryBuys.secondBuyGroupingPrice);
const secondBuyPrice = await page.getValue(selectors.entryBuys.secondBuyPrice);
const secondBuyGrouping = await page.getValue(selectors.entryBuys.secondBuyGrouping);
const secondBuyPacking = await page.getValue(selectors.entryBuys.secondBuyPacking);
const secondBuyWeight = await page.getValue(selectors.entryBuys.secondBuyWeight);
const secondBuyStickers = await page.getValue(selectors.entryBuys.secondBuyStickers);
const secondBuyPackage = await page.getValue(selectors.entryBuys.secondBuyPackage);
const secondBuyQuantity = await page.getValue(selectors.entryBuys.secondBuyQuantity);
expect(secondBuyPackingPrice).toEqual('100');
expect(secondBuyGroupingPrice).toEqual('200');
expect(secondBuyPrice).toEqual('300');
expect(secondBuyGrouping).toEqual('400');
expect(secondBuyPacking).toEqual('500');
expect(secondBuyWeight).toEqual('600');
expect(secondBuyStickers).toEqual('700');
expect(secondBuyPackage).toEqual('94');
expect(secondBuyQuantity).toEqual('800');
});
});

View File

@ -4,8 +4,8 @@ vn-avatar {
display: block;
border-radius: 50%;
overflow: hidden;
height: 36px;
width: 36px;
height: 38px;
width: 38px;
font-size: 22px;
background-color: $color-main;
position: relative;

View File

@ -59,12 +59,13 @@ export default class Auth {
password: password || undefined
};
const now = new Date();
return this.$http.post('VnUsers/signIn', params)
.then(json => this.onLoginOk(json, remember));
.then(json => this.onLoginOk(json, now, remember));
}
onLoginOk(json, remember) {
this.vnToken.set(json.data.token, json.data.created, remember);
onLoginOk(json, now, remember) {
this.vnToken.set(json.data.token, now, json.data.ttl, remember);
return this.loadAcls().then(() => {
let continueHash = this.$state.params.continue;

View File

@ -1,11 +1,16 @@
import ngModule from '../module';
import HttpError from 'core/lib/http-error';
interceptor.$inject = ['$q', 'vnApp', 'vnToken', '$translate'];
function interceptor($q, vnApp, vnToken, $translate) {
interceptor.$inject = ['$q', 'vnApp', '$translate'];
function interceptor($q, vnApp, $translate) {
let apiPath = 'api/';
let token = sessionStorage.getItem('vnToken')
?? localStorage.getItem('vnToken');
return {
setToken(newToken) {
token = newToken;
},
setApiPath(path) {
apiPath = path;
},
@ -14,8 +19,8 @@ function interceptor($q, vnApp, vnToken, $translate) {
if (config.url.charAt(0) !== '/' && apiPath)
config.url = `${apiPath}${config.url}`;
if (vnToken.token)
config.headers.Authorization = vnToken.token;
if (token)
config.headers.Authorization = token;
if ($translate.use())
config.headers['Accept-Language'] = $translate.use();
if (config.filter) {

View File

@ -6,37 +6,118 @@ import ngModule from '../module';
* @property {String} token The current login token or %null
*/
export default class Token {
constructor() {
try {
this.token = sessionStorage.getItem('vnToken');
this.created = sessionStorage.getItem('vnTokenCreated');
if (!this.token) {
this.token = localStorage.getItem('vnToken');
this.created = localStorage.getItem('vnTokenCreated');
}
} catch (e) {}
}
set(token, created, remember) {
this.unset();
try {
if (remember) {
localStorage.setItem('vnToken', token);
localStorage.setItem('vnTokenCreated', created);
} else {
sessionStorage.setItem('vnToken', token);
sessionStorage.setItem('vnTokenCreated', created);
}
} catch (e) {}
constructor(vnInterceptor, $http, $rootScope) {
Object.assign(this, {
vnInterceptor,
$http,
$rootScope
});
this.token = token;
this.created = created;
try {
this.getStorage(sessionStorage);
this.remember = true;
if (!this.token) {
this.getStorage(localStorage);
this.remember = false;
}
} catch (e) {}
}
set(token, created, ttl, remember) {
this.unset();
Object.assign(this, {
token,
created,
ttl,
remember
});
this.vnInterceptor.setToken(token);
try {
if (remember)
this.setStorage(localStorage, token, created, ttl);
else
this.setStorage(sessionStorage, token, created, ttl);
} catch (err) {
console.error(err);
}
}
unset() {
localStorage.removeItem('vnToken');
sessionStorage.removeItem('vnToken');
this.token = null;
this.created = null;
this.ttl = null;
this.remember = null;
this.vnInterceptor.setToken(null);
this.removeStorage(localStorage);
this.removeStorage(sessionStorage);
}
getStorage(storage) {
this.token = storage.getItem('vnToken');
if (!this.token) return;
const created = storage.getItem('vnTokenCreated');
this.created = created && new Date(created);
this.renewPeriod = storage.getItem('vnTokenRenewPeriod');
}
setStorage(storage, token, created, ttl) {
storage.setItem('vnToken', token);
storage.setItem('vnTokenCreated', created.toJSON());
storage.setItem('vnTokenTtl', ttl);
}
removeStorage(storage) {
storage.removeItem('vnToken');
storage.removeItem('vnTokenCreated');
storage.removeItem('vnTokenTtl');
}
fetchConfig() {
const filter = {fields: ['renewInterval', 'renewPeriod']};
this.$http.get('AccessTokenConfigs/findOne', {filter}).then(res => {
const data = res.data;
if (!data) return;
this.renewPeriod = data.renewPeriod;
this.stopRenewer();
this.inservalId = setInterval(() => this.checkValidity(), data.renewInterval * 1000);
this.checkValidity();
});
}
checkValidity() {
if (this.checking || !this.created) return;
this.checking = true;
const renewPeriod = Math.min(this.ttl, this.renewPeriod) * 1000;
const maxDate = this.created.getTime() + renewPeriod;
const now = new Date();
if (now.getTime() <= maxDate) {
this.checking = false;
return;
}
this.$http.post('VnUsers/renewToken')
.then(res => {
const token = res.data;
this.set(token.id, now, token.ttl, this.remember);
})
.catch(res => {
if (res.data?.error?.code !== 'periodNotExceeded')
throw res;
})
.finally(() => {
this.checking = false;
});
}
stopRenewer() {
clearInterval(this.inservalId);
}
}
Token.$inject = ['vnInterceptor', '$http', '$rootScope'];
ngModule.service('vnToken', Token);

View File

@ -42,7 +42,7 @@
<button class="buttonAccount">
<img
id="user"
ng-src="{{$ctrl.getImageUrl()}}"
ng-src="{{::$ctrl.getImageUrl()}}"
ng-click="userPopover.show($event)"
translate-attr="{title: 'Account'}"
on-error-src/>

View File

@ -3,14 +3,13 @@ import Component from 'core/lib/component';
import './style.scss';
export class Layout extends Component {
constructor($element, $, vnModules, vnToken) {
constructor($element, $, vnModules) {
super($element, $);
this.modules = vnModules.get();
}
$onInit() {
this.getUserData();
this.getAccessTokenConfig();
}
getUserData() {
@ -32,41 +31,11 @@ export class Layout extends Component {
window.location.reload();
}
getAccessTokenConfig() {
this.$http.get('AccessTokenConfigs').then(json => {
const firtsResult = json.data[0];
if (!firtsResult) return;
this.renewPeriod = firtsResult.renewPeriod;
this.renewInterval = firtsResult.renewInterval;
const intervalMilliseconds = firtsResult.renewInterval * 1000;
this.inservalId = setInterval(this.checkTokenValidity.bind(this), intervalMilliseconds);
});
}
checkTokenValidity() {
const now = new Date();
const differenceMilliseconds = now - new Date(this.vnToken.created);
const differenceSeconds = Math.floor(differenceMilliseconds / 1000);
if (differenceSeconds > this.renewPeriod) {
this.$http.post('VnUsers/renewToken')
.then(json => {
if (json.data.token) {
let remember = true;
if (window.sessionStorage.vnToken) remember = false;
this.vnToken.set(json.data.token, json.data.created, remember);
}
});
}
}
$onDestroy() {
clearInterval(this.inservalId);
this.vnToken.stopRenewer();
}
}
Layout.$inject = ['$element', '$scope', 'vnModules', 'vnToken'];
Layout.$inject = ['$element', '$scope', 'vnModules'];
ngModule.vnComponent('vnLayout', {
template: require('./index.html'),

View File

@ -37,49 +37,4 @@ describe('Component vnLayout', () => {
expect(url).not.toBeDefined();
});
});
describe('getAccessTokenConfig()', () => {
it(`should set the renewPeriod and renewInterval properties in localStorage`, () => {
const response = [{
renewPeriod: 100,
renewInterval: 5
}];
$httpBackend.expect('GET', `AccessTokenConfigs`).respond(response);
controller.getAccessTokenConfig();
$httpBackend.flush();
expect(controller.renewPeriod).toBe(100);
expect(controller.renewInterval).toBe(5);
expect(controller.inservalId).toBeDefined();
});
});
describe('checkTokenValidity()', () => {
it(`should not call renewToken and not set vnToken in the controller`, () => {
controller.renewPeriod = 100;
controller.vnToken.created = new Date();
controller.checkTokenValidity();
expect(controller.vnToken.token).toBeNull();
});
it(`should call renewToken and set vnToken properties in the controller`, () => {
const response = {
token: 999,
created: new Date()
};
controller.renewPeriod = 100;
const oneHourBefore = new Date(Date.now() - (60 * 60 * 1000));
controller.vnToken.created = oneHourBefore;
$httpBackend.expect('POST', `VnUsers/renewToken`).respond(response);
controller.checkTokenValidity();
$httpBackend.flush();
expect(controller.vnToken.token).toBe(999);
expect(controller.vnToken.created).toEqual(response.created);
});
});
});

View File

@ -2,8 +2,6 @@
vn-id="model"
url="{{$ctrl.url}}"
filter="$ctrl.filter"
link="{originFk: $ctrl.originId}"
where="{changedModel: $ctrl.changedModel, changedModelId: $ctrl.changedModelId}"
data="$ctrl.logs"
order="creationDate DESC, id DESC"
limit="20">
@ -17,90 +15,110 @@
<vn-data-viewer
model="model"
class="vn-w-sm vn-px-sm vn-pb-xl">
<div class="change vn-mb-sm" ng-repeat="log in $ctrl.logs">
<div class="left">
<vn-avatar class="vn-mt-xs"
ng-class="::{system: !log.user}"
val="{{::log.user ? log.user.nickname : $ctrl.$t('System')}}"
ng-click="$ctrl.showWorkerDescriptor($event, log)">
<img
ng-if="::log.user.image"
ng-src="/api/Images/user/160x160/{{::log.userFk}}/download?access_token={{::$ctrl.vnToken.token}}">
</img>
</vn-avatar>
<div class="arrow bg-panel"></div>
<div class="origin-log" ng-repeat="originLog in $ctrl.logTree">
<div class="origin-info vn-mb-md" ng-if="::$ctrl.logTree.length > 1">
<h6 class="origin-id">
{{::$ctrl.modelI18n}} #{{::originLog.originFk}}
</h6>
<div class="line"></div>
</div>
<vn-card class="detail">
<div class="header vn-pa-sm">
<div class="action-model">
<span class="model-name"
ng-if="::$ctrl.showModelName && log.changedModel"
ng-style="::{backgroundColor: $ctrl.hashToColor(log.changedModel)}"
title="{{::log.changedModel}}">
{{::log.changedModelI18n}}
</span>
</div>
<div
class="action-date text-secondary text-caption vn-ml-sm"
title="{{::log.creationDate | date:'dd/MM/yyyy HH:mm:ss'}}">
{{::$ctrl.relativeDate(log.creationDate)}}
<vn-icon
class="action vn-ml-xs"
ng-class="::$ctrl.actionsClass[log.action]"
icon="{{::$ctrl.actionsIcon[log.action]}}"
translate-attr="::{title: $ctrl.actionsText[log.action]}">
</vn-icon>
<div class="user-log vn-mb-sm" ng-repeat="userLog in ::originLog.logs">
<div class="timeline">
<div class="user-avatar">
<vn-avatar
ng-class="::{system: !userLog.user}"
val="{{::userLog.user ? userLog.user.nickname : $ctrl.$t('System')}}"
ng-click="$ctrl.showWorkerDescriptor($event, userLog)">
<img
ng-if="::userLog.user.image"
ng-src="/api/Images/user/160x160/{{::userLog.userFk}}/download?access_token={{::$ctrl.vnToken.token}}">
</img>
</vn-avatar>
</div>
<div class="arrow bg-panel" ng-if="::$ctrl.byRecord"></div>
<div class="line"></div>
</div>
<div class="model vn-pb-sm vn-px-sm"
ng-if="::$ctrl.showModelName">
<span class="model-id" ng-if="::log.changedModelId">#{{::log.changedModelId}}</span>
<vn-icon
icon="filter_alt"
translate-attr="{title: 'Show all record changes'}"
ng-click="$ctrl.filterByEntity(log)">
</vn-icon>
<span class="model-value" title="{{::log.changedModelValue}}">{{::log.changedModelValue}}</span>
</div>
<div class="changes vn-pa-sm"
ng-class="{expanded: log.expand}"
ng-if="::log.props.length || log.description">
<vn-icon
icon="expand_more"
translate-attr="{title: 'Details'}"
ng-click="log.expand = !log.expand">
</vn-icon>
<span ng-if="::log.props.length"
class="attributes">
<span ng-if="!log.expand" ng-repeat="prop in ::log.props"
class="basic-json">
<span class="json-field" title="{{::prop.name}}">
{{::prop.nameI18n}}:
<div class="user-changes">
<div class="model-log" ng-repeat="modelLog in ::userLog.logs">
<div class="model-info vn-my-sm" ng-if="::!$ctrl.byRecord">
<vn-icon
icon="filter_alt"
translate-attr="{title: 'Show all record changes'}"
ng-click="$ctrl.filterByRecord(modelLog)">
</vn-icon>
<span class="model-name"
ng-if="::$ctrl.showModelName && modelLog.model"
ng-style="::{backgroundColor: $ctrl.hashToColor(modelLog.model)}"
title="{{::modelLog.model}}">
{{::modelLog.modelI18n}}
</span>
<vn-json-value value="::prop.val.val"></vn-json-value><span ng-if="::!$last">,</span>
</span>
<div ng-if="log.expand" class="expanded-json">
<div ng-repeat="prop in ::log.props">
<span class="json-field" title="{{::prop.name}}">
{{::prop.nameI18n}}:
</span>
<vn-log-value val="::prop.val"></vn-log-value>
<span ng-if="::log.action == 'update'">
<vn-log-value val="::prop.old"></vn-log-value>
</span>
</div>
<span class="model-id" ng-if="::modelLog.id">#{{::modelLog.id}}</span>
<span class="model-value" title="{{::modelLog.showValue}}">{{::modelLog.showValue}}</span>
</div>
</span>
<span ng-if="::!log.props.length" class="description">
{{::log.description}}
</span>
</vn-card>
<vn-card class="changes-log vn-mb-xs" ng-repeat="log in ::modelLog.logs">
<div class="change-info vn-pa-sm">
<div
class="date text-secondary text-caption vn-mr-sm"
title="{{::log.creationDate | date:'dd/MM/yyyy HH:mm:ss'}}">
{{::$ctrl.relativeDate(log.creationDate)}}
</div>
<div>
<vn-icon
class="pit vn-ml-xs"
icon="preview"
translate-attr="::{title: 'View record at this point in time'}"
ng-show="::log.action != 'insert'"
ng-click="$ctrl.viewPitInstance($event, log.id, modelLog)">
</vn-icon>
<vn-icon
class="action vn-ml-xs"
ng-class="::$ctrl.actionsClass[log.action]"
icon="{{::$ctrl.actionsIcon[log.action]}}"
translate-attr="::{title: $ctrl.actionsText[log.action]}">
</vn-icon>
</div>
</div>
<div class="change-detail vn-pa-sm"
ng-class="{expanded: log.expand}"
ng-if="::log.props.length || log.description">
<vn-icon
icon="expand_more"
translate-attr="{title: 'Details'}"
ng-click="log.expand = !log.expand">
</vn-icon>
<span ng-if="::log.props.length"
class="attributes">
<span ng-if="!log.expand" ng-repeat="prop in ::log.props"
class="basic-json">
<span class="json-field" title="{{::prop.name}}">
{{::prop.nameI18n}}:
</span>
<vn-json-value value="::prop.val.val"></vn-json-value><span ng-if="::!$last">,</span>
</span>
<div ng-if="log.expand" class="expanded-json">
<div ng-repeat="prop in ::log.props">
<span class="json-field" title="{{::prop.name}}">
{{::prop.nameI18n}}:
</span>
<vn-log-value val="::prop.val"></vn-log-value>
<span ng-if="::log.action == 'update'">
<vn-log-value val="::prop.old"></vn-log-value>
</span>
</div>
</div>
</span>
<span ng-if="::!log.props.length" class="description">
{{::log.description}}
</span>
</vn-card>
</div>
</div>
</div>
</div>
</div>
</vn-data-viewer>
<vn-float-button
ng-if="model.userFilter"
ng-if="$ctrl.hasFilter"
icon="filter_alt_off"
translate-attr="{title: 'Quit filter'}"
ng-click="$ctrl.resetFilter()"
@ -212,5 +230,33 @@
</vn-date-picker>
</form>
</vn-side-menu>
<vn-worker-descriptor-popover vn-id="workerDescriptor">
<vn-popover vn-id="instance-popover">
<tpl-body class="vn-log-instance">
<vn-spinner
ng-if="$ctrl.instance.canceler"
class="loading vn-pa-sm"
enable="true">
</vn-spinner>
<div
ng-if="!$ctrl.instance.canceler" class="instance">
<h6 class="header vn-pa-sm">
{{$ctrl.instance.modelLog.modelI18n}} #{{$ctrl.instance.modelLog.id}}
</h6>
<div class="change-detail vn-pa-sm">
<div ng-if="$ctrl.instance.props"
ng-repeat="prop in $ctrl.instance.props">
<span class="json-field" title="{{::prop.name}}">
{{::prop.nameI18n}}:
</span>
<vn-log-value val="::prop.val"></vn-log-value>
</div>
<div ng-if="!$ctrl.instance.props" translate>
No data
</div>
</div>
</div>
</tpl-body>
</vn-popover>
<vn-worker-descriptor-popover
vn-id="worker-descriptor">
</vn-worker-descriptor-popover>

View File

@ -3,7 +3,10 @@ import Section from '../section';
import {hashToColor} from 'core/lib/string';
import './style.scss';
const validDate = /^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/;
const validDate = new RegExp(
/^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])/.source
+ /T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$/.source
);
export default class Controller extends Section {
constructor($element, $) {
@ -28,6 +31,20 @@ export default class Controller extends Section {
select: 'visibility'
};
this.filter = {
fields: [
'id',
'originFk',
'userFk',
'action',
'changedModel',
'oldInstance',
'newInstance',
'creationDate',
'changedModel',
'changedModelId',
'changedModelValue',
'description'
],
include: [{
relation: 'user',
scope: {
@ -48,6 +65,11 @@ export default class Controller extends Section {
this.today.setHours(0, 0, 0, 0);
}
$onInit() {
const match = this.url?.match(/(.*)Logs$/);
this.modelI18n = match && this.translateModel(match[1]);
}
$postLink() {
this.resetFilter();
this.$.$watch(
@ -63,47 +85,75 @@ export default class Controller extends Section {
set logs(value) {
this._logs = value;
this.logTree = [];
if (!value) return;
const empty = {};
const validations = window.validations;
const castJsonValue = this.castJsonValue;
for (const log of value) {
let originLog;
let userLog;
let modelLog;
let nLogs;
for (let i = 0; i < value.length; i++) {
const log = value[i];
const prevLog = i > 0 ? value[i - 1] : null;
const locale = validations[log.changedModel]?.locale || empty;
// Origin
const originChanged = !prevLog
|| log.originFk != prevLog.originFk;
if (originChanged) {
this.logTree.push(originLog = {
originFk: log.originFk,
logs: []
});
}
// User
const userChanged = originChanged
|| log.userFk != prevLog.userFk;
if (userChanged) {
originLog.logs.push(userLog = {
user: log.user,
userFk: log.userFk,
logs: []
});
}
// Model
const modelChanged = userChanged
|| log.changedModel != prevLog.changedModel
|| log.changedModelId != prevLog.changedModelId
|| nLogs >= 6;
if (modelChanged) {
userLog.logs.push(modelLog = {
model: log.changedModel,
modelI18n: firstUpper(locale.name) || log.changedModel,
id: log.changedModelId,
showValue: log.changedModelValue,
logs: []
});
nLogs = 0;
}
nLogs++;
modelLog.logs.push(log);
// Changes
const notDelete = log.action != 'delete';
const olds = (notDelete ? log.oldInstance : null) || empty;
const vals = (notDelete ? log.newInstance : log.oldInstance) || empty;
const locale = validations[log.changedModel]?.locale || empty;
log.changedModelI18n = firstUpper(locale.name) || log.changedModel;
let props = Object.keys(olds).concat(Object.keys(vals));
props = [...new Set(props)];
let propNames = Object.keys(olds).concat(Object.keys(vals));
propNames = [...new Set(propNames)];
log.props = [];
for (const prop of props) {
if (prop.endsWith('$')) continue;
log.props.push({
name: prop,
nameI18n: firstUpper(locale.columns?.[prop]) || prop,
old: getVal(olds, prop),
val: getVal(vals, prop)
});
}
log.props.sort(
(a, b) => a.nameI18n.localeCompare(b.nameI18n));
}
function getVal(vals, prop) {
let val, id;
const showProp = `${prop}$`;
if (vals[showProp] != null) {
val = vals[showProp];
id = vals[prop];
} else
val = vals[prop];
return {val: castJsonValue(val), id};
log.props = this.parseProps(propNames, locale, vals, olds);
}
}
@ -114,17 +164,76 @@ export default class Controller extends Section {
set models(value) {
this._models = value;
if (!value) return;
for (const model of value) {
const name = model.changedModel;
model.changedModelI18n =
firstUpper(window.validations[name]?.locale?.name) || name;
}
for (const model of value)
model.changedModelI18n = this.translateModel(model.changedModel);
}
get showModelName() {
return !(this.changedModel && this.changedModelId);
}
parseProps(propNames, locale, vals, olds) {
const castJsonValue = this.castJsonValue;
const props = [];
for (const prop of propNames) {
if (prop.endsWith('$')) continue;
props.push({
name: prop,
nameI18n: firstUpper(locale.columns?.[prop]) || prop,
val: getVal(vals, prop),
old: olds && getVal(olds, prop)
});
}
props.sort(
(a, b) => a.nameI18n.localeCompare(b.nameI18n));
function getVal(vals, prop) {
let val; let id;
const showProp = `${prop}$`;
if (vals[showProp] != null) {
val = vals[showProp];
id = vals[prop];
} else
val = vals[prop];
return {val: castJsonValue(val), id};
}
return props;
}
viewPitInstance(event, id, modelLog) {
if (this.instance?.canceler)
this.instance.canceler.resolve();
const canceler = this.$q.defer();
this.instance = {
modelLog,
canceler
};
const options = {timeout: canceler.promise};
this.$http.get(`${this.url}/${id}/pitInstance`, options)
.then(res => {
const instance = res.data;
const propNames = Object.keys(instance);
const locale = window.validations[modelLog.model]?.locale || {};
this.instance.props = this.parseProps(propNames, locale, instance);
})
.finally(() => {
this.instance.canceler = null;
this.$.$applyAsync(() => this.$.instancePopover.relocate());
});
this.$.instancePopover.show(event);
}
translateModel(name) {
return firstUpper(window.validations[name]?.locale?.name) || name;
}
castJsonValue(value) {
return typeof value === 'string' && validDate.test(value)
? new Date(value)
@ -160,12 +269,11 @@ export default class Controller extends Section {
applyFilter() {
const filter = this.$.filter;
function getParam(prop, value) {
const getParam = (prop, value) => {
if (value == null || value == '') return null;
switch (prop) {
case 'search':
const or = [];
if (/^\s*[0-9]+\s*$/.test(value))
if (/^\s*[0-9]+\s*$/.test(value) || this.byRecord)
return {changedModelId: value.trim()};
else
return {changedModelValue: {like: `%${value}%`}};
@ -177,72 +285,86 @@ export default class Controller extends Section {
]};
case 'who':
switch (value) {
case 'all':
return null;
case 'user':
return {userFk: {neq: null}};
case 'system':
return {userFk: null};
case 'all':
default:
return null;
}
case 'actions':
case 'actions': {
const inq = [];
for (const action in value) {
if (value[action])
inq.push(action);
}
return inq.length ? {action: {inq}} : null;
}
case 'from':
if (filter.to) {
if (filter.to)
return {creationDate: {gte: value}};
} else {
else {
const to = new Date(value);
to.setHours(23, 59, 59, 999);
return {creationDate: {between: [value, to]}};
}
case 'to':
case 'to': {
const to = new Date(value);
to.setHours(23, 59, 59, 999);
return {creationDate: {lte: to}};
}
case 'userFk':
return filter.who != 'system'
? {[prop]: value} : null;
default:
return {[prop]: value};
}
}
};
this.hasFilter = false;
const and = [];
if (!filter.search || !filter.changedModel)
this.byRecord = false;
if (!this.byRecord)
and.push({originFk: this.originId});
for (const prop in filter) {
const param = getParam(prop, filter[prop]);
if (param) and.push(param);
if (param) {
and.push(param);
this.hasFilter = true;
}
}
const lbFilter = and.length ? {where: {and}} : null;
return this.$.model.applyFilter(lbFilter);
}
filterByEntity(log) {
filterByRecord(modelLog) {
this.byRecord = true;
this.$.filter = {
who: 'all',
search: log.changedModelId,
changedModel: log.changedModel
search: modelLog.id,
changedModel: modelLog.model
};
}
searchUser(search) {
if (/^[0-9]+$/.test(search)) {
if (/^[0-9]+$/.test(search))
return {id: search};
} else {
else {
return {or: [
{name: search},
{nickname: {like: `%${search}%`}}
]}
]};
}
}
showWorkerDescriptor(event, log) {
if (log.user?.worker)
this.$.workerDescriptor.show(event.target, log.userFk);
showWorkerDescriptor(event, userLog) {
if (userLog.user?.worker)
this.$.workerDescriptor.show(event.target, userLog.userFk);
}
}

View File

@ -24,4 +24,5 @@ Changes: Cambios
today: hoy
yesterday: ayer
Show all record changes: Mostrar todos los cambios realizados en el registro
View record at this point in time: Ver el registro en este punto
Quit filter: Quitar filtro

View File

@ -1,167 +1,246 @@
@import "util";
vn-log {
.change {
.origin-log {
&:first-child > .origin-info {
margin-top: 0;
}
& > .origin-info {
display: flex;
align-items: center;
margin-top: 28px;
gap: 6px;
& > .origin-id {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
color: $color-font-secondary;
margin: 0;
}
& > .line {
flex-grow: 1;
background-color: $color-font-secondary;
height: 2px;
}
}
}
.user-log {
display: flex;
& > .left {
& > .timeline {
position: relative;
padding-right: 10px;
width: 38px;
min-width: 38px;
flex-grow: auto;
& > vn-avatar {
cursor: pointer;
&.system {
background-color: $color-main !important;
}
}
& > .arrow {
height: 8px;
width: 8px;
position: absolute;
transform: rotateY(0deg) rotate(45deg);
top: 18px;
top: 15px;
right: -4px;
z-index: 1;
}
& > .user-avatar {
background-color: $color-bg;
padding: $spacing-sm 0;
margin-top: -$spacing-sm;
position: sticky;
top: 64px;
& > vn-avatar {
cursor: pointer;
display: block;
&.system {
background-color: $color-main !important;
}
}
}
& > .line {
position: absolute;
background-color: $color-main;
width: 2px;
left: 17px;
left: 18px;
z-index: -1;
top: 44px;
bottom: -8px;
top: 0;
bottom: -$spacing-sm;
}
}
&:last-child > .left > .line {
&:last-child > .timeline > .line {
display: none;
}
.detail {
position: relative;
& > .user-changes {
flex-grow: 1;
width: 100%;
border-radius: 2px;
overflow: hidden;
}
}
.model-log {
& > .model-info {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
min-height: 22px;
& > .header {
display: flex;
justify-content: space-between;
align-items: center;
overflow: hidden;
& > .model-name {
display: inline-block;
padding: 2px 5px;
color: $color-font-dark;
border-radius: 8px;
vertical-align: middle;
}
& > .model-value {
font-style: italic;
}
& > .model-id {
color: $color-font-secondary;
font-size: .9rem;
}
& > vn-icon[icon="filter_alt"] {
@extend %clickable-light;
vertical-align: middle;
font-size: 18px;
color: $color-font-secondary;
float: right;
display: none;
& > .action-model {
display: inline-flex;
overflow: hidden;
& > .model-name {
display: inline-block;
padding: 2px 5px;
color: $color-font-dark;
border-radius: 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
& > .action-date {
white-space: nowrap;
& > .action {
display: inline-flex;
align-items: center;
justify-content: center;
color: $color-font-bg;
vertical-align: middle;
border-radius: 50%;
width: 24px;
height: 24px;
font-size: 18px;
&.notice {
background-color: $color-notice-medium
}
&.success {
background-color: $color-success-medium;
}
&.warning {
background-color: $color-main-medium;
}
&.alert {
background-color: lighten($color-alert, 5%);
}
}
@include mobile {
display: initial;
}
}
& > .model {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-height: 18px;
}
&:hover > .model-info > vn-icon[icon="filter_alt"] {
display: initial;
}
}
.changes-log {
position: relative;
max-width: 100%;
width: 100%;
border-radius: 2px;
overflow: hidden;
& > vn-icon {
&:last-child {
margin-bottom: 0;
}
& > .change-info {
display: flex;
justify-content: space-between;
align-items: center;
overflow: hidden;
& > .date {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
& > div {
white-space: nowrap;
& > vn-icon.pit {
@extend %clickable-light;
vertical-align: middle;
padding: 2px;
margin: -2px;
font-size: 18px;
font-size: 20px;
color: $color-font-secondary;
float: right;
display: none;
@include mobile {
display: initial;
display: inline-block;
}
}
& > .model-value {
font-style: italic;
}
& > .model-id {
color: $color-font-secondary;
font-size: .9rem;
}
}
&:hover > .model > vn-icon {
display: initial;
}
}
}
.changes {
overflow: hidden;
background-color: rgba(255, 255, 255, .05);
color: $color-font-light;
position: relative;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-height: 34px;
box-sizing: border-box;
& > .action {
display: inline-flex;
align-items: center;
justify-content: center;
color: $color-font-bg;
vertical-align: middle;
border-radius: 50%;
width: 24px;
height: 24px;
font-size: 18px;
& > vn-icon {
@extend %clickable;
float: right;
position: relative;
transition-property: transform, background-color;
transition-duration: 150ms;
margin: -5px;
margin-left: 4px;
padding: 1px;
border-radius: 50%;
&.notice {
background-color: $color-notice-medium
}
&.success {
background-color: $color-success-medium;
}
&.warning {
background-color: $color-main-medium;
}
&.alert {
background-color: lighten($color-alert, 5%);
}
}
}
&:hover vn-icon.pit {
display: inline-block;
}
}
&.expanded {
text-overflow: initial;
white-space: initial;
& > .change-detail {
overflow: hidden;
background-color: rgba(255, 255, 255, .05);
color: $color-font-light;
position: relative;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-height: 34px;
box-sizing: border-box;
& > vn-icon {
transform: rotate(180deg);
@extend %clickable;
float: right;
position: relative;
transition-property: transform, background-color;
transition-duration: 150ms;
margin: -5px;
margin-left: 4px;
padding: 1px;
border-radius: 50%;
}
&.expanded {
text-overflow: initial;
white-space: initial;
& > vn-icon {
transform: rotate(180deg);
}
}
& > .no-changes {
font-style: italic;
}
}
& > .no-changes {
font-style: italic;
}
.id-value {
font-size: .9rem;
color: $color-font-secondary;
}
}
.vn-log-instance {
display: block;
& > .loading {
display: flex;
justify-content: center;
}
& > .instance {
min-width: 180px;
max-width: 400px;
& > .header {
background-color: $color-main;
color: $color-font-dark;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
margin: 0;
}
& > .change-detail {
color: $color-font-light;
}
}
}
vn-log-value > .id-value {
font-size: .9rem;
color: $color-font-secondary;
}

View File

@ -11,7 +11,8 @@ function config($stateProvider, $urlRouterProvider) {
abstract: true,
template: '<vn-layout></vn-layout>',
resolve: {
config: ['vnConfig', vnConfig => vnConfig.initialize()]
config: ['vnConfig', vnConfig => vnConfig.initialize()],
token: ['vnToken', vnToken => vnToken.fetchConfig()]
}
})
.state('outLayout', {

View File

@ -0,0 +1,91 @@
const NotFoundError = require('vn-loopback/util/not-found-error');
module.exports = Self => {
Self.remoteMethod('pitInstance', {
description: 'Gets the status of instance at specific point in time',
accepts: [
{
arg: 'id',
type: 'integer',
description: 'The log id',
required: true
}
],
returns: {
type: [Self],
root: true
},
http: {
path: `/:id/pitInstance`,
verb: 'GET'
}
});
Self.pitInstance = async function(id) {
const log = await Self.findById(id, {
fields: [
'changedModel',
'changedModelId',
'creationDate'
]
});
if (!log)
throw new NotFoundError();
const where = {
changedModel: log.changedModel,
changedModelId: log.changedModelId
};
// Fetch creation and all update logs for record up to requested log
const createdWhere = {
action: 'insert',
creationDate: {lte: log.creationDate}
};
const createdLog = await Self.findOne({
fields: ['id', 'creationDate', 'newInstance'],
where: Object.assign(createdWhere, where),
order: 'creationDate DESC, id DESC'
});
const instance = {};
let logsWhere = {
action: 'update'
};
if (createdLog) {
Object.assign(instance, createdLog.newInstance);
Object.assign(logsWhere, {
creationDate: {between: [
createdLog.creationDate,
log.creationDate
]},
id: {between: [
Math.min(id, createdLog.id),
Math.max(id, createdLog.id)
]}
});
} else {
Object.assign(logsWhere, {
creationDate: {lte: log.creationDate},
id: {lte: id}
});
}
const logs = await Self.find({
fields: ['newInstance'],
where: Object.assign(logsWhere, where),
order: 'creationDate, id'
});
if (!logs.length && !createdLog)
throw new NotFoundError('No logs found for record');
// Merge all logs in order into one instance
for (const log of logs)
Object.assign(instance, log.newInstance);
return instance;
};
};

View File

@ -5,6 +5,7 @@ module.exports = function(Self) {
Self.super_.setup.call(this);
require('../methods/log/editors')(this);
require('../methods/log/models')(this);
require('../methods/log/pitInstance')(this);
}
});
};

View File

@ -115,7 +115,7 @@
"This client is not invoiceable": "This client is not invoiceable",
"INACTIVE_PROVIDER": "Inactive provider",
"reference duplicated": "reference duplicated",
"The PDF document does not exists": "The PDF document does not exists. Try regenerating it from 'Regenerate invoice PDF' option",
"The PDF document does not exist": "The PDF document does not exists. Try regenerating it from 'Regenerate invoice PDF' option",
"This item is not available": "This item is not available",
"Deny buy request": "Purchase request for ticket id [{{ticketId}}]({{{url}}}) has been rejected. Reason: {{observation}}",
"The type of business must be filled in basic data": "The type of business must be filled in basic data",
@ -175,5 +175,7 @@
"Pass expired": "The password has expired, change it from Salix",
"Can't transfer claimed sales": "Can't transfer claimed sales",
"Invalid quantity": "Invalid quantity",
"Failed to upload delivery note": "Error to upload delivery note {{id}}"
"Failed to upload delivery note": "Error to upload delivery note {{id}}",
"Mail not sent": "There has been an error sending the invoice to the client [{{clientId}}]({{{clientUrl}}}), please check the email address",
"The renew period has not been exceeded": "The renew period has not been exceeded"
}

View File

@ -177,7 +177,6 @@
"You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria",
"Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas",
"The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta",
"Sorts whole route": "Reordena ruta entera",
"New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*",
"New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*",
"Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío",
@ -211,7 +210,7 @@
"You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito",
"You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas",
"Amounts do not match": "Las cantidades no coinciden",
"The PDF document does not exists": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'",
"The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'",
"The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos",
"You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días",
"The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día",
@ -265,7 +264,7 @@
"It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas",
"A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.",
"There is no assigned email for this client": "No hay correo asignado para este cliente",
"Exists an invoice with a previous date": "Existe una factura con fecha anterior",
"Exists an invoice with a future date": "Existe una factura con fecha posterior",
"Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite",
"Warehouse inventory not set": "El almacén inventario no está establecido",
"This locker has already been assigned": "Esta taquilla ya ha sido asignada",
@ -294,5 +293,10 @@
"Invalid NIF for VIES": "Invalid NIF for VIES",
"Ticket does not exist": "Este ticket no existe",
"Ticket is already signed": "Este ticket ya ha sido firmado",
"You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono",
"Fecha fuera de rango": "Fecha fuera de rango",
"Error while generating PDF": "Error al generar PDF",
"Error when sending mail to client": "Error al enviar el correo al cliente",
"Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico",
"The renew period has not been exceeded": "El periodo de renovación no ha sido superado"
}

View File

@ -77,14 +77,6 @@ module.exports = Self => {
if (salesPersonId)
await models.Chat.sendCheckingPresence(ctx, salesPersonId, message);
await models.ClaimLog.create({
originFk: args.id,
userFk: userId,
action: 'insert',
description: 'Claim-pickup-order sent',
changedModel: 'Mail'
});
const email = new Email('claim-pickup-order', params);
return email.send();

View File

@ -52,4 +52,5 @@ columns:
hasInvoiceSimplified: simplified invoice
typeFk: type
lastSalesPersonFk: last salesperson
rating: rating
recommendedCredit: recommended credit

View File

@ -52,4 +52,5 @@ columns:
hasInvoiceSimplified: factura simple
typeFk: tipo
lastSalesPersonFk: último comercial
rating: clasificación
recommendedCredit: crédito recomendado

View File

@ -19,9 +19,6 @@ module.exports = Self => {
});
Self.confirmTransaction = async(ctx, id, options) => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
let tx;
const myOptions = {userId: ctx.req.accessToken.userId};
@ -34,29 +31,8 @@ module.exports = Self => {
}
try {
const oldTpvTransaction = await models.TpvTransaction.findById(id, null, myOptions);
const confirm = await Self.rawSql('CALL hedera.tpvTransaction_confirmById(?)', [id], myOptions);
const tpvTransaction = await models.TpvTransaction.findById(id, null, myOptions);
const oldInstance = {status: oldTpvTransaction.status};
const newInstance = {status: tpvTransaction.status};
const logRecord = {
originFk: tpvTransaction.clientFk,
userFk: userId,
action: 'update',
changedModel: 'TpvTransaction',
changedModelId: id,
oldInstance: oldInstance,
newInstance: newInstance
};
await models.ClientLog.create(logRecord, myOptions);
if (tx) await tx.commit();
return confirm;
} catch (e) {
if (tx) await tx.rollback();

View File

@ -30,34 +30,9 @@ module.exports = Self => {
}
});
Self.sendSms = async(ctx, id, destination, message, options) => {
Self.sendSms = async(ctx, id, destination, message) => {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const userId = ctx.req.accessToken.userId;
const sms = await models.Sms.send(ctx, destination, message);
const logRecord = {
originFk: id,
userFk: userId,
action: 'insert',
changedModel: 'sms',
newInstance: {
destinationFk: id,
destination: destination,
message: message,
statusCode: sms.statusCode,
status: sms.status
}
};
const clientLog = await models.ClientLog.create(logRecord, myOptions);
sms.logId = clientLog.id;
return sms;
};
};

View File

@ -13,10 +13,7 @@ describe('client sendSms()', () => {
const sms = await models.Client.sendSms(ctx, id, destination, message, options);
const createdLog = await models.ClientLog.findById(sms.logId, null, options);
const json = JSON.parse(JSON.stringify(createdLog.newInstance));
expect(json.message).toEqual(message);
expect(sms).toBeDefined();
await tx.rollback();
} catch (e) {

View File

@ -144,20 +144,7 @@ module.exports = Self => {
if (taxDataChecked && !hasSageData)
throw new UserError(`You need to fill sage information before you check verified data`);
if (args.despiteOfClient) {
const logRecord = {
originFk: clientId,
userFk: userId,
action: 'update',
changedModel: 'Client',
changedModelId: clientId,
description: $t(`Client checked as validated despite of duplication`, {
clientId: args.despiteOfClient
})
};
await models.ClientLog.create(logRecord, myOptions);
}
// Remove unwanted properties
delete args.ctx;
delete args.id;

View File

@ -282,7 +282,7 @@ module.exports = Self => {
await Self.changeCredit(ctx, finalState, changes);
// Credit management changes
if (orgData?.rating != changes.rating || orgData?.recommendedCredit != changes.recommendedCredit)
if (changes?.rating || changes?.recommendedCredit)
await Self.changeCreditManagement(ctx, finalState, changes);
const oldInstance = {};
@ -479,21 +479,6 @@ module.exports = Self => {
hasChanges = oldData.name != changes.name || oldData.active != changes.active;
if (!hasChanges) return;
const isClient = await Self.app.models.Client.count({id: oldData.id});
if (isClient) {
const loopBackContext = LoopBackContext.getCurrentContext();
const userId = loopBackContext.active.accessToken.userId;
const logRecord = {
originFk: oldData.id,
userFk: userId,
action: 'update',
changedModel: 'VnUser',
oldInstance: {name: oldData.name, active: oldData.active},
newInstance: {name: changes.name, active: changes.active}
};
await Self.app.models.ClientLog.create(logRecord);
}
}
});
});

View File

@ -1,165 +0,0 @@
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
module.exports = Self => {
Self.remoteMethodCtx('addBuy', {
description: 'Inserts a new buy for the current entry',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'The entry id',
http: {source: 'path'}
},
{
arg: 'itemFk',
type: 'number',
required: true
},
{
arg: 'quantity',
type: 'number',
required: true
},
{
arg: 'packageFk',
type: 'string',
required: true
},
{
arg: 'packing',
type: 'number',
},
{
arg: 'grouping',
type: 'number'
},
{
arg: 'weight',
type: 'number',
},
{
arg: 'stickers',
type: 'number',
},
{
arg: 'price2',
type: 'number',
},
{
arg: 'price3',
type: 'number',
},
{
arg: 'buyingValue',
type: 'number'
}],
returns: {
type: 'object',
root: true
},
http: {
path: `/:id/addBuy`,
verb: 'POST'
}
});
Self.addBuy = async(ctx, options) => {
const conn = Self.dataSource.connector;
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
try {
const models = Self.app.models;
ctx.args.entryFk = ctx.args.id;
// remove unwanted properties
delete ctx.args.id;
delete ctx.args.ctx;
const newBuy = await models.Buy.create(ctx.args, myOptions);
const filter = {
fields: [
'id',
'itemFk',
'stickers',
'packing',
'grouping',
'quantity',
'packageFk',
'weight',
'buyingValue',
'price2',
'price3'
],
include: {
relation: 'item',
scope: {
fields: [
'id',
'typeFk',
'name',
'size',
'minPrice',
'tag5',
'value5',
'tag6',
'value6',
'tag7',
'value7',
'tag8',
'value8',
'tag9',
'value9',
'tag10',
'value10',
'groupingMode'
],
include: {
relation: 'itemType',
scope: {
fields: ['code', 'description']
}
}
}
}
};
const stmts = [];
let stmt;
stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc');
stmt = new ParameterizedSQL(
`CREATE TEMPORARY TABLE tmp.buyRecalc
(INDEX (id))
ENGINE = MEMORY
SELECT ? AS id`, [newBuy.id]);
stmts.push(stmt);
stmts.push('CALL buy_recalcPrices()');
const sql = ParameterizedSQL.join(stmts, ';');
await conn.executeStmt(sql, myOptions);
const buy = await models.Buy.findById(newBuy.id, filter, myOptions);
if (tx) await tx.commit();
return buy;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};

View File

@ -75,7 +75,7 @@ module.exports = Self => {
value[field] = newValue;
if (filter) {
ctx.args.filter = {where: filter, limit: null};
ctx.args = {where: filter, limit: null};
lines = await models.Buy.latestBuysFilter(ctx, null, myOptions);
}

View File

@ -1,42 +0,0 @@
const models = require('vn-loopback/server/server').models;
const LoopBackContext = require('loopback-context');
describe('entry addBuy()', () => {
const activeCtx = {
accessToken: {userId: 18},
};
const ctx = {
req: activeCtx
};
const entryId = 2;
it('should create a new buy for the given entry', async() => {
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
const itemId = 4;
const quantity = 10;
ctx.args = {
id: entryId,
itemFk: itemId,
quantity: quantity,
packageFk: 3
};
const tx = await models.Entry.beginTransaction({});
const options = {transaction: tx};
try {
const newBuy = await models.Entry.addBuy(ctx, options);
expect(newBuy.itemFk).toEqual(itemId);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -53,7 +53,36 @@ describe('Buy editLatestsBuys()', () => {
const options = {transaction: tx};
try {
const filter = {'i.typeFk': 1};
const filter = {'categoryFk': 1, 'tags': []};
const ctx = {
args: {
filter: filter
},
req: {accessToken: {userId: 1}}
};
const field = 'size';
const newValue = 88;
await models.Buy.editLatestBuys(ctx, field, newValue, null, filter, options);
const [result] = await models.Buy.latestBuysFilter(ctx, null, options);
expect(result[field]).toEqual(newValue);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should change the value of a given column for filter tags', async() => {
const tx = await models.Buy.beginTransaction({});
const options = {transaction: tx};
try {
const filter = {'tags': [{tagFk: 1, value: 'Brown'}]};
const ctx = {
args: {
filter: filter

View File

@ -3,7 +3,6 @@ module.exports = Self => {
require('../methods/entry/filter')(Self);
require('../methods/entry/getEntry')(Self);
require('../methods/entry/getBuys')(Self);
require('../methods/entry/addBuy')(Self);
require('../methods/entry/importBuys')(Self);
require('../methods/entry/importBuysPreview')(Self);
require('../methods/entry/lastItemBuys')(Self);

View File

@ -222,13 +222,6 @@
</vn-data-viewer>
<div fixed-bottom-right>
<vn-vertical style="align-items: center;">
<vn-button class="round md vn-mb-sm"
ng-click="model.insert({})"
icon="add"
vn-tooltip="Add buy"
tooltip-position="left"
vn-bind="+">
</vn-button>
<a ui-sref="entry.card.buy.import" >
<vn-button class="round md vn-mb-sm"
icon="publish"

View File

@ -13,11 +13,6 @@ export default class Controller extends Section {
query: `Buys/${buy.id}`,
method: 'patch'
};
} else {
options = {
query: `Entries/${this.entry.id}/addBuy`,
method: 'post'
};
}
this.$http[options.method](options.query, buy).then(res => {
if (!res.data) return;

View File

@ -25,17 +25,6 @@ describe('Entry buy', () => {
controller.saveBuy(buy);
$httpBackend.flush();
});
it(`should call the entry addBuy post route if the received buy has no ID`, () => {
controller.entry = {id: 1};
const buy = {itemFk: 1, quantity: 1, packageFk: 1};
const query = `Entries/${controller.entry.id}/addBuy`;
$httpBackend.expectPOST(query).respond(200);
controller.saveBuy(buy);
$httpBackend.flush();
});
});
describe('deleteBuys()', () => {

View File

@ -1,5 +1,4 @@
const UserError = require('vn-loopback/util/user-error');
const print = require('vn-print');
module.exports = Self => {
Self.remoteMethodCtx('createPdf', {
@ -25,56 +24,28 @@ module.exports = Self => {
Self.createPdf = async function(ctx, id, options) {
const models = Self.app.models;
if (process.env.NODE_ENV == 'test')
throw new UserError(`Action not allowed on the test environment`);
options = typeof options == 'object'
? Object.assign({}, options) : {};
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
if (!options.transaction)
tx = options.transaction = await Self.beginTransaction({});
try {
const invoiceOut = await Self.findById(id, null, myOptions);
const canCreatePdf = await models.ACL.checkAccessAcl(ctx, 'InvoiceOut', 'canCreatePdf', 'WRITE');
const invoiceOut = await Self.findById(id, {fields: ['hasPdf']}, options);
if (invoiceOut.hasPdf && !canCreatePdf)
throw new UserError(`You don't have enough privileges`);
if (invoiceOut.hasPdf) {
const canCreatePdf = await models.ACL.checkAccessAcl(ctx, 'InvoiceOut', 'canCreatePdf', 'WRITE');
if (!canCreatePdf)
throw new UserError(`You don't have enough privileges`);
}
await invoiceOut.updateAttributes({
hasPdf: true
}, myOptions);
const invoiceReport = new print.Report('invoice', {
reference: invoiceOut.ref,
recipientId: invoiceOut.clientFk
});
const buffer = await invoiceReport.toPdfStream();
const issued = invoiceOut.issued;
const year = issued.getFullYear().toString();
const month = (issued.getMonth() + 1).toString();
const day = issued.getDate().toString();
const fileName = `${year}${invoiceOut.ref}.pdf`;
// Store invoice
await print.storage.write(buffer, {
type: 'invoice',
path: `${year}/${month}/${day}`,
fileName: fileName
});
await Self.makePdf(id, options);
if (tx) await tx.commit();
} catch (e) {
} catch (err) {
if (tx) await tx.rollback();
throw e;
throw err;
}
};
};

View File

@ -1,6 +1,5 @@
const fs = require('fs-extra');
const path = require('path');
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('download', {
@ -37,45 +36,43 @@ module.exports = Self => {
Self.download = async function(ctx, id, options) {
const models = Self.app.models;
const myOptions = {};
options = typeof options == 'object'
? Object.assign({}, options) : {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const pdfFile = await Self.filePath(id, options);
const container = await models.InvoiceContainer.container(pdfFile.year);
const rootPath = container.client.root;
const file = {
path: path.join(rootPath, pdfFile.path, pdfFile.name),
contentType: 'application/pdf',
name: pdfFile.name
};
try {
const invoiceOut = await models.InvoiceOut.findById(id, null, myOptions);
await fs.access(file.path);
} catch (error) {
await Self.createPdf(ctx, id, options);
}
const issued = invoiceOut.issued;
const year = issued.getFullYear().toString();
const month = (issued.getMonth() + 1).toString();
const day = issued.getDate().toString();
const container = await models.InvoiceContainer.container(year);
const rootPath = container.client.root;
const src = path.join(rootPath, year, month, day);
const fileName = `${year}${invoiceOut.ref}.pdf`;
const fileSrc = path.join(src, fileName);
const file = {
path: fileSrc,
contentType: 'application/pdf',
name: fileName
};
let stream = await fs.createReadStream(file.path);
// XXX: To prevent unhandled ENOENT error
// https://stackoverflow.com/questions/17136536/is-enoent-from-fs-createreadstream-uncatchable
stream.on('error', err => {
const e = new Error(err.message);
err.stack = e.stack;
console.error(err);
});
if (process.env.NODE_ENV == 'test') {
try {
await fs.access(file.path);
} catch (error) {
await Self.createPdf(ctx, id, myOptions);
stream = null;
}
const stream = fs.createReadStream(file.path);
return [stream, file.contentType, `filename="${file.name}"`];
} catch (error) {
if (error.code === 'ENOENT')
throw new UserError('The PDF document does not exists');
throw error;
}
return [stream, file.contentType, `filename="${pdfFile.name}"`];
};
};

View File

@ -30,15 +30,10 @@ module.exports = Self => {
type: 'number',
description: 'The company id to invoice',
required: true
}, {
arg: 'printerFk',
type: 'number',
description: 'The printer to print',
required: true
}
],
returns: {
type: 'object',
type: 'number',
root: true
},
http: {
@ -50,26 +45,22 @@ module.exports = Self => {
Self.invoiceClient = async(ctx, options) => {
const args = ctx.args;
const models = Self.app.models;
const myOptions = {userId: ctx.req.accessToken.userId};
options = typeof options == 'object'
? Object.assign({}, options) : {};
options.userId = ctx.req.accessToken.userId;
let tx;
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
if (!options.transaction)
tx = options.transaction = await Self.beginTransaction({});
const minShipped = Date.vnNew();
minShipped.setFullYear(args.maxShipped.getFullYear() - 1);
let invoiceId;
let invoiceOut;
try {
const client = await models.Client.findById(args.clientId, {
fields: ['id', 'hasToInvoiceByAddress']
}, myOptions);
}, options);
if (client.hasToInvoiceByAddress) {
await Self.rawSql('CALL ticketToInvoiceByAddress(?, ?, ?, ?)', [
@ -77,49 +68,58 @@ module.exports = Self => {
args.maxShipped,
args.addressId,
args.companyFk
], myOptions);
], options);
} else {
await Self.rawSql('CALL invoiceFromClient(?, ?, ?)', [
args.maxShipped,
client.id,
args.companyFk
], myOptions);
], options);
}
// Make invoice
const isSpanishCompany = await getIsSpanishCompany(args.companyFk, myOptions);
// Check negative bases
// Validates ticket nagative base
const hasAnyNegativeBase = await getNegativeBase(myOptions);
let query =
`SELECT COUNT(*) isSpanishCompany
FROM supplier s
JOIN country c ON c.id = s.countryFk
AND c.code = 'ES'
WHERE s.id = ?`;
const [supplierCompany] = await Self.rawSql(query, [
args.companyFk
], options);
const isSpanishCompany = supplierCompany?.isSpanishCompany;
query = 'SELECT hasAnyNegativeBase() AS base';
const [result] = await Self.rawSql(query, null, options);
const hasAnyNegativeBase = result?.base;
if (hasAnyNegativeBase && isSpanishCompany)
throw new UserError('Negative basis');
// Invoicing
query = `SELECT invoiceSerial(?, ?, ?) AS serial`;
const [invoiceSerial] = await Self.rawSql(query, [
client.id,
args.companyFk,
'G'
], myOptions);
], options);
const serialLetter = invoiceSerial.serial;
query = `CALL invoiceOut_new(?, ?, NULL, @invoiceId)`;
await Self.rawSql(query, [
serialLetter,
args.invoiceDate
], myOptions);
], options);
const [newInvoice] = await Self.rawSql(`SELECT @invoiceId id`, null, myOptions);
if (newInvoice.id) {
await Self.rawSql('CALL invoiceOutBooking(?)', [newInvoice.id], myOptions);
const [newInvoice] = await Self.rawSql(`SELECT @invoiceId id`, null, options);
if (!newInvoice)
throw new UserError('No tickets to invoice', 'notInvoiced');
invoiceOut = await models.InvoiceOut.findById(newInvoice.id, {
include: {
relation: 'client'
}
}, myOptions);
invoiceId = newInvoice.id;
}
await Self.rawSql('CALL invoiceOutBooking(?)', [newInvoice.id], options);
invoiceId = newInvoice.id;
if (tx) await tx.commit();
} catch (e) {
@ -127,47 +127,6 @@ module.exports = Self => {
throw e;
}
if (invoiceId) {
if (!invoiceOut.client().isToBeMailed) {
const query = `
CALL vn.report_print(
'invoice',
?,
account.myUser_getId(),
JSON_OBJECT('refFk', ?),
'normal'
);`;
await models.InvoiceOut.rawSql(query, [args.printerFk, invoiceOut.ref]);
} else {
ctx.args = {
reference: invoiceOut.ref,
recipientId: invoiceOut.clientFk,
recipient: invoiceOut.client().email
};
await models.InvoiceOut.invoiceEmail(ctx, invoiceOut.ref);
}
}
return invoiceId;
};
async function getNegativeBase(options) {
const models = Self.app.models;
const query = 'SELECT hasAnyNegativeBase() AS base';
const [result] = await models.InvoiceOut.rawSql(query, null, options);
return result && result.base;
}
async function getIsSpanishCompany(companyId, options) {
const models = Self.app.models;
const query = `SELECT COUNT(*) isSpanishCompany
FROM supplier s
JOIN country c ON c.id = s.countryFk
AND c.code = 'ES'
WHERE s.id = ?`;
const [supplierCompany] = await models.InvoiceOut.rawSql(query, [
companyId
], options);
return supplierCompany && supplierCompany.isSpanishCompany;
}
};

View File

@ -1,3 +1,4 @@
const UserError = require('vn-loopback/util/user-error');
const {Email} = require('vn-print');
module.exports = Self => {
@ -10,20 +11,17 @@ module.exports = Self => {
type: 'string',
required: true,
http: {source: 'path'}
},
{
}, {
arg: 'recipient',
type: 'string',
description: 'The recipient email',
required: true,
},
{
}, {
arg: 'replyTo',
type: 'string',
description: 'The sender email to reply to',
required: false
},
{
}, {
arg: 'recipientId',
type: 'number',
description: 'The recipient id to send to the recipient preferred language',
@ -42,16 +40,13 @@ module.exports = Self => {
Self.invoiceEmail = async(ctx, reference) => {
const args = Object.assign({}, ctx.args);
const {InvoiceOut} = Self.app.models;
const params = {
recipient: args.recipient,
lang: ctx.req.getLocale()
};
const invoiceOut = await InvoiceOut.findOne({
where: {
ref: reference
}
const invoiceOut = await Self.findOne({
where: {ref: reference}
});
delete args.ctx;
@ -74,6 +69,10 @@ module.exports = Self => {
]
};
return email.send(mailOptions);
try {
return email.send(mailOptions);
} catch (err) {
throw new UserError('Error when sending mail to client', 'mailNotSent');
}
};
};

View File

@ -0,0 +1,87 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('makePdfAndNotify', {
description: 'Create invoice PDF and send it to client',
accessType: 'WRITE',
accepts: [
{
arg: 'id',
type: 'number',
description: 'The invoice id',
required: true,
http: {source: 'path'}
}, {
arg: 'printerFk',
type: 'number',
description: 'The printer to print',
required: true
}
],
http: {
path: '/:id/makePdfAndNotify',
verb: 'POST'
}
});
Self.makePdfAndNotify = async function(ctx, id, printerFk) {
const models = Self.app.models;
options = typeof options == 'object'
? Object.assign({}, options) : {};
options.userId = ctx.req.accessToken.userId;
try {
await Self.makePdf(id, options);
} catch (err) {
console.error(err);
throw new UserError('Error while generating PDF', 'pdfError');
}
const invoiceOut = await Self.findById(id, {
fields: ['ref', 'clientFk'],
include: {
relation: 'client',
scope: {
fields: ['id', 'email', 'isToBeMailed', 'salesPersonFk']
}
}
}, options);
const ref = invoiceOut.ref;
const client = invoiceOut.client();
if (client.isToBeMailed) {
try {
ctx.args = {
reference: ref,
recipientId: client.id,
recipient: client.email
};
await Self.invoiceEmail(ctx, ref);
} catch (err) {
const origin = ctx.req.headers.origin;
const message = ctx.req.__('Mail not sent', {
clientId: client.id,
clientUrl: `${origin}/#!/claim/${id}/summary`
});
const salesPersonId = client.salesPersonFk;
if (salesPersonId)
await models.Chat.sendCheckingPresence(ctx, salesPersonId, message);
throw new UserError('Error when sending mail to client', 'mailNotSent');
}
} else {
const query = `
CALL vn.report_print(
'invoice',
?,
account.myUser_getId(),
JSON_OBJECT('refFk', ?),
'normal'
);`;
await Self.rawSql(query, [printerFk, ref], options);
}
};
};

View File

@ -1,28 +0,0 @@
const models = require('vn-loopback/server/server').models;
const fs = require('fs-extra');
describe('InvoiceOut download()', () => {
const userId = 9;
const invoiceId = 1;
const ctx = {
req: {
accessToken: {userId: userId},
headers: {origin: 'http://localhost:5000'},
}
};
it('should return the downloaded file name', async() => {
spyOn(models.InvoiceContainer, 'container').and.returnValue({
client: {root: '/path'}
});
spyOn(fs, 'createReadStream').and.returnValue(new Promise(resolve => resolve('streamObject')));
spyOn(fs, 'access').and.returnValue(true);
spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true)));
const result = await models.InvoiceOut.download(ctx, invoiceId);
expect(result[1]).toEqual('application/pdf');
expect(result[2]).toMatch(/filename="\d{4}T1111111.pdf"/);
});
});

View File

@ -18,12 +18,14 @@ describe('InvoiceOut invoiceClient()', () => {
accessToken: {userId: userId},
__: value => {
return value;
}
},
headers: {origin: 'http://localhost'}
};
const ctx = {req: activeCtx};
it('should make a global invoicing', async() => {
spyOn(models.InvoiceOut, 'createPdf').and.returnValue(new Promise(resolve => resolve(true)));
spyOn(models.InvoiceOut, 'makePdf').and.returnValue(new Promise(resolve => resolve(true)));
spyOn(models.InvoiceOut, 'invoiceEmail');
const tx = await models.InvoiceOut.beginTransaction({});

View File

@ -2,6 +2,9 @@
"InvoiceOut": {
"dataSource": "vn"
},
"InvoiceOutConfig": {
"dataSource": "vn"
},
"InvoiceOutSerial": {
"dataSource": "vn"
},

View File

@ -0,0 +1,22 @@
{
"name": "InvoiceOutConfig",
"base": "VnModel",
"options": {
"mysql": {
"table": "invoiceOutConfig"
}
},
"properties": {
"id": {
"id": true,
"type": "number",
"description": "Identifier"
},
"parallelism": {
"type": "number",
"required": true
}
}
}

View File

@ -1,3 +1,6 @@
const print = require('vn-print');
const path = require('path');
module.exports = Self => {
require('../methods/invoiceOut/filter')(Self);
require('../methods/invoiceOut/summary')(Self);
@ -10,6 +13,7 @@ module.exports = Self => {
require('../methods/invoiceOut/createManualInvoice')(Self);
require('../methods/invoiceOut/clientsToInvoice')(Self);
require('../methods/invoiceOut/invoiceClient')(Self);
require('../methods/invoiceOut/makePdfAndNotify')(Self);
require('../methods/invoiceOut/refund')(Self);
require('../methods/invoiceOut/invoiceEmail')(Self);
require('../methods/invoiceOut/exportationPdf')(Self);
@ -19,4 +23,45 @@ module.exports = Self => {
require('../methods/invoiceOut/getInvoiceDate')(Self);
require('../methods/invoiceOut/negativeBases')(Self);
require('../methods/invoiceOut/negativeBasesCsv')(Self);
Self.filePath = async function(id, options) {
const fields = ['ref', 'issued'];
const invoiceOut = await Self.findById(id, {fields}, options);
const issued = invoiceOut.issued;
const year = issued.getFullYear().toString();
const month = (issued.getMonth() + 1).toString();
const day = issued.getDate().toString();
return {
path: path.join(year, month, day),
name: `${year}${invoiceOut.ref}.pdf`,
year
};
};
Self.makePdf = async function(id, options) {
const fields = ['id', 'hasPdf', 'ref'];
const invoiceOut = await Self.findById(id, {fields}, options);
const invoiceReport = new print.Report('invoice', {
reference: invoiceOut.ref
});
const buffer = await invoiceReport.toPdfStream();
const pdfFile = await Self.filePath(id, options);
// Store invoice
await invoiceOut.updateAttributes({
hasPdf: true
}, options);
if (process.env.NODE_ENV !== 'test') {
await print.storage.write(buffer, {
type: 'invoice',
path: pdfFile.path,
fileName: pdfFile.name
});
}
};
};

View File

@ -1,7 +1,6 @@
<vn-card
ng-if="$ctrl.status"
class="vn-w-lg vn-pa-md"
style="height: 80px; display: flex; align-items: center; justify-content: center; gap: 20px;">
class="status vn-w-lg vn-pa-md">
<vn-spinner
enable="$ctrl.status != 'done'">
</vn-spinner>
@ -20,8 +19,15 @@
Ended process
</span>
</div>
<div ng-if="$ctrl.nAddresses" class="text-caption text-secondary">
{{$ctrl.percentage | percentage: 0}} ({{$ctrl.addressNumber}} {{'of' | translate}} {{$ctrl.nAddresses}})
<div ng-if="$ctrl.nAddresses">
<div class="text-caption text-secondary">
{{$ctrl.percentage | percentage: 0}}
({{$ctrl.addressNumber}} <span translate>of</span> {{$ctrl.nAddresses}})
</div>
<div class="text-caption text-secondary">
{{$ctrl.nPdfs}} <span translate>of</span> {{$ctrl.totalPdfs}}
<span translate>PDFs</span>
</div>
</div>
</div>
</vn-card>
@ -55,7 +61,11 @@
{{::error.address.nickname}}
</vn-td>
<vn-td expand>
<span class="chip alert">{{::error.message}}</span>
<span
class="chip"
ng-class="error.isWarning ? 'warning': 'alert'">
{{::error.message}}
</span>
</vn-td>
</vn-tr>
</vn-tbody>
@ -137,7 +147,7 @@
<vn-submit
ng-if="$ctrl.invoicing"
label="Stop"
ng-click="$ctrl.stopInvoicing()">
ng-click="$ctrl.status = 'stopping'">
</vn-submit>
</vn-vertical>
</form>

View File

@ -7,32 +7,29 @@ class Controller extends Section {
$onInit() {
const date = Date.vnNew();
Object.assign(this, {
maxShipped: new Date(date.getFullYear(), date.getMonth(), 0),
clientsToInvoice: 'all',
maxShipped: new Date(date.getFullYear(), date.getMonth(), 0),
clientsToInvoice: 'all',
companyFk: this.vnConfig.companyFk,
parallelism: 1
});
this.$http.get('UserConfigs/getUserConfig')
.then(res => {
this.companyFk = res.data.companyFk;
this.getInvoiceDate(this.companyFk);
});
}
const params = {companyFk: this.companyFk};
this.$http.get('InvoiceOuts/getInvoiceDate', {params})
.then(res => {
this.minInvoicingDate = res.data.issued ? new Date(res.data.issued) : null;
this.invoiceDate = this.minInvoicingDate;
});
getInvoiceDate(companyFk) {
const params = { companyFk: companyFk };
this.fetchInvoiceDate(params);
}
fetchInvoiceDate(params) {
this.$http.get('InvoiceOuts/getInvoiceDate', { params })
.then(res => {
this.minInvoicingDate = res.data.issued ? new Date(res.data.issued) : null;
this.invoiceDate = this.minInvoicingDate;
});
}
stopInvoicing() {
this.status = 'stopping';
const filter = {fields: ['parallelism']};
this.$http.get('InvoiceOutConfigs/findOne', {filter})
.then(res => {
if (res.data.parallelism)
this.parallelism = res.data.parallelism;
})
.catch(res => {
if (res.status == 404) return;
throw res;
});
}
makeInvoice() {
@ -49,7 +46,7 @@ class Controller extends Section {
if (this.invoiceDate < this.maxShipped)
throw new UserError('Invoice date can\'t be less than max date');
if (this.minInvoicingDate && this.invoiceDate.getTime() < this.minInvoicingDate.getTime())
throw new UserError('Exists an invoice with a previous date');
throw new UserError('Exists an invoice with a future date');
if (!this.companyFk)
throw new UserError('Choose a valid company');
if (!this.printerFk)
@ -70,8 +67,11 @@ class Controller extends Section {
if (!this.addresses.length)
throw new UserError(`There aren't tickets to invoice`);
this.nRequests = 0;
this.nPdfs = 0;
this.totalPdfs = 0;
this.addressIndex = 0;
return this.invoiceOut();
this.invoiceClient();
})
.catch(err => this.handleError(err));
} catch (err) {
@ -85,8 +85,11 @@ class Controller extends Section {
throw err;
}
invoiceOut() {
if (this.addressIndex == this.addresses.length || this.status == 'stopping') {
invoiceClient() {
if (this.nRequests == this.parallelism || this.isInvoicing) return;
if (this.addressIndex >= this.addresses.length || this.status == 'stopping') {
if (this.nRequests) return;
this.invoicing = false;
this.status = 'done';
return;
@ -95,34 +98,59 @@ class Controller extends Section {
this.status = 'invoicing';
const address = this.addresses[this.addressIndex];
this.currentAddress = address;
this.isInvoicing = true;
const params = {
clientId: address.clientId,
addressId: address.id,
invoiceDate: this.invoiceDate,
maxShipped: this.maxShipped,
companyFk: this.companyFk,
printerFk: this.printerFk,
companyFk: this.companyFk
};
this.$http.post(`InvoiceOuts/invoiceClient`, params)
.then(() => this.invoiceNext())
.then(res => {
this.isInvoicing = false;
if (res.data)
this.makePdfAndNotify(res.data, address);
this.invoiceNext();
})
.catch(res => {
const message = res.data?.error?.message || res.message;
this.isInvoicing = false;
if (res.status >= 400 && res.status < 500) {
this.errors.unshift({address, message});
this.invoiceError(address, res);
this.invoiceNext();
} else {
this.invoicing = false;
this.status = 'done';
throw new UserError(`Critical invoicing error, proccess stopped`);
}
})
});
}
invoiceNext() {
this.addressIndex++;
this.invoiceOut();
this.invoiceClient();
}
makePdfAndNotify(invoiceId, address) {
this.nRequests++;
this.totalPdfs++;
const params = {printerFk: this.printerFk};
this.$http.post(`InvoiceOuts/${invoiceId}/makePdfAndNotify`, params)
.catch(res => {
this.invoiceError(address, res, true);
})
.finally(() => {
this.nPdfs++;
this.nRequests--;
this.invoiceClient();
});
}
invoiceError(address, res, isWarning) {
const message = res.data?.error?.message || res.message;
this.errors.unshift({address, message, isWarning});
}
get nAddresses() {

View File

@ -10,6 +10,7 @@ Build packaging tickets: Generando tickets de embalajes
Address id: Id dirección
Printer: Impresora
of: de
PDFs: PDFs
Client: Cliente
Current client id: Id cliente actual
Invoicing client: Facturando cliente

View File

@ -1,17 +1,21 @@
@import "variables";
vn-invoice-out-global-invoicing{
h5{
vn-invoice-out-global-invoicing {
h5 {
color: $color-primary;
}
.status {
height: 80px;
display: flex;
align-items: center;
justify-content: center;
gap: 20px;
}
#error {
line-break: normal;
overflow-wrap: break-word;
white-space: normal;
}
}

View File

@ -21,7 +21,6 @@ module.exports = Self => {
Self.guessPriority = async(ctx, id) => {
const userId = ctx.req.accessToken.userId;
const $t = ctx.req.__; // $translate
const query = `CALL vn.routeGuessPriority(?)`;
const tx = await Self.beginTransaction({});
@ -30,16 +29,6 @@ module.exports = Self => {
const priority = await Self.rawSql(query, [id], options);
let logRecord = {
originFk: id,
userFk: userId,
action: 'update',
changedModel: 'Route',
description: $t('Sorts whole route')
};
await Self.app.models.RouteLog.create(logRecord, options);
await tx.commit();
return priority;
} catch (e) {

View File

@ -31,18 +31,6 @@ describe('route updateVolume()', () => {
const updatedRoute = await app.models.Route.findById(routeId, null, options);
expect(updatedRoute.m3).not.toEqual(route.m3);
const logs = await app.models.RouteLog.find({
fields: ['id', 'newInstance']
}, options);
const m3Log = logs.filter(log => {
if (log.newInstance)
return log.newInstance.m3 === updatedRoute.m3;
});
expect(m3Log.length).toEqual(1);
await tx.rollback();
} catch (e) {
await tx.rollback();

View File

@ -35,24 +35,9 @@ module.exports = Self => {
}
try {
const originalRoute = await models.Route.findById(id, null, myOptions);
await Self.rawSql(`CALL vn.routeUpdateM3(?)`, [id], myOptions);
const updatedRoute = await models.Route.findById(id, null, myOptions);
await models.RouteLog.create({
originFk: id,
userFk: userId,
action: 'update',
changedModel: 'Route',
changedModelId: id,
oldInstance: {m3: originalRoute.m3},
newInstance: {m3: updatedRoute.m3}
}, myOptions);
if (tx) await tx.commit();
return updatedRoute;
} catch (e) {
if (tx) await tx.rollback();

View File

@ -106,7 +106,7 @@ module.exports = Self => {
}
}
const query = `CALL vn.ticket_recalc(?)`;
const query = `CALL vn.ticket_recalc(?, NULL)`;
await Self.rawSql(query, [refundTicket.id], myOptions);
if (tx) await tx.commit();

View File

@ -110,4 +110,53 @@ describe('sale updateQuantity()', () => {
throw e;
}
});
it('should throw an error if the quantity is negative and it is not a refund ticket', async() => {
const ctx = {
req: {
accessToken: {userId: 1},
headers: {origin: 'localhost:5000'},
__: () => {}
}
};
const saleId = 17;
const newQuantity = -10;
const tx = await models.Sale.beginTransaction({});
let error;
try {
const options = {transaction: tx};
await models.Sale.updateQuantity(ctx, saleId, newQuantity, options);
await tx.rollback();
} catch (e) {
await tx.rollback();
error = e;
}
expect(error).toEqual(new Error('You can only add negative amounts in refund tickets'));
});
it('should update a negative quantity when is a ticket refund', async() => {
const tx = await models.Sale.beginTransaction({});
const saleId = 13;
const newQuantity = -10;
try {
const options = {transaction: tx};
await models.Sale.updateQuantity(ctx, saleId, newQuantity, options);
const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options);
expect(modifiedLine.quantity).toEqual(newQuantity);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -96,7 +96,7 @@ module.exports = Self => {
await sale.updateAttributes({price: newPrice}, myOptions);
await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions);
await Self.rawSql('CALL vn.ticket_recalc(?)', [sale.ticketFk], myOptions);
await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [sale.ticketFk], myOptions);
const salesPerson = sale.ticket().client().salesPersonUser();
if (salesPerson) {

View File

@ -68,6 +68,13 @@ module.exports = Self => {
if (newQuantity > sale.quantity && !isRoleAdvanced)
throw new UserError('The new quantity should be smaller than the old one');
const ticketRefund = await models.TicketRefund.findOne({
where: {refundTicketFk: sale.ticketFk},
fields: ['id']}
, myOptions);
if (newQuantity < 0 && !ticketRefund)
throw new UserError('You can only add negative amounts in refund tickets');
const oldQuantity = sale.quantity;
const result = await sale.updateAttributes({quantity: newQuantity}, myOptions);

View File

@ -97,22 +97,6 @@ module.exports = Self => {
});
await models.Chat.sendCheckingPresence(ctx, requesterId, message, myOptions);
const logRecord = {
originFk: sale.ticketFk,
userFk: userId,
action: 'update',
changedModel: 'ticketRequest',
newInstance: {
destinationFk: sale.ticketFk,
quantity: sale.quantity,
concept: sale.concept,
itemId: sale.itemFk,
ticketId: sale.ticketFk,
}
};
await Self.app.models.TicketLog.create(logRecord, myOptions);
if (tx) await tx.commit();
return sale;

View File

@ -85,7 +85,7 @@ module.exports = Self => {
}, myOptions);
await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id], myOptions);
await Self.rawSql('CALL vn.ticket_recalc(?)', [id], myOptions);
await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [id], myOptions);
const sale = await models.Sale.findById(newSale.id, {
include: {

View File

@ -242,16 +242,6 @@ module.exports = Self => {
const oldProperties = await loggable.translateValues(Self, changes.old);
const newProperties = await loggable.translateValues(Self, changes.new);
await models.TicketLog.create({
originFk: args.id,
userFk: userId,
action: 'update',
changedModel: 'Ticket',
changedModelId: args.id,
oldInstance: oldProperties,
newInstance: newProperties
}, myOptions);
const salesPersonId = originalTicket.client().salesPersonFk;
if (salesPersonId) {
const origin = ctx.req.headers.origin;

View File

@ -52,22 +52,9 @@ module.exports = Self => {
});
if (!ticket.originId || !ticket.destinationId) continue;
const ticketDestinationLogRecord = {
originFk: ticket.destinationId,
userFk: ctx.req.accessToken.userId,
action: 'update',
changedModel: 'Ticket',
changedModelId: ticket.destinationId,
changedModelValue: ticket.destinationId,
oldInstance: {},
newInstance: {mergedTicket: ticket.originId}
};
await models.Sale.updateAll({ticketFk: ticket.originId}, {ticketFk: ticket.destinationId}, myOptions);
if (await models.Ticket.setDeleted(ctx, ticket.originId, myOptions)) {
await models.TicketLog.create(ticketDestinationLogRecord, myOptions);
if (await models.Ticket.setDeleted(ctx, ticket.originId, myOptions))
await models.Chat.sendCheckingPresence(ctx, ticket.workerFk, message);
}
}
if (tx)
await tx.commit();

View File

@ -30,54 +30,12 @@ module.exports = Self => {
}
});
Self.sendSms = async(ctx, id, destination, message, options) => {
Self.sendSms = async(ctx, id, destination, message) => {
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 userId = ctx.req.accessToken.userId;
try {
const sms = await models.Sms.send(ctx, destination, message);
const newTicketSms = {
ticketFk: id,
smsFk: sms.id
};
await models.TicketSms.create(newTicketSms);
const logRecord = {
originFk: id,
userFk: userId,
action: 'insert',
changedModel: 'sms',
newInstance: {
destinationFk: id,
destination: destination,
message: message,
statusCode: sms.statusCode,
status: sms.status
}
};
const ticketLog = await models.TicketLog.create(logRecord, myOptions);
sms.logId = ticketLog.id;
if (tx) await tx.commit();
return sms;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
const sms = await models.Sms.send(ctx, destination, message);
await models.TicketSms.create({
ticketFk: id,
smsFk: sms.id
});
};
};

View File

@ -81,17 +81,15 @@ module.exports = Self => {
throw new UserError('You must delete all the buy requests first');
// removes item shelvings
if (hasItemShelvingSales && isSalesAssistant) {
const promises = [];
for (let sale of sales) {
if (sale.itemShelvingSale()) {
const itemShelvingSale = sale.itemShelvingSale();
const destroyedShelving = models.ItemShelvingSale.destroyById(itemShelvingSale.id, myOptions);
promises.push(destroyedShelving);
}
const promises = [];
for (let sale of sales) {
if (sale.itemShelvingSale()) {
const itemShelvingSale = sale.itemShelvingSale();
const destroyedShelving = models.ItemShelvingSale.destroyById(itemShelvingSale.id, myOptions);
promises.push(destroyedShelving);
}
await Promise.all(promises);
}
await Promise.all(promises);
// Remove ticket greuges
const ticketGreuges = await models.Greuge.find({where: {ticketFk: id}}, myOptions);

View File

@ -43,12 +43,10 @@ describe('ticket merge()', () => {
await models.Ticket.merge(ctx, [tickets], options);
const createdTicketLog = await models.TicketLog.find({where: {originFk: tickets.destinationId}}, options);
const deletedTicket = await models.Ticket.findOne({where: {id: tickets.originId}}, options);
const salesTicketFuture = await models.Sale.find({where: {ticketFk: tickets.destinationId}}, options);
const chatNotificationAfterMerge = await models.Chat.find(null, options);
expect(createdTicketLog.length).toEqual(1);
expect(deletedTicket.isDeleted).toEqual(true);
expect(salesTicketFuture.length).toEqual(2);
expect(chatNotificationBeforeMerge.length).toEqual(chatNotificationAfterMerge.length - 2);

View File

@ -12,19 +12,14 @@ describe('ticket sendSms()', () => {
const destination = 222222222;
const message = 'this is the message created in a test';
const sms = await models.Ticket.sendSms(ctx, id, destination, message, options);
const createdLog = await models.TicketLog.findById(sms.logId, null, options);
await models.Ticket.sendSms(ctx, id, destination, message, options);
const filter = {
ticketFk: createdLog.originFk
ticketFk: id
};
const ticketSms = await models.TicketSms.findOne(filter, options);
const json = JSON.parse(JSON.stringify(createdLog.newInstance));
expect(json.message).toEqual(message);
expect(ticketSms.ticketFk).toEqual(createdLog.originFk);
expect(ticketSms.ticketFk).toEqual(id);
await tx.rollback();
} catch (e) {

View File

@ -84,13 +84,6 @@ module.exports = Self => {
for (const sale of sales) {
const originalSale = map.get(sale.id);
const originalSaleData = { // <-- Loopback modifies original instance on save
itemFk: originalSale.itemFk,
quantity: originalSale.quantity,
concept: originalSale.concept,
ticketFk: originalSale.ticketFk
};
if (sale.quantity == originalSale.quantity) {
query = `UPDATE sale
SET ticketFk = ?
@ -100,48 +93,6 @@ module.exports = Self => {
await transferPartialSale(
ticketId, originalSale, sale, myOptions);
}
// Log to original ticket
await models.TicketLog.create({
originFk: id,
userFk: userId,
action: 'update',
changedModel: 'Sale',
changedModelId: sale.id,
oldInstance: {
item: originalSaleData.itemFk,
quantity: originalSaleData.quantity,
concept: originalSaleData.concept,
ticket: originalSaleData.ticketFk
},
newInstance: {
item: sale.itemFk,
quantity: sale.quantity,
concept: sale.concept,
ticket: ticketId
}
}, myOptions);
// Log to destination ticket
await models.TicketLog.create({
originFk: ticketId,
userFk: userId,
action: 'update',
changedModel: 'Sale',
changedModelId: sale.id,
oldInstance: {
item: originalSaleData.itemFk,
quantity: originalSaleData.quantity,
concept: originalSaleData.concept,
ticket: originalSaleData.ticketFk
},
newInstance: {
item: sale.itemFk,
quantity: sale.quantity,
concept: sale.concept,
ticket: ticketId
}
}, myOptions);
}
const isTicketEmpty = await models.Ticket.isEmpty(id, myOptions);

View File

@ -147,7 +147,7 @@ module.exports = Self => {
await Promise.all(promises);
await Self.rawSql('CALL vn.manaSpellersRequery(?)', [userId], myOptions);
await Self.rawSql('CALL vn.ticket_recalc(?)', [id], myOptions);
await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [id], myOptions);
const ticket = await models.Ticket.findById(id, {
include: {

View File

@ -1,30 +1,4 @@
const LoopBackContext = require('loopback-context');
module.exports = Self => {
// Methods
require('./ticket-methods')(Self);
Self.observe('before save', async function(ctx) {
const loopBackContext = LoopBackContext.getCurrentContext();
const httpCtx = loopBackContext.active;
if (ctx.isNewInstance) return;
let changes = ctx.data || ctx.instance;
if (changes.routeFk === null && ctx.currentInstance.routeFk != null) {
let instance = JSON.parse(JSON.stringify(ctx.currentInstance));
let userId = httpCtx.accessToken.userId;
let logRecord = {
originFk: ctx.currentInstance.routeFk,
userFk: userId,
action: 'delete',
changedModel: 'Route',
oldInstance: {ticket: instance.id},
newInstance: null
};
await Self.app.models.RouteLog.create(logRecord);
}
});
};

View File

@ -156,7 +156,7 @@
icon="install_mobile"
ng-show="$ctrl.totalChecked > 0"
ng-click="$ctrl.sendDocuware()"
vn-tooltip="Set as delivered and open delivery note(s)"
vn-tooltip="Set as delivered and send delivery note(s) to the tablet"
tooltip-position="left">
</vn-button>
<vn-button class="round vn-mb-sm"

View File

@ -3,7 +3,7 @@ Go to lines: Ir a lineas
Not available: No disponible
Not visible: No visible
Payment on account...: Pago a cuenta...
Set as delivered and open delivery note(s): Marcar como servido/s y abrir albarán/es
Set as delivered and send delivery note(s) to the tablet: Marcar como servido/s y enviar albarán/es a la tablet
Closure: Cierre
You cannot make a payment on account from multiple clients: No puedes realizar un pago a cuenta de clientes diferentes
Filter by selection: Filtro por selección

View File

@ -25,9 +25,7 @@ module.exports = Self => {
});
Self.cloneWithEntries = async(ctx, id) => {
const userId = ctx.req.accessToken.userId;
const conn = Self.dataSource.connector;
const models = Self.app.models;
const travel = await Self.findById(id, {
fields: [
'id',
@ -81,18 +79,6 @@ module.exports = Self => {
]
});
const oldProperties = await loggable.translateValues(Self, travel);
const newProperties = await loggable.translateValues(Self, newTravel);
await models.TravelLog.create({
originFk: newTravel.id,
userFk: userId,
action: 'insert',
changedModel: 'Travel',
changedModelId: newTravel.id,
oldInstance: oldProperties,
newInstance: newProperties
});
return newTravel.id;
};
};

View File

@ -30,24 +30,8 @@ module.exports = Self => {
SET travelFk = NULL, dmsFk = NULL
WHERE id = ?`, [id], {userId});
const oldInstance = {
travelFk: travelThermograph.travelFk,
dmsFk: travelThermograph.dmsFk
};
await models.TravelLog.create({
originFk: travelThermograph.travelFk,
userFk: userId,
action: 'delete',
changedModel: 'TravelThermograph',
changedModelId: id,
oldInstance: oldInstance,
newInstance: {}
});
travelThermograph.travelFk = null;
travelThermograph.dmsFk = null;
return travelThermograph;
};
};

View File

@ -37,6 +37,16 @@ class Controller extends SearchPanel {
}
applyFilters(param) {
if (typeof this.filter.scopeDays === 'number') {
const shippedFrom = Date.vnNew();
shippedFrom.setHours(0, 0, 0, 0);
const shippedTo = new Date(shippedFrom.getTime());
shippedTo.setDate(shippedTo.getDate() + this.filter.scopeDays);
shippedTo.setHours(23, 59, 59, 999);
Object.assign(this.filter, {shippedFrom, shippedTo});
}
this.model.applyFilter({}, this.filter)
.then(() => {
if (param && this.model._orgData.length === 1)

View File

@ -92,7 +92,7 @@
</span>
</vn-td>
<vn-td expand>{{entry.supplierName}}</vn-td>
<vn-td shrink>{{entry.ref}}</vn-td>
<vn-td shrink>{{entry.reference}}</vn-td>
<vn-td shrink>{{entry.hb}}</vn-td>
<vn-td shrink>{{entry.freightValue | currency: 'EUR': 2}}</vn-td>
<vn-td shrink>{{entry.packageValue | currency: 'EUR': 2}}</vn-td>

View File

@ -40,7 +40,6 @@ module.exports = Self => {
Self.updateWorkerTimeControlMail = async(ctx, options) => {
const models = Self.app.models;
const args = ctx.args;
const userId = ctx.req.accessToken.userId;
const myOptions = {};
@ -57,9 +56,6 @@ module.exports = Self => {
if (!workerTimeControlMail) throw new UserError(`There aren't records for this week`);
const oldState = workerTimeControlMail.state;
const oldReason = workerTimeControlMail.reason;
await workerTimeControlMail.updateAttributes({
state: args.state,
reason: args.reason || null
@ -70,22 +66,5 @@ module.exports = Self => {
sendedCounter: workerTimeControlMail.sendedCounter + 1
}, myOptions);
}
const logRecord = {
originFk: args.workerId,
userFk: userId,
action: 'update',
changedModel: 'WorkerTimeControlMail',
oldInstance: {
state: oldState,
reason: oldReason
},
newInstance: {
state: args.state,
reason: args.reason
}
};
return models.WorkerLog.create(logRecord, myOptions);
};
};

View File

@ -1,10 +1,10 @@
module.exports = function(Self) {
Self.observe('after save', async function(ctx) {
const instance = ctx.instance;
const instance = ctx.data || ctx.instance;
const models = Self.app.models;
const options = ctx.options;
if (!instance.sectorFk || !instance.labelerFk) return;
if (!instance?.sectorFk || !instance?.labelerFk) return;
const sector = await models.Sector.findById(instance.sectorFk, {
fields: ['mainPrinterFk']

View File

@ -16,18 +16,12 @@
"type": "number"
},
"trainFk": {
"type": "number",
"required": true
"type": "number"
},
"itemPackingTypeFk": {
"type": "string",
"required": true
"type": "string"
},
"warehouseFk": {
"type": "number",
"required": true
},
"sectorFk": {
"type": "number"
},
"labelerFk": {

View File

@ -3,27 +3,35 @@
data="absenceTypes"
auto-load="true">
</vn-crud-model>
<div class="vn-w-lg">
<vn-card class="vn-pa-sm calendars">
<vn-icon ng-if="::$ctrl.isSubordinate" icon="info" color-marginal
vn-tooltip="To start adding absences, click an absence type from the right menu and then on the day you want to add an absence">
</vn-icon>
<vn-calendar
ng-repeat="month in $ctrl.months"
data="$ctrl.events"
default-date="month"
format-day="$ctrl.formatDay($day, $element)"
display-controls="false"
hide-contiguous="true"
hide-year="true"
on-selection="$ctrl.onSelection($event, $days)">
</vn-calendar>
</vn-card>
<div ng-if="$ctrl.worker.hasWorkCenter">
<div class="vn-w-lg">
<vn-card class="vn-pa-sm calendars">
<vn-icon ng-if="::$ctrl.isSubordinate" icon="info" color-marginal
vn-tooltip="To start adding absences, click an absence type from the right menu and then on the day you want to add an absence">
</vn-icon>
<vn-calendar
ng-repeat="month in $ctrl.months"
data="$ctrl.events"
default-date="month"
format-day="$ctrl.formatDay($day, $element)"
display-controls="false"
hide-contiguous="true"
hide-year="true"
on-selection="$ctrl.onSelection($event, $days)">
</vn-calendar>
</vn-card>
</div>
</div>
<div
ng-if="!$ctrl.worker.hasWorkCenter"
class="bg-title"
translate>
Autonomous worker
</div>
<vn-side-menu side="right">
<div class="vn-pa-md">
<div class="totalBox vn-mb-sm" style="text-align: center;">
<h6>{{'Contract' | translate}} #{{$ctrl.businessId}}</h6>
<h6>{{'Contract' | translate}} #{{$ctrl.card.worker.hasWorkCenter}}</h6>
<div>
{{'Used' | translate}} {{$ctrl.contractHolidays.holidaysEnjoyed || 0}}
{{'of' | translate}} {{$ctrl.contractHolidays.totalHolidays || 0}} {{'days' | translate}}
@ -63,7 +71,6 @@
ng-model="$ctrl.businessId"
search-function="{businessFk: $search}"
value-field="businessFk"
show-field="businessFk"
order="businessFk DESC"
limit="5">
<tpl-item>
@ -103,3 +110,4 @@
message="This item will be deleted"
question="Are you sure you want to continue?">
</vn-confirm>

View File

@ -64,8 +64,7 @@ class Controller extends Section {
set worker(value) {
this._worker = value;
if (value) {
if (value && value.hasWorkCenter) {
this.getIsSubordinate();
this.getActiveContract();
}

View File

@ -74,7 +74,7 @@ describe('Worker', () => {
let yesterday = new Date(today.getTime());
yesterday.setDate(yesterday.getDate() - 1);
controller.worker = {id: 1107};
controller.worker = {id: 1107, hasWorkCenter: true};
expect(controller.getIsSubordinate).toHaveBeenCalledWith();
expect(controller.getActiveContract).toHaveBeenCalledWith();

View File

@ -12,3 +12,4 @@ To start adding absences, click an absence type from the right menu and then on
You can just add absences within the current year: Solo puedes añadir ausencias dentro del año actual
Current day: Día actual
Paid holidays: Vacaciones pagadas
Autonomous worker: Trabajador autónomo

View File

@ -34,6 +34,10 @@ class Controller extends ModuleCard {
this.$http.get(`Workers/${this.$params.id}`, {filter})
.then(res => this.worker = res.data);
this.$http.get(`Workers/${this.$params.id}/activeContract`)
.then(res => {
if (res.data) this.worker.hasWorkCenter = res.data.workCenterFk;
});
}
}

View File

@ -4,106 +4,114 @@
filter="::$ctrl.filter"
data="$ctrl.hours">
</vn-crud-model>
<vn-card class="vn-pa-lg vn-w-lg">
<vn-table model="model" auto-load="false">
<vn-thead>
<vn-tr>
<vn-td ng-repeat="weekday in $ctrl.weekDays" center>
<div class="weekday" translate>{{::$ctrl.weekdayNames[$index].name}}</div>
<div>
<span>{{::weekday.dated | date: 'dd'}}</span>
<span title="{{::weekday.dated | date: 'MMMM' | translate}}" translate>
{{::weekday.dated | date: 'MMMM'}}
</span>
</div>
<vn-chip
title="{{::weekday.event.name}}"
ng-class="{invisible: !weekday.event}">
<vn-avatar
ng-style="::{backgroundColor: weekday.event.color}">
</vn-avatar>
<div ng-if="$ctrl.worker.hasWorkCenter">
<vn-card class="vn-pa-lg vn-w-lg">
<vn-table model="model" auto-load="false">
<vn-thead>
<vn-tr>
<vn-td ng-repeat="weekday in $ctrl.weekDays" center>
<div class="weekday" translate>{{::$ctrl.weekdayNames[$index].name}}</div>
<div>
{{::weekday.event.name}}
<span>{{::weekday.dated | date: 'dd'}}</span>
<span title="{{::weekday.dated | date: 'MMMM' | translate}}" translate>
{{::weekday.dated | date: 'MMMM'}}
</span>
</div>
</vn-chip>
</vn-td>
</vn-tr>
</vn-thead>
<vn-tbody>
<vn-tr>
<vn-td ng-repeat="weekday in $ctrl.weekDays" class="hours vn-pa-none" expand>
<section ng-repeat="hour in weekday.hours">
<vn-icon
icon="{{
::hour.direction == 'in' ? 'arrow_forward' : 'arrow_back'
}}"
title="{{
::(hour.direction == 'in' ? 'In' : 'Out') | translate
}}"
ng-class="::{'invisible': hour.direction == 'middle'}">
</vn-icon>
<vn-chip
ng-class="::{'colored': hour.manual, 'clickable': true}"
removable="::hour.manual"
on-remove="$ctrl.showDeleteDialog($event, hour)"
ng-click="$ctrl.edit($event, hour)"
>
<prepend>
<vn-icon icon="edit"
vn-tooltip="Edit">
</vn-icon>
</prepend>
{{::hour.timed | date: 'HH:mm'}}
title="{{::weekday.event.name}}"
ng-class="{invisible: !weekday.event}">
<vn-avatar
ng-style="::{backgroundColor: weekday.event.color}">
</vn-avatar>
<div>
{{::weekday.event.name}}
</div>
</vn-chip>
</section>
</vn-td>
</vn-tr>
</vn-tbody>
<vn-tfoot>
<vn-tr>
<vn-td ng-repeat="weekday in $ctrl.weekDays" center>
{{$ctrl.formatHours(weekday.workedHours)}} h.
</vn-td>
</vn-tr>
<vn-tr>
<vn-td center ng-repeat="weekday in $ctrl.weekDays">
<vn-icon-button
icon="add_circle"
vn-tooltip="Add time"
ng-click="$ctrl.showAddTimeDialog(weekday)">
</vn-icon-button>
</vn-td>
</vn-tr>
</vn-tfoot>
</vn-table>
</vn-card>
</vn-td>
</vn-tr>
</vn-thead>
<vn-tbody>
<vn-tr>
<vn-td ng-repeat="weekday in $ctrl.weekDays" class="hours vn-pa-none" expand>
<section ng-repeat="hour in weekday.hours">
<vn-icon
icon="{{
::hour.direction == 'in' ? 'arrow_forward' : 'arrow_back'
}}"
title="{{
::(hour.direction == 'in' ? 'In' : 'Out') | translate
}}"
ng-class="::{'invisible': hour.direction == 'middle'}">
</vn-icon>
<vn-chip
ng-class="::{'colored': hour.manual, 'clickable': true}"
removable="::hour.manual"
on-remove="$ctrl.showDeleteDialog($event, hour)"
ng-click="$ctrl.edit($event, hour)"
>
<prepend>
<vn-icon icon="edit"
vn-tooltip="Edit">
</vn-icon>
</prepend>
{{::hour.timed | date: 'HH:mm'}}
</vn-chip>
</section>
</vn-td>
</vn-tr>
</vn-tbody>
<vn-tfoot>
<vn-tr>
<vn-td ng-repeat="weekday in $ctrl.weekDays" center>
{{$ctrl.formatHours(weekday.workedHours)}} h.
</vn-td>
</vn-tr>
<vn-tr>
<vn-td center ng-repeat="weekday in $ctrl.weekDays">
<vn-icon-button
icon="add_circle"
vn-tooltip="Add time"
ng-click="$ctrl.showAddTimeDialog(weekday)">
</vn-icon-button>
</vn-td>
</vn-tr>
</vn-tfoot>
</vn-table>
</vn-card>
<vn-button-bar ng-show="$ctrl.state" class="vn-w-lg">
<vn-button
label="Satisfied"
disabled="$ctrl.state == 'CONFIRMED'"
ng-if="$ctrl.isHimSelf"
ng-click="$ctrl.isSatisfied()">
</vn-button>
<vn-button
label="Not satisfied"
disabled="$ctrl.state == 'REVISE'"
ng-if="$ctrl.isHimSelf"
ng-click="reason.show()">
</vn-button>
<vn-button
label="Reason"
ng-if="$ctrl.reason && ($ctrl.isHimSelf || $ctrl.isHr)"
ng-click="reason.show()">
</vn-button>
<vn-button
label="Resend"
ng-click="sendEmailConfirmation.show()"
class="right"
vn-tooltip="Resend email of this week to the user"
ng-show="::$ctrl.isHr">
</vn-button>
</vn-button-bar>
<vn-button-bar ng-show="$ctrl.state" class="vn-w-lg">
<vn-button
label="Satisfied"
disabled="$ctrl.state == 'CONFIRMED'"
ng-if="$ctrl.isHimSelf"
ng-click="$ctrl.isSatisfied()">
</vn-button>
<vn-button
label="Not satisfied"
disabled="$ctrl.state == 'REVISE'"
ng-if="$ctrl.isHimSelf"
ng-click="reason.show()">
</vn-button>
<vn-button
label="Reason"
ng-if="$ctrl.reason && ($ctrl.isHimSelf || $ctrl.isHr)"
ng-click="reason.show()">
</vn-button>
<vn-button
label="Resend"
ng-click="sendEmailConfirmation.show()"
class="right"
vn-tooltip="Resend email of this week to the user"
ng-show="::$ctrl.isHr">
</vn-button>
</vn-button-bar>
</div>
<div
ng-if="!$ctrl.worker.hasWorkCenter"
class="bg-title"
translate>
Autonomous worker
</div>
<vn-side-menu side="right">
<div class="vn-pa-md">

View File

@ -151,6 +151,7 @@ class Controller extends Section {
}
getAbsences() {
if (!this.worker.hasWorkerCenter) return;
const fullYear = this.started.getFullYear();
let params = {
workerFk: this.$params.id,

View File

@ -16,6 +16,10 @@ describe('Component vnWorkerTimeControl', () => {
$scope = $rootScope.$new();
$element = angular.element('<vn-worker-time-control></vn-worker-time-control>');
controller = $componentController('vnWorkerTimeControl', {$element, $scope});
controller.worker = {
hasWorkerCenter: true
};
}));
describe('date() setter', () => {

View File

@ -5,10 +5,9 @@ module.exports = {
name: 'report-footer',
async serverPrefetch() {
this.company = await db.findOne(`
SELECT IFNULL(ci.footnotes, cl.footnotes) as footnotes
SELECT IFNULL(ci.footnotes, c.footnotes) footnotes
FROM company c
LEFT JOIN companyL10n cl ON c.id = cl.id
LEFT JOIN companyI18n ci ON ci.companyFk = cl.id
LEFT JOIN companyI18n ci ON ci.companyFk = c.id
AND ci.lang = (SELECT lang FROM account.user where id = ?)
WHERE c.code = ?`,
[this.recipientId, this.companyCode]);

View File

@ -63,12 +63,12 @@ class Email extends Component {
await getAttachments(componentPath, component.attachments);
if (component.components)
await getSubcomponentAttachments(component)
await getSubcomponentAttachments(component);
}
}
}
await getSubcomponentAttachments(instance)
await getSubcomponentAttachments(instance);
if (this.attachments)
await getAttachments(this.path, this.attachments);

View File

@ -20,14 +20,18 @@ module.exports = {
options.to = config.app.senderEmail;
}
let res;
let error;
return this.transporter.sendMail(options).catch(err => {
try {
res = await this.transporter.sendMail(options);
} catch (err) {
error = err;
throw err;
}).finally(async() => {
} finally {
await this.mailLog(options, error);
});
}
return res;
},
async mailLog(options, error) {
@ -46,14 +50,21 @@ module.exports = {
const fileNames = attachments.join(',\n');
await db.rawSql(`
INSERT INTO vn.mail (receiver, replyTo, sent, subject, body, attachment, status)
VALUES (?, ?, 1, ?, ?, ?, ?)`, [
INSERT INTO vn.mail
SET receiver = ?,
replyTo = ?,
sent = ?,
subject = ?,
body = ?,
attachment = ?,
status = ?`, [
options.to,
options.replyTo,
error ? 2 : 1,
options.subject,
options.text || options.html,
fileNames,
error && error.message || 'Sent'
error && error.message || 'OK'
]);
}

View File

@ -16,6 +16,10 @@ h2 {
font-size: 22px
}
.column-oriented td,
.column-oriented th {
padding: 6px
}
#nickname h2 {
max-width: 400px;

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