refs #5213 primeros cambios
gitea/salix/pipeline/head This commit is unstable Details

This commit is contained in:
Carlos Satorres 2023-04-12 12:40:21 +02:00
commit 6196cebb70
143 changed files with 3335 additions and 896 deletions

View File

@ -6,5 +6,9 @@
"source.fixAll.eslint": true
},
"search.useIgnoreFiles": false,
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"eslint.format.enable": true,
"[javascript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
}
}

View File

@ -5,16 +5,28 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2314.01] - 2023-04-20
### Added
- (Clientes -> Morosos) Ahora se puede filtrar por las columnas "Desde" y "Fecha Ú. O.". También se envia un email al comercial cuando se añade una nota.
- (Monitor tickets) Muestra un icono al lado de la zona, si el ticket es frágil y se envía por agencia
- (Facturas recibidas -> Bases negativas) Nueva sección
### Changed
-
### Fixed
- (Clientes -> Morosos) Ahora se mantienen los elementos seleccionados al hacer sroll.
## [2312.01] - 2023-04-06
### Added
- (Monitor tickets) Muestra un icono al lado de la zona, si el ticket es frágil y se envía por agencia
### Changed
- (Monitor tickets) Cuando se filtra por 'Pendiente' ya no muestra los estados de 'Previa'
- (Envíos -> Extra comunitarios) Se agrupan las entradas del mismo travel. Añadidos campos Referencia y Importe.
### Fixed
-
- (Envíos -> Índice) Cambiado el buscador superior por uno lateral
## [2310.01] - 2023-03-23

View File

@ -2,6 +2,7 @@
module.exports = Self => {
Self.remoteMethod('changePassword', {
description: 'Changes the user password',
accessType: 'WRITE',
accepts: [
{
arg: 'id',

View File

@ -1,6 +1,7 @@
module.exports = Self => {
Self.remoteMethod('setPassword', {
description: 'Sets the user password',
accessType: 'WRITE',
accepts: [
{
arg: 'id',

View File

@ -69,15 +69,15 @@ module.exports = Self => {
const result = response.headers.get('set-cookie');
const [firtHeader] = result.split(' ');
const firtCookie = firtHeader.substring(0, firtHeader.length - 1);
const cookie = firtHeader.substring(0, firtHeader.length - 1);
const body = await response.text();
const dom = new jsdom.JSDOM(body);
const token = dom.window.document.querySelector('[name="__CSRFToken__"]').value;
await login(token, firtCookie);
await login(token, cookie);
}
async function login(token, firtCookie) {
async function login(token, cookie) {
const data = {
__CSRFToken__: token,
do: 'scplogin',
@ -90,21 +90,18 @@ module.exports = Self => {
body: new URLSearchParams(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie': firtCookie
'Cookie': cookie
}
};
const response = await fetch(ostUri, params);
const result = response.headers.get('set-cookie');
const [firtHeader] = result.split(' ');
const secondCookie = firtHeader.substring(0, firtHeader.length - 1);
await fetch(ostUri, params);
await close(token, secondCookie);
await close(token, cookie);
}
async function close(token, secondCookie) {
async function close(token, cookie) {
for (const ticketId of ticketsId) {
try {
const lock = await getLockCode(token, secondCookie, ticketId);
const lock = await getLockCode(token, cookie, ticketId);
if (!lock.code) {
let error = `Can't get lock code`;
if (lock.msg) error += `: ${lock.msg}`;
@ -127,7 +124,7 @@ module.exports = Self => {
method: 'POST',
body: form,
headers: {
'Cookie': secondCookie
'Cookie': cookie
}
};
await fetch(ostUri, params);
@ -139,13 +136,13 @@ module.exports = Self => {
}
}
async function getLockCode(token, secondCookie, ticketId) {
async function getLockCode(token, cookie, ticketId) {
const ostUri = `${config.host}/ajax.php/lock/ticket/${ticketId}`;
const params = {
method: 'POST',
headers: {
'X-CSRFToken': token,
'Cookie': secondCookie
'Cookie': cookie
}
};
const response = await fetch(ostUri, params);

View File

@ -4,7 +4,8 @@
"options": {
"mysql": {
"table": "salix.User"
}
},
"resetPasswordTokenTTL": "604800"
},
"properties": {
"id": {

View File

@ -0,0 +1,4 @@
ALTER TABLE `vn`.`invoiceInConfig` ADD daysAgo INT UNSIGNED DEFAULT 45 COMMENT 'Días en el pasado para mostrar facturas en invoiceIn series en salix';
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES
('InvoiceIn', 'getSerial', 'READ', 'ALLOW', 'ROLE', 'administrative');

View File

@ -8,7 +8,7 @@ WHERE code IN ('ZKA', 'ZKE');
UPDATE `vn`.`itemType`
SET isFragile = 1
WHERE id IN (SELECT it.id
FROM itemCategory ic
JOIN itemType it ON it.categoryFk = ic.id
FROM `vn`.`itemCategory` ic
JOIN `vn`.`itemType` it ON it.categoryFk = ic.id
WHERE ic.code = 'plant');

View File

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

View File

@ -0,0 +1,3 @@
DROP TRIGGER `vn`.`supplierAccount_afterInsert`;
DROP TRIGGER `vn`.`supplierAccount_afterUpdate`;
DROP TRIGGER `vn`.`supplierAccount_afterDelete`;

View File

@ -0,0 +1,72 @@
CREATE TABLE `vn`.`wagonType` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL UNIQUE,
`divisible` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
CREATE TABLE `vn`.`wagonTypeColor` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL UNIQUE,
`rgb` varchar(30) NOT NULL UNIQUE,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
CREATE TABLE `vn`.`wagonTypeTray` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`typeFk` int(11) unsigned,
`height` int(11) unsigned NOT NULL,
`colorFk` int(11) unsigned,
PRIMARY KEY (`id`),
UNIQUE KEY (`typeFk`,`height`),
CONSTRAINT `wagonTypeTray_type` FOREIGN KEY (`typeFk`) REFERENCES `wagonType` (`id`) ON UPDATE CASCADE,
CONSTRAINT `wagonTypeTray_color` FOREIGN KEY (`colorFk`) REFERENCES `wagonTypeColor` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
CREATE TABLE `vn`.`wagonConfig` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`width` int(11) unsigned DEFAULT 1350,
`height` int(11) unsigned DEFAULT 1900,
`maxWagonHeight` int(11) unsigned DEFAULT 200,
`minHeightBetweenTrays` int(11) unsigned DEFAULT 50,
`maxTrays` int(11) unsigned DEFAULT 6,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
CREATE TABLE `vn`.`collectionWagon` (
`collectionFk` int(11) NOT NULL,
`wagonFk` int(11) NOT NULL,
`position` int(11) unsigned,
PRIMARY KEY (`collectionFk`,`position`),
UNIQUE KEY `collectionWagon_unique` (`collectionFk`,`wagonFk`),
CONSTRAINT `collectionWagon_collection` FOREIGN KEY (`collectionFk`) REFERENCES `collection` (`id`) ON UPDATE CASCADE,
CONSTRAINT `collectionWagon_wagon` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
CREATE TABLE `vn`.`collectionWagonTicket` (
`ticketFk` int(11) NOT NULL,
`wagonFk` int(11) NOT NULL,
`trayFk` int(11) unsigned NOT NULL,
`side` SET('L', 'R') NULL,
PRIMARY KEY (`ticketFk`),
CONSTRAINT `collectionWagonTicket_ticket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON UPDATE CASCADE,
CONSTRAINT `collectionWagonTicket_wagon` FOREIGN KEY (`wagonFk`) REFERENCES `wagon` (`id`) ON UPDATE CASCADE,
CONSTRAINT `collectionWagonTicket_tray` FOREIGN KEY (`trayFk`) REFERENCES `wagonTypeTray` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
ALTER TABLE `vn`.`wagon` ADD `typeFk` int(11) unsigned NOT NULL;
ALTER TABLE `vn`.`wagon` ADD `label` int(11) unsigned NOT NULL;
ALTER TABLE `vn`.`wagon` ADD CONSTRAINT `wagon_type` FOREIGN KEY (`typeFk`) REFERENCES `wagonType` (`id`) ON UPDATE CASCADE;
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES
('WagonType', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
('WagonTypeColor', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
('WagonTypeTray', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
('WagonConfig', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
('CollectionWagon', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
('CollectionWagonTicket', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
('Wagon', '*', '*', 'ALLOW', 'ROLE', 'productionAssi'),
('WagonType', 'createWagonType', '*', 'ALLOW', 'ROLE', 'productionAssi'),
('WagonType', 'deleteWagonType', '*', 'ALLOW', 'ROLE', 'productionAssi'),
('WagonType', 'editWagonType', '*', 'ALLOW', 'ROLE', 'productionAssi');

View File

@ -0,0 +1,72 @@
DROP TRIGGER IF EXISTS `vn`.`client_beforeUpdate`;
USE `vn`;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_beforeUpdate`
BEFORE UPDATE ON `client`
FOR EACH ROW
BEGIN
DECLARE vText VARCHAR(255) DEFAULT NULL;
DECLARE vPayMethodFk INT;
-- Comprueba que el formato de los teléfonos es válido
IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN
CALL pbx.phone_isValid(NEW.phone);
END IF;
IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN
CALL pbx.phone_isValid(NEW.mobile);
END IF;
SELECT id INTO vPayMethodFk
FROM vn.payMethod
WHERE code = 'bankDraft';
IF NEW.payMethodFk = vPayMethodFk AND NEW.dueDay = 0 THEN
SET NEW.dueDay = 5;
END IF;
-- Avisar al comercial si ha llegado la documentación sepa/core
IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN
SET vText = 'Sepa de VNL';
END IF;
IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN
SET vText = 'Core de VNL';
END IF;
IF vText IS NOT NULL
THEN
INSERT INTO mail(receiver, replyTo, `subject`, body)
SELECT
CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'),
'administracion@verdnatura.es',
CONCAT('Cliente ', NEW.id),
CONCAT('Recibida la documentación: ', vText)
FROM worker w
LEFT JOIN account.user u ON w.userFk = u.id AND u.active
LEFT JOIN account.account ac ON ac.id = u.id
WHERE w.id = NEW.salesPersonFk;
END IF;
IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN
IF (SELECT COUNT(clientFk)
FROM clientProtected
WHERE clientFk = NEW.id
) > 0 THEN
CALL util.throw("HAS_CLIENT_PROTECTED");
END IF;
END IF;
IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN
SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk);
END IF;
IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN
SET NEW.isTaxDataChecked = 0;
END IF;
END$$
DELIMITER ;

View File

@ -0,0 +1,13 @@
DROP TRIGGER IF EXISTS `vn`.`invoiceOut_afterInsert`;
USE vn;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` TRIGGER `vn`.`invoiceOut_afterInsert`
AFTER INSERT ON `invoiceOut`
FOR EACH ROW
BEGIN
CALL clientRisk_update(NEW.clientFk, NEW.companyFk, NEW.amount);
END$$
DELIMITER ;

View File

@ -0,0 +1,4 @@
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES
('InvoiceIn', 'negativeBases', 'READ', 'ALLOW', 'ROLE', 'administrative'),
('InvoiceIn', 'negativeBasesCsv', 'READ', 'ALLOW', 'ROLE', 'administrative');

View File

@ -0,0 +1,14 @@
CREATE TABLE `vn`.`workerObservation` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`workerFk` int(10) unsigned DEFAULT NULL,
`userFk` int(10) unsigned DEFAULT NULL,
`text` text COLLATE utf8mb3_unicode_ci NOT NULL,
`created` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`),
CONSTRAINT `workerFk_workerObservation_FK` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE,
CONSTRAINT `userFk_workerObservation_FK` FOREIGN KEY (`userFk`) REFERENCES `account`.`user`(`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Todas las observaciones referentes a un trabajador';
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`)
VALUES
('WorkerObservation', '*', '*', 'ALLOW', 'ROLE', 'hr');

View File

@ -2490,9 +2490,9 @@ REPLACE INTO `vn`.`invoiceIn`(`id`, `serialNumber`,`serial`, `supplierFk`, `issu
(9, 1009, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1242, 1, 442, 1),
(10, 1010, 'R', 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1243, 1, 442, 1);
INSERT INTO `vn`.`invoiceInConfig` (`id`, `retentionRate`, `retentionName`, `sageWithholdingFk`)
INSERT INTO `vn`.`invoiceInConfig` (`id`, `retentionRate`, `retentionName`, `sageWithholdingFk`, `daysAgo`)
VALUES
(1, -2, '2% retention', 2);
(1, -2, '2% retention', 2, 45);
INSERT INTO `vn`.`invoiceInDueDay`(`invoiceInFk`, `dueDated`, `bankFk`, `amount`)
VALUES
@ -2840,4 +2840,27 @@ INSERT INTO `vn`.`workerTimeControlMail` (`id`, `workerFk`, `year`, `week`, `sta
(3, 9, 2000, 51, 'CONFIRMED', util.VN_NOW(), 1, NULL),
(4, 9, 2001, 1, 'SENDED', util.VN_NOW(), 1, NULL);
INSERT INTO `vn`.`wagonConfig` (`id`, `width`, `height`, `maxWagonHeight`, `minHeightBetweenTrays`, `maxTrays`)
VALUES
(1, 1350, 1900, 200, 50, 6);
INSERT INTO `vn`.`wagonTypeColor` (`id`, `name`, `rgb`)
VALUES
(1, 'white', '#ffffff'),
(2, 'red', '#ff0000'),
(3, 'green', '#00ff00'),
(4, 'blue', '#0000ff');
INSERT INTO `vn`.`wagonType` (`id`, `name`, `divisible`)
VALUES
(1, 'Wagon Type #1', 1);
INSERT INTO `vn`.`wagonTypeTray` (`id`, `typeFk`, `height`, `colorFk`)
VALUES
(1, 1, 100, 1),
(2, 1, 50, 2),
(3, 1, 0, 3);

View File

@ -426,7 +426,8 @@ export default {
fourthStarted: 'vn-fixed-price tr:nth-child(5) vn-date-picker[ng-model="price.started"]',
fourthEnded: 'vn-fixed-price tr:nth-child(5) vn-date-picker[ng-model="price.ended"]',
fourthDeleteIcon: 'vn-fixed-price tr:nth-child(5) > td:nth-child(9) > vn-icon-button[icon="delete"]',
orderColumnId: 'vn-fixed-price th[field="itemFk"]'
orderColumnId: 'vn-fixed-price th[field="itemFk"]',
removeWarehouseFilter: 'vn-searchbar > form > vn-textfield > div.container > div.prepend > prepend > div > span:nth-child(1) > vn-icon > i'
},
itemCreateView: {
temporalName: 'vn-item-create vn-textfield[ng-model="$ctrl.item.provisionalName"]',
@ -987,6 +988,12 @@ export default {
locker: 'vn-worker-basic-data vn-input-number[ng-model="$ctrl.worker.locker"]',
saveButton: 'vn-worker-basic-data button[type=submit]'
},
workerNotes: {
addNoteFloatButton: 'vn-float-button',
note: 'vn-textarea[ng-model="$ctrl.note.text"]',
saveButton: 'button[type=submit]',
firstNoteText: 'vn-worker-note .text'
},
workerPbx: {
extension: 'vn-worker-pbx vn-textfield[ng-model="$ctrl.worker.sip.extension"]',
saveButton: 'vn-worker-pbx button[type=submit]'
@ -1127,6 +1134,15 @@ export default {
saveButton: 'vn-invoice-in-tax vn-submit',
},
invoiceInIndex: {
topbarSearchParams: 'vn-searchbar div.search-params > span',
},
invoiceInSerial: {
daysAgo: 'vn-invoice-in-serial-search-panel vn-input-number[ng-model="$ctrl.filter.daysAgo"]',
serial: 'vn-invoice-in-serial-search-panel vn-textfield[ng-model="$ctrl.filter.serial"]',
chip: 'vn-chip > vn-icon',
goToIndex: 'vn-invoice-in-serial vn-icon-button[icon="icon-invoice-in"]',
},
travelIndex: {
anySearchResult: 'vn-travel-index vn-tbody > a',
firstSearchResult: 'vn-travel-index vn-tbody > a:nth-child(1)',
@ -1138,7 +1154,16 @@ export default {
landingDate: 'vn-travel-create vn-date-picker[ng-model="$ctrl.travel.landed"]',
warehouseOut: 'vn-travel-create vn-autocomplete[ng-model="$ctrl.travel.warehouseOutFk"]',
warehouseIn: 'vn-travel-create vn-autocomplete[ng-model="$ctrl.travel.warehouseInFk"]',
save: 'vn-travel-create vn-submit > button'
save: 'vn-travel-create vn-submit > button',
generalSearchFilter: 'vn-travel-search-panel vn-textfield[ng-model="$ctrl.search"]',
agencyFilter: 'vn-travel-search-panel vn-autocomplete[ng-model="$ctrl.filter.agencyModeFk"]',
warehouseOutFilter: 'vn-travel-search-panel vn-autocomplete[ng-model="$ctrl.filter.warehouseOutFk"]',
warehouseInFilter: 'vn-travel-search-panel vn-autocomplete[ng-model="$ctrl.filter.warehouseInFk"]',
scopeDaysFilter: 'vn-travel-search-panel vn-input-number[ng-model="$ctrl.filter.scopeDays"]',
continentFilter: 'vn-travel-search-panel vn-autocomplete[ng-model="$ctrl.filter.continent"]',
totalEntriesFilter: 'vn-travel-search-panel vn-input-number[ng-model="$ctrl.totalEntries"]',
chip: 'vn-travel-search-panel vn-chip > vn-icon',
},
travelExtraCommunity: {
anySearchResult: 'vn-travel-extra-community > vn-card div > tbody > tr[ng-attr-id="{{::travel.id}}"]',

View File

@ -90,7 +90,7 @@ describe('SmartTable SearchBar integration', () => {
await page.waitToClick(selectors.itemFixedPrice.orderColumnId);
const result = await page.waitToGetProperty(selectors.itemFixedPrice.firstItemID, 'value');
expect(result).toEqual('13');
expect(result).toEqual('3');
});
it('should reload page and have same order', async() => {
@ -99,7 +99,7 @@ describe('SmartTable SearchBar integration', () => {
});
const result = await page.waitToGetProperty(selectors.itemFixedPrice.firstItemID, 'value');
expect(result).toEqual('13');
expect(result).toEqual('3');
});
});
});

View File

@ -0,0 +1,42 @@
import selectors from '../../helpers/selectors';
import getBrowser from '../../helpers/puppeteer';
describe('Worker Add notes path', () => {
let browser;
let page;
beforeAll(async() => {
browser = await getBrowser();
page = browser.page;
await page.loginAndModule('employee', 'worker');
await page.accessToSearchResult('Bruce Banner');
await page.accessToSection('worker.card.note.index');
});
afterAll(async() => {
await browser.close();
});
it(`should reach the notes index`, async() => {
await page.waitForState('worker.card.note.index');
});
it(`should click on the add note button`, async() => {
await page.waitToClick(selectors.workerNotes.addNoteFloatButton);
await page.waitForState('worker.card.note.create');
});
it(`should create a note`, async() => {
await page.waitForSelector(selectors.workerNotes.note);
await page.type(`${selectors.workerNotes.note} textarea`, 'Meeting with Black Widow 21st 9am');
await page.waitToClick(selectors.workerNotes.saveButton);
const message = await page.waitForSnackbar();
expect(message.text).toContain('Data saved!');
});
it('should confirm the note was created', async() => {
const result = await page.waitToGetProperty(selectors.workerNotes.firstNoteText, 'innerText');
expect(result).toEqual('Meeting with Black Widow 21st 9am');
});
});

View File

@ -15,8 +15,9 @@ describe('Item fixed prices path', () => {
await browser.close();
});
it('should click on the add new foxed price button', async() => {
await page.doSearch();
it('should click on the add new fixed price button', async() => {
await page.waitToClick(selectors.itemFixedPrice.removeWarehouseFilter);
await page.waitForSpinnerLoad();
await page.waitToClick(selectors.itemFixedPrice.add);
await page.waitForSelector(selectors.itemFixedPrice.fourthFixedPrice);
});
@ -37,7 +38,8 @@ describe('Item fixed prices path', () => {
it('should reload the section and check the created price has the expected ID', async() => {
await page.accessToSection('item.index');
await page.accessToSection('item.fixedPrice');
await page.doSearch();
await page.waitToClick(selectors.itemFixedPrice.removeWarehouseFilter);
await page.waitForSpinnerLoad();
const result = await page.waitToGetProperty(selectors.itemFixedPrice.fourthItemID, 'value');

View File

@ -0,0 +1,29 @@
import getBrowser from '../../helpers/puppeteer';
describe('InvoiceIn negative bases path', () => {
let browser;
let page;
const httpRequests = [];
beforeAll(async() => {
browser = await getBrowser();
page = browser.page;
page.on('request', req => {
if (req.url().includes(`InvoiceIns/negativeBases`))
httpRequests.push(req.url());
});
await page.loginAndModule('administrative', 'invoiceIn');
await page.accessToSection('invoiceIn.negative-bases');
});
afterAll(async() => {
await browser.close();
});
it('should show negative bases in a date range', async() => {
const request = httpRequests.find(req =>
req.includes(`from`) && req.includes(`to`));
expect(request).toBeDefined();
});
});

View File

@ -0,0 +1,48 @@
import selectors from '../../helpers/selectors.js';
import getBrowser from '../../helpers/puppeteer';
describe('InvoiceIn serial path', () => {
let browser;
let page;
let httpRequest;
beforeAll(async() => {
browser = await getBrowser();
page = browser.page;
await page.loginAndModule('administrative', 'invoiceIn');
await page.accessToSection('invoiceIn.serial');
page.on('request', req => {
if (req.url().includes(`InvoiceIns/getSerial`))
httpRequest = req.url();
});
});
afterAll(async() => {
await browser.close();
});
it('should check that passes the correct params to back', async() => {
await page.overwrite(selectors.invoiceInSerial.daysAgo, '30');
await page.keyboard.press('Enter');
expect(httpRequest).toContain('daysAgo=30');
await page.overwrite(selectors.invoiceInSerial.serial, 'R');
await page.keyboard.press('Enter');
expect(httpRequest).toContain('serial=R');
await page.click(selectors.invoiceInSerial.chip);
});
it('should go to index and check if the search-panel has the correct params', async() => {
await page.click(selectors.invoiceInSerial.goToIndex);
const params = await page.$$(selectors.invoiceInIndex.topbarSearchParams);
const serial = await params[0].getProperty('title');
const isBooked = await params[1].getProperty('title');
const from = await params[2].getProperty('title');
expect(await serial.jsonValue()).toContain('serial');
expect(await isBooked.jsonValue()).toContain('not isBooked');
expect(await from.jsonValue()).toContain('from');
});
});

View File

@ -9,7 +9,8 @@ describe('Travel basic data path', () => {
browser = await getBrowser();
page = browser.page;
await page.loginAndModule('buyer', 'travel');
await page.accessToSearchResult('3');
await page.write(selectors.travelIndex.generalSearchFilter, '3');
await page.keyboard.press('Enter');
await page.accessToSection('travel.card.basicData');
});

View File

@ -9,7 +9,8 @@ describe('Travel descriptor path', () => {
browser = await getBrowser();
page = browser.page;
await page.loginAndModule('buyer', 'travel');
await page.accessToSearchResult('1');
await page.write(selectors.travelIndex.generalSearchFilter, '1');
await page.keyboard.press('Enter');
await page.waitForState('travel.card.summary');
});
@ -81,7 +82,8 @@ describe('Travel descriptor path', () => {
await page.waitToClick('.cancel');
await page.waitToClick(selectors.globalItems.homeButton);
await page.selectModule('travel');
await page.accessToSearchResult('3');
await page.write(selectors.travelIndex.generalSearchFilter, '3');
await page.keyboard.press('Enter');
await page.waitForState('travel.card.summary');
const state = await page.getState();

View File

@ -10,7 +10,8 @@ describe('Travel thermograph path', () => {
browser = await getBrowser();
page = browser.page;
await page.loginAndModule('buyer', 'travel');
await page.accessToSearchResult('3');
await page.write(selectors.travelIndex.generalSearchFilter, '3');
await page.keyboard.press('Enter');
await page.accessToSection('travel.card.thermograph.index');
});

View File

@ -0,0 +1,62 @@
import selectors from '../../helpers/selectors.js';
import getBrowser from '../../helpers/puppeteer';
describe('Travel search panel path', () => {
let browser;
let page;
let httpRequest;
beforeAll(async() => {
browser = await getBrowser();
page = browser.page;
await page.loginAndModule('buyer', 'travel');
page.on('request', req => {
if (req.url().includes(`Travels/filter`))
httpRequest = req.url();
});
});
afterAll(async() => {
await browser.close();
});
it('should filter using all the fields', async() => {
await page.click(selectors.travelIndex.chip);
await page.write(selectors.travelIndex.generalSearchFilter, 'travel');
await page.keyboard.press('Enter');
expect(httpRequest).toContain('search=travel');
await page.click(selectors.travelIndex.chip);
await page.autocompleteSearch(selectors.travelIndex.agencyFilter, 'Entanglement');
expect(httpRequest).toContain('agencyModeFk');
await page.click(selectors.travelIndex.chip);
await page.autocompleteSearch(selectors.travelIndex.warehouseOutFilter, 'Warehouse One');
expect(httpRequest).toContain('warehouseOutFk');
await page.click(selectors.travelIndex.chip);
await page.autocompleteSearch(selectors.travelIndex.warehouseInFilter, 'Warehouse Two');
expect(httpRequest).toContain('warehouseInFk');
await page.click(selectors.travelIndex.chip);
await page.overwrite(selectors.travelIndex.scopeDaysFilter, '15');
await page.keyboard.press('Enter');
expect(httpRequest).toContain('scopeDays=15');
await page.click(selectors.travelIndex.chip);
await page.autocompleteSearch(selectors.travelIndex.continentFilter, 'Asia');
expect(httpRequest).toContain('continent');
await page.click(selectors.travelIndex.chip);
await page.write(selectors.travelIndex.totalEntriesFilter, '1');
await page.keyboard.press('Enter');
expect(httpRequest).toContain('totalEntries=1');
});
});

View File

@ -26,7 +26,7 @@ Value should have at most %s characters: El valor debe tener un máximo de %s ca
Enter a new search: Introduce una nueva búsqueda
No results: Sin resultados
Ups! It seems there was an error: ¡Vaya! Parece que ha habido un error
General search: Busqueda general
General search: Búsqueda general
January: Enero
February: Febrero
March: Marzo
@ -42,9 +42,9 @@ December: Diciembre
Monday: Lunes
Tuesday: Martes
Wednesday: Miércoles
Thursday: Jueves
Friday: Viernes
Saturday: Sábado
Thursday: Jueves
Friday: Viernes
Saturday: Sábado
Sunday: Domingo
Has delivery: Hay reparto
Loading: Cargando
@ -63,4 +63,4 @@ Loading...: Cargando...
No results found: Sin resultados
No data: Sin datos
Undo changes: Deshacer cambios
Load more results: Cargar más resultados
Load more results: Cargar más resultados

View File

@ -2,6 +2,7 @@
$font-size: 11pt;
$menu-width: 256px;
$right-menu-width: 318px;
$topbar-height: 56px;
$mobile-width: 800px;
$float-spacing: 20px;

View File

@ -88,13 +88,13 @@ vn-layout {
}
&.right-menu {
& > vn-topbar > .end {
width: 80px + $menu-width;
width: 80px + $right-menu-width;
}
& > .main-view {
padding-right: $menu-width;
padding-right: $right-menu-width;
}
[fixed-bottom-right] {
right: $menu-width;
right: $right-menu-width;
}
}
& > .main-view {

View File

@ -268,8 +268,11 @@
"Exists an invoice with a previous date": "Existe una factura con fecha anterior",
"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",
"This locker has already been assigned": "Esta taquilla ya ha sido asignada",
"Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº {{id}}",
"Not exist this branch": "La rama no existe",
"This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado"
"This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado",
"Insert a date range": "Inserte un rango de fechas",
"Added observation": "{{user}} añadió esta observacion: {{text}}",
"Comment added to client": "Observación añadida al cliente {{clientFk}}"
}

View File

@ -1,8 +1,7 @@
const mysql = require('mysql');
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const MySQL = require('loopback-connector-mysql').MySQL;
const EnumFactory = require('loopback-connector-mysql').EnumFactory;
const Transaction = require('loopback-connector').Transaction;
const { Transaction, SQLConnector, ParameterizedSQL } = require('loopback-connector');
const fs = require('fs');
const limitSet = new Set([
@ -254,49 +253,49 @@ class VnMySQL extends MySQL {
}
create(model, data, opts, cb) {
const ctx = {data};
const ctx = { data };
this.invokeMethod('create',
arguments, model, ctx, opts, cb);
}
createAll(model, data, opts, cb) {
const ctx = {data};
const ctx = { data };
this.invokeMethod('createAll',
arguments, model, ctx, opts, cb);
}
save(model, data, opts, cb) {
const ctx = {data};
const ctx = { data };
this.invokeMethod('save',
arguments, model, ctx, opts, cb);
}
updateOrCreate(model, data, opts, cb) {
const ctx = {data};
const ctx = { data };
this.invokeMethod('updateOrCreate',
arguments, model, ctx, opts, cb);
}
replaceOrCreate(model, data, opts, cb) {
const ctx = {data};
const ctx = { data };
this.invokeMethod('replaceOrCreate',
arguments, model, ctx, opts, cb);
}
destroyAll(model, where, opts, cb) {
const ctx = {where};
const ctx = { where };
this.invokeMethod('destroyAll',
arguments, model, ctx, opts, cb);
}
update(model, where, data, opts, cb) {
const ctx = {where, data};
const ctx = { where, data };
this.invokeMethod('update',
arguments, model, ctx, opts, cb);
}
replaceById(model, id, data, opts, cb) {
const ctx = {id, data};
const ctx = { id, data };
this.invokeMethod('replaceById',
arguments, model, ctx, opts, cb);
}
@ -321,16 +320,16 @@ class VnMySQL extends MySQL {
let tx;
if (!opts.transaction) {
tx = await Transaction.begin(this, {});
opts = Object.assign({transaction: tx, httpCtx: opts.httpCtx}, opts);
opts = Object.assign({ transaction: tx, httpCtx: opts.httpCtx }, opts);
}
try {
// Fetch old values (update|delete) or login
let where, id, data, idName, limit, op, oldInstances, newInstances;
const hasGrabUser = settings.log && settings.log.grabUser;
if(hasGrabUser){
if (hasGrabUser) {
const userId = opts.httpCtx && opts.httpCtx.active.accessToken.userId;
const user = await Model.app.models.Account.findById(userId, {fields: ['name']}, opts);
const user = await Model.app.models.Account.findById(userId, { fields: ['name'] }, opts);
await this.executeP(`CALL account.myUser_loginWithName(?)`, [user.name], opts);
}
else {
@ -344,18 +343,18 @@ class VnMySQL extends MySQL {
op = opMap.get(method);
if (!where) {
if (id) where = {[idName]: id};
else where = {[idName]: data[idName]};
if (id) where = { [idName]: id };
else where = { [idName]: data[idName] };
}
// Fetch old values
switch (op) {
case 'update':
case 'delete':
// Single entity operation
const stmt = this.buildSelectStmt(op, data, idName, model, where, limit);
stmt.merge(`FOR UPDATE`);
oldInstances = await this.executeStmt(stmt, opts);
case 'update':
case 'delete':
// Single entity operation
const stmt = this.buildSelectStmt(op, data, idName, model, where, limit);
stmt.merge(`FOR UPDATE`);
oldInstances = await this.executeStmt(stmt, opts);
}
}
@ -365,30 +364,30 @@ class VnMySQL extends MySQL {
super[method].apply(this, fnArgs);
});
if(hasGrabUser)
if (hasGrabUser)
await this.executeP(`CALL account.myUser_logout()`, null, opts);
else {
// Fetch new values
const ids = [];
switch (op) {
case 'insert':
case 'update': {
case 'insert':
case 'update': {
switch (method) {
case 'createAll':
for (const row of res[1])
ids.push(row[idName]);
break;
case 'create':
ids.push(res[1]);
break;
case 'update':
if (data[idName] != null)
ids.push(data[idName]);
break;
case 'createAll':
for (const row of res[1])
ids.push(row[idName]);
break;
case 'create':
ids.push(res[1]);
break;
case 'update':
if (data[idName] != null)
ids.push(data[idName]);
break;
}
const newWhere = ids.length ? {[idName]: ids} : where;
const newWhere = ids.length ? { [idName]: ids } : where;
const stmt = this.buildSelectStmt(op, data, idName, model, newWhere, limit);
newInstances = await this.executeStmt(stmt, opts);
@ -431,9 +430,9 @@ class VnMySQL extends MySQL {
const stmt = new ParameterizedSQL(
'SELECT ' +
this.buildColumnNames(model, {fields}) +
' FROM ' +
this.tableEscaped(model)
this.buildColumnNames(model, { fields }) +
' FROM ' +
this.tableEscaped(model)
);
stmt.merge(this.buildWhere(model, where));
if (limit) stmt.merge(`LIMIT 1`);
@ -505,8 +504,8 @@ class VnMySQL extends MySQL {
if (oldI) {
Object.keys(oldI).forEach(prop => {
const hasChanges = oldI[prop] instanceof Date ?
oldI[prop]?.getTime() != newI[prop]?.getTime() :
oldI[prop] != newI[prop];
oldI[prop]?.getTime() != newI[prop]?.getTime() :
oldI[prop] != newI[prop];
if (!hasChanges) {
delete oldI[prop];
@ -537,13 +536,13 @@ exports.initialize = function initialize(dataSource, callback) {
modelBuilder.defineValueType.bind(modelBuilder) :
modelBuilder.constructor.registerType.bind(modelBuilder.constructor);
defineType(function Point() {});
defineType(function Point() { });
dataSource.EnumFactory = EnumFactory;
if (callback) {
if (dataSource.settings.lazyConnect) {
process.nextTick(function() {
process.nextTick(function () {
callback();
});
} else
@ -551,13 +550,13 @@ exports.initialize = function initialize(dataSource, callback) {
}
};
MySQL.prototype.connect = function(callback) {
MySQL.prototype.connect = function (callback) {
const self = this;
const options = generateOptions(this.settings);
if (this.client) {
if (callback) {
process.nextTick(function() {
process.nextTick(function () {
callback(null, self.client);
});
}
@ -566,7 +565,7 @@ MySQL.prototype.connect = function(callback) {
function connectionHandler(options, callback) {
const client = mysql.createPool(options);
client.getConnection(function(err, connection) {
client.getConnection(function (err, connection) {
const conn = connection;
if (!err) {
if (self.debug)
@ -645,3 +644,31 @@ function generateOptions(settings) {
}
return options;
}
SQLConnector.prototype.all = function find(model, filter, options, cb) {
const self = this;
// Order by id if no order is specified
filter = filter || {};
const stmt = this.buildSelect(model, filter, options);
this.execute(stmt.sql, stmt.params, options, function (err, data) {
if (err) {
return cb(err, []);
}
try {
const objs = data.map(function (obj) {
return self.fromRow(model, obj);
});
if (filter && filter.include) {
self.getModelDefinition(model).model.include(
objs, filter.include, options, cb,
);
} else {
cb(null, objs);
}
} catch (error) {
cb(error, [])
}
});
};

View File

@ -1,63 +0,0 @@
module.exports = Self => {
Self.remoteMethod('checkDuplicatedData', {
description: 'Checks if a client has same email, mobile or phone than other client and send an email',
accepts: [{
arg: 'id',
type: 'number',
required: true,
description: 'The client id'
}],
returns: {
type: 'object',
root: true
},
http: {
verb: 'GET',
path: '/:id/checkDuplicatedData'
}
});
Self.checkDuplicatedData = async function(id, options) {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const client = await Self.app.models.Client.findById(id, myOptions);
const findParams = [];
if (client.email) {
const emails = client.email.split(',');
for (let email of emails)
findParams.push({email: email});
}
if (client.phone)
findParams.push({phone: client.phone});
if (client.mobile)
findParams.push({mobile: client.mobile});
const filterObj = {
where: {
and: [
{or: findParams},
{id: {neq: client.id}}
]
}
};
const clientSameData = await Self.findOne(filterObj, myOptions);
if (clientSameData) {
await Self.app.models.Mail.create({
receiver: 'direccioncomercial@verdnatura.es',
subject: `Cliente con email/teléfono/móvil duplicados`,
body: 'El cliente ' + client.id + ' comparte alguno de estos datos con el cliente ' + clientSameData.id +
'\n- Email: ' + client.email +
'\n- Teléfono: ' + client.phone +
'\n- Móvil: ' + client.mobile
}, myOptions);
}
};
};

View File

@ -1,24 +0,0 @@
const models = require('vn-loopback/server/server').models;
describe('client checkDuplicated()', () => {
it('should send an mail if mobile/phone/email is duplicated', async() => {
const tx = await models.Client.beginTransaction({});
try {
const options = {transaction: tx};
const id = 1110;
const mailModel = models.Mail;
spyOn(mailModel, 'create');
await models.Client.checkDuplicatedData(id, options);
expect(mailModel.create).toHaveBeenCalled();
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -0,0 +1,52 @@
module.exports = Self => {
Self.remoteMethodCtx('observationEmail', {
description: 'Send an email with the observation',
accessType: 'WRITE',
accepts: [
{
arg: 'defaulters',
type: ['object'],
required: true,
description: 'The defaulters to send the email'
},
{
arg: 'observation',
type: 'string',
required: true,
description: 'The observation'
}],
returns: {
arg: 'observationEmail'
},
http: {
path: `/observationEmail`,
verb: 'POST'
}
});
Self.observationEmail = async(ctx, defaulters, observation, options) => {
const models = Self.app.models;
const $t = ctx.req.__; // $translate
const myOptions = {};
const userId = ctx.req.accessToken.userId;
if (typeof options == 'object')
Object.assign(myOptions, options);
for (const defaulter of defaulters) {
const user = await models.Account.findById(userId, {fields: ['name']}, myOptions);
const body = $t('Added observation', {
user: user.name,
text: observation
});
await models.Mail.create({
subject: $t('Comment added to client', {clientFk: defaulter.clientFk}),
body: body,
receiver: `${defaulter.salesPersonName}@verdnatura.es`,
replyTo: `${user.name}@verdnatura.es`
}, myOptions);
}
};
};

View File

@ -2,7 +2,6 @@ module.exports = Self => {
require('../methods/client/addressesPropagateRe')(Self);
require('../methods/client/canBeInvoiced')(Self);
require('../methods/client/canCreateTicket')(Self);
require('../methods/client/checkDuplicated')(Self);
require('../methods/client/confirmTransaction')(Self);
require('../methods/client/consumption')(Self);
require('../methods/client/createAddress')(Self);

View File

@ -1,3 +1,4 @@
module.exports = Self => {
require('../methods/defaulter/filter')(Self);
require('../methods/defaulter/observationEmail')(Self);
};

View File

@ -9,9 +9,7 @@ export default class Controller extends Section {
}
onSubmit() {
return this.$.watcher.submit().then(() => {
this.$http.get(`Clients/${this.$params.id}/checkDuplicatedData`);
});
return this.$.watcher.submit();
}
}

View File

@ -12,7 +12,6 @@ export default class Controller extends Section {
onSubmit() {
return this.$.watcher.submit().then(json => {
this.$state.go('client.card.basicData', {id: json.data.id});
this.$http.get(`Clients/${this.client.id}/checkDuplicatedData`);
});
}

View File

@ -5,6 +5,7 @@
limit="20"
order="amount DESC"
data="defaulters"
on-data-change="$ctrl.reCheck()"
auto-load="true">
</vn-crud-model>
<vn-portal slot="topbar">
@ -17,22 +18,22 @@
</vn-searchbar>
</vn-portal>
<vn-card>
<smart-table
<smart-table
model="model"
options="$ctrl.smartTableOptions"
options="$ctrl.smartTableOptions"
expr-builder="$ctrl.exprBuilder(param, value)">
<slot-actions>
<div>
<div class="totalBox" style="text-align: center;">
<h6 translate>Total</h6>
<vn-label-value
label="Balance due"
<vn-label-value
label="Balance due"
value="{{$ctrl.balanceDueTotal | currency: 'EUR': 2}}">
</vn-label-value>
</div>
</div>
<div class="vn-pa-md">
<vn-button
<vn-button
ng-show="$ctrl.checked.length > 0"
ng-click="notesDialog.show()"
name="notesDialog"
@ -46,7 +47,7 @@
<thead>
<tr>
<th shrink>
<vn-multi-check
<vn-multi-check
model="model">
</vn-multi-check>
</th>
@ -56,25 +57,25 @@
<th field="salesPersonFk">
<span translate>Comercial</span>
</th>
<th
field="amount"
<th
field="amount"
vn-tooltip="Balance due">
<span translate>Balance D.</span>
</th>
<th
field="workerFk"
<th
field="workerFk"
vn-tooltip="Worker who made the last observation">
<span translate>Author</span>
</th>
<th field="observation" expand>
<span translate>Last observation</span>
</th>
<th
<th
vn-tooltip="Last observation date"
field="created">
<span translate>L. O. Date</span>
</th>
<th
<th
vn-tooltip="Credit insurance"
field="creditInsurance"
shrink>
@ -88,8 +89,9 @@
<tbody>
<tr ng-repeat="defaulter in defaulters">
<td shrink>
<vn-check
<vn-check
ng-model="defaulter.checked"
on-change="$ctrl.saveChecked(defaulter.clientFk)"
vn-click-stop>
</vn-check>
</td>
@ -150,7 +152,7 @@
</vn-client-summary>
</vn-popup>
<!-- Dialog of add notes button -->
<!-- Dialog of add notes button -->
<vn-dialog
vn-id="notesDialog"
on-accept="$ctrl.onResponse()">
@ -160,7 +162,7 @@
<vn-horizontal>
<vn-textarea vn-one
vn-id="message"
label="Message"
label="Message"
ng-model="$ctrl.defaulter.observation"
rows="3"
required="true"

View File

@ -6,6 +6,7 @@ export default class Controller extends Section {
constructor($element, $) {
super($element, $);
this.defaulter = {};
this.checkedDefaulers = [];
this.smartTableOptions = {
activeButtons: {
@ -45,11 +46,11 @@ export default class Controller extends Section {
},
{
field: 'created',
searchable: false
datepicker: true
},
{
field: 'defaulterSinced',
searchable: false
datepicker: true
}
]
};
@ -68,6 +69,19 @@ export default class Controller extends Section {
return checkedLines;
}
saveChecked(clientId) {
this.checkedDefaulers = this.checkedDefaulers.includes(clientId) ?
this.checkedDefaulers.filter(id => id !== clientId) : [...this.checkedDefaulers, clientId];
}
reCheck() {
if (!this.$.model.data || !this.checkedDefaulers.length) return;
this.$.model.data.forEach(defaulter => {
defaulter.checked = this.checkedDefaulers.includes(defaulter.clientFk);
});
}
getBalanceDueTotal() {
this.$http.get('Defaulters/filter')
.then(res => {
@ -109,11 +123,20 @@ export default class Controller extends Section {
}
this.$http.post(`ClientObservations`, params) .then(() => {
this.vnApp.showMessage(this.$t('Observation saved!'));
this.vnApp.showSuccess(this.$t('Observation saved!'));
this.sendMail();
this.$state.reload();
});
}
sendMail() {
const params = {
defaulters: this.checked,
observation: this.defaulter.observation
};
this.$http.post(`Defaulters/observationEmail`, params);
}
exprBuilder(param, value) {
switch (param) {
case 'creditInsurance':
@ -122,8 +145,25 @@ export default class Controller extends Section {
case 'workerFk':
case 'salesPersonFk':
return {[`d.${param}`]: value};
case 'created':
return {'d.created': {
between: this.dateRange(value)}
};
case 'defaulterSinced':
return {'d.defaulterSinced': {
between: this.dateRange(value)}
};
}
}
dateRange(value) {
const minHour = new Date(value);
minHour.setHours(0, 0, 0, 0);
const maxHour = new Date(value);
maxHour.setHours(23, 59, 59, 59);
return [minHour, maxHour];
}
}
ngModule.vnComponent('vnClientDefaulter', {

View File

@ -81,14 +81,15 @@ describe('client defaulter', () => {
const params = [{text: controller.defaulter.observation, clientFk: data[1].clientFk}];
jest.spyOn(controller.vnApp, 'showMessage');
jest.spyOn(controller.vnApp, 'showSuccess');
$httpBackend.expect('GET', `Defaulters/filter`).respond(200);
$httpBackend.expect('POST', `ClientObservations`, params).respond(200, params);
$httpBackend.expect('POST', `Defaulters/observationEmail`).respond(200);
controller.onResponse();
$httpBackend.flush();
expect(controller.vnApp.showMessage).toHaveBeenCalledWith('Observation saved!');
expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Observation saved!');
});
});
@ -117,5 +118,62 @@ describe('client defaulter', () => {
expect(controller.balanceDueTotal).toEqual(875);
});
});
describe('dateRange()', () => {
it('should return two dates with the hours at the start and end of the given date', () => {
const now = Date.vnNew();
const today = now.getDate();
const dateRange = controller.dateRange(now);
const start = dateRange[0].toString();
const end = dateRange[1].toString();
expect(start).toContain(today);
expect(start).toContain('00:00:00');
expect(end).toContain(today);
expect(end).toContain('23:59:59');
});
});
describe('reCheck()', () => {
it(`should recheck buys`, () => {
controller.$.model.data = [
{checked: false, clientFk: 1},
{checked: false, clientFk: 2},
{checked: false, clientFk: 3},
{checked: false, clientFk: 4},
];
controller.checkedDefaulers = [1, 2];
controller.reCheck();
expect(controller.$.model.data[0].checked).toEqual(true);
expect(controller.$.model.data[1].checked).toEqual(true);
expect(controller.$.model.data[2].checked).toEqual(false);
expect(controller.$.model.data[3].checked).toEqual(false);
});
});
describe('saveChecked()', () => {
it(`should check buy`, () => {
const buyCheck = 3;
controller.checkedDefaulers = [1, 2];
controller.saveChecked(buyCheck);
expect(controller.checkedDefaulers[2]).toEqual(buyCheck);
});
it(`should uncheck buy`, () => {
const buyUncheck = 3;
controller.checkedDefaulers = [1, 2, 3];
controller.saveChecked(buyUncheck);
expect(controller.checkedDefaulers[2]).toEqual(undefined);
});
});
});
});

View File

@ -6,4 +6,6 @@ Last observation: Última observación
L. O. Date: Fecha Ú. O.
Last observation date: Fecha última observación
Search client: Buscar clientes
Worker who made the last observation: Trabajador que ha realizado la última observación
Worker who made the last observation: Trabajador que ha realizado la última observación
Email sended!: Email enviado!
Observation saved!: Observación añadida!

View File

@ -2,6 +2,10 @@ import ngModule from '../module';
import Section from 'salix/components/section';
export default class Controller extends Section {
$onInit() {
this.card.reload();
}
onSubmit() {
const orgData = this.$.watcher.orgData;
delete this.client.despiteOfClient;

View File

@ -64,4 +64,7 @@ Compensation Account: Cuenta para compensar
Amount to return: Cantidad a devolver
Delivered amount: Cantidad entregada
Unpaid: Impagado
There is no zona: No hay zona
<<<<<<< HEAD
There is no zona: No hay zona
=======
>>>>>>> 736d0375f6b00d6eecb44c01ecc999c42dc219ae

View File

@ -0,0 +1,65 @@
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
const buildFilter = require('vn-loopback/util/filter').buildFilter;
const mergeFilters = require('vn-loopback/util/filter').mergeFilters;
module.exports = Self => {
Self.remoteMethodCtx('getSerial', {
description: 'Return invoiceIn serial',
accessType: 'READ',
accepts: [{
arg: 'filter',
type: 'object'
}, {
arg: 'daysAgo',
type: 'number',
required: true
}, {
arg: 'serial',
type: 'string'
}],
returns: {
type: 'object',
root: true
},
http: {
path: '/getSerial',
verb: 'GET'
}
});
Self.getSerial = async(ctx, options) => {
const conn = Self.dataSource.connector;
const args = ctx.args;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const issued = Date.vnNew();
const where = buildFilter(args, (param, value) => {
switch (param) {
case 'daysAgo':
issued.setDate(issued.getDate() - value);
return {'i.issued': {gte: issued}};
case 'serial':
return {'i.serial': {like: `%${value}%`}};
}
});
filter = mergeFilters(args.filter, {where});
const stmt = new ParameterizedSQL(
`SELECT i.serial, SUM(IF(i.isBooked, 0,1)) pending, COUNT(*) total
FROM vn.invoiceIn i`
);
stmt.merge(conn.makeWhere(filter.where));
stmt.merge(`GROUP BY i.serial`);
stmt.merge(conn.makeOrderBy(filter.order));
stmt.merge(conn.makeLimit(filter));
const result = await conn.executeStmt(stmt, myOptions);
return result;
};
};

View File

@ -0,0 +1,53 @@
const {toCSV} = require('vn-loopback/util/csv');
module.exports = Self => {
Self.remoteMethodCtx('negativeBasesCsv', {
description: 'Returns the negative bases as .csv',
accessType: 'READ',
accepts: [{
arg: 'negativeBases',
type: ['object'],
required: true
},
{
arg: 'from',
type: 'date',
description: 'From date'
},
{
arg: 'to',
type: 'date',
description: 'To date'
}],
returns: [
{
arg: 'body',
type: 'file',
root: true
}, {
arg: 'Content-Type',
type: 'String',
http: {target: 'header'}
}, {
arg: 'Content-Disposition',
type: 'String',
http: {target: 'header'}
}
],
http: {
path: '/negativeBasesCsv',
verb: 'GET'
}
});
Self.negativeBasesCsv = async ctx => {
const args = ctx.args;
const content = toCSV(args.negativeBases);
return [
content,
'text/csv',
`attachment; filename="negative-bases-${new Date(args.from).toLocaleDateString()}-${new Date(args.to).toLocaleDateString()}.csv"`
];
};
};
Can't render this file because it contains an unexpected character in line 50 and column 35.

View File

@ -0,0 +1,112 @@
const UserError = require('vn-loopback/util/user-error');
const ParameterizedSQL = require('loopback-connector').ParameterizedSQL;
module.exports = Self => {
Self.remoteMethodCtx('negativeBases', {
description: 'Find all negative bases',
accessType: 'READ',
accepts: [
{
arg: 'from',
type: 'date',
description: 'From date'
},
{
arg: 'to',
type: 'date',
description: 'To date'
},
{
arg: 'filter',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string'
},
],
returns: {
type: ['object'],
root: true
},
http: {
path: `/negativeBases`,
verb: 'GET'
}
});
Self.negativeBases = async(ctx, options) => {
const conn = Self.dataSource.connector;
const args = ctx.args;
if (!args.from || !args.to)
throw new UserError(`Insert a date range`);
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const stmts = [];
let stmt;
stmts.push(`DROP TEMPORARY TABLE IF EXISTS tmp.ticket`);
stmts.push(new ParameterizedSQL(
`CREATE TEMPORARY TABLE tmp.ticket
(KEY (ticketFk))
ENGINE = MEMORY
SELECT id ticketFk
FROM ticket t
WHERE shipped BETWEEN ? AND ?
AND refFk IS NULL`, [args.from, args.to]));
stmts.push(`CALL vn.ticket_getTax(NULL)`);
stmts.push(`DROP TEMPORARY TABLE IF EXISTS tmp.filter`);
stmts.push(new ParameterizedSQL(
`CREATE TEMPORARY TABLE tmp.filter
ENGINE = MEMORY
SELECT
co.code company,
cou.country,
c.id clientId,
c.socialName clientSocialName,
SUM(s.quantity * s.price * ( 100 - s.discount ) / 100) amount,
negativeBase.taxableBase,
negativeBase.ticketFk,
c.isActive,
c.hasToInvoice,
c.isTaxDataChecked,
w.id comercialId,
CONCAT(w.firstName, ' ', w.lastName) comercialName
FROM vn.ticket t
JOIN vn.company co ON co.id = t.companyFk
JOIN vn.sale s ON s.ticketFk = t.id
JOIN vn.client c ON c.id = t.clientFk
JOIN vn.country cou ON cou.id = c.countryFk
LEFT JOIN vn.worker w ON w.id = c.salesPersonFk
LEFT JOIN (
SELECT ticketFk, taxableBase
FROM tmp.ticketAmount
GROUP BY ticketFk
HAVING taxableBase < 0
) negativeBase ON negativeBase.ticketFk = t.id
WHERE t.shipped BETWEEN ? AND ?
AND t.refFk IS NULL
AND c.typeFk IN ('normal','trust')
GROUP BY t.clientFk, negativeBase.taxableBase
HAVING amount <> 0`, [args.from, args.to]));
stmt = new ParameterizedSQL(`
SELECT f.*
FROM tmp.filter f`);
stmt.merge(conn.makeWhere(args.filter.where));
stmt.merge(conn.makeOrderBy(args.filter.order));
const negativeBasesIndex = stmts.push(stmt) - 1;
stmts.push(`DROP TEMPORARY TABLE tmp.filter, tmp.ticket, tmp.ticketTax, tmp.ticketAmount`);
const sql = ParameterizedSQL.join(stmts, ';');
const result = await conn.executeStmt(sql, myOptions);
return negativeBasesIndex === 0 ? result : result[negativeBasesIndex];
};
};

View File

@ -0,0 +1,24 @@
const models = require('vn-loopback/server/server').models;
describe('invoiceIn getSerial()', () => {
it('should check that returns without serial param', async() => {
const ctx = {args: {daysAgo: 45}};
const result = await models.InvoiceIn.getSerial(ctx);
expect(result.length).toBeGreaterThan(0);
});
it('should check that returns with serial param', async() => {
const ctx = {args: {daysAgo: 45, serial: 'R'}};
const result = await models.InvoiceIn.getSerial(ctx);
expect(result.length).toBeGreaterThan(0);
});
it('should check that returns with non exist serial param', async() => {
const ctx = {args: {daysAgo: 45, serial: 'Mock serial'}};
const result = await models.InvoiceIn.getSerial(ctx);
expect(result.length).toEqual(0);
});
});

View File

@ -0,0 +1,47 @@
const models = require('vn-loopback/server/server').models;
describe('invoiceIn negativeBases()', () => {
it('should return all negative bases in a date range', async() => {
const tx = await models.InvoiceIn.beginTransaction({});
const options = {transaction: tx};
const ctx = {
args: {
from: new Date().setMonth(new Date().getMonth() - 12),
to: new Date(),
filter: {}
}
};
try {
const result = await models.InvoiceIn.negativeBases(ctx, options);
expect(result.length).toBeGreaterThan(0);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
it('should throw an error if a date range is not in args', async() => {
let error;
const tx = await models.InvoiceIn.beginTransaction({});
const options = {transaction: tx};
const ctx = {
args: {
filter: {}
}
};
try {
await models.InvoiceIn.negativeBases(ctx, options);
await tx.rollback();
} catch (e) {
error = e;
await tx.rollback();
}
expect(error.message).toEqual(`Insert a date range`);
});
});

View File

@ -17,6 +17,9 @@
},
"retentionName": {
"type": "string"
},
"daysAgo": {
"type": "number"
}
},
"relations": {

View File

@ -6,4 +6,7 @@ module.exports = Self => {
require('../methods/invoice-in/getTotals')(Self);
require('../methods/invoice-in/invoiceInPdf')(Self);
require('../methods/invoice-in/invoiceInEmail')(Self);
require('../methods/invoice-in/getSerial')(Self);
require('../methods/invoice-in/negativeBases')(Self);
require('../methods/invoice-in/negativeBasesCsv')(Self);
};

View File

@ -13,3 +13,6 @@ import './dueDay';
import './intrastat';
import './create';
import './log';
import './serial';
import './serial-search-panel';
import './negative-bases';

View File

@ -7,6 +7,7 @@ Foreign value: Divisa
InvoiceIn: Facturas recibidas
InvoiceIn cloned: Factura clonada
InvoiceIn deleted: Factura eliminada
InvoiceIn Serial: Facturas por series
Invoice list: Listado de facturas recibidas
InvoiceIn booked: Factura contabilizada
Net: Neto
@ -22,3 +23,5 @@ Total stems: Total tallos
Show agricultural receipt as PDF: Ver recibo agrícola como PDF
Send agricultural receipt as PDF: Enviar recibo agrícola como PDF
New InvoiceIn: Nueva Factura
Days ago: Últimos días
Negative bases: Bases negativas

View File

@ -0,0 +1,133 @@
<vn-crud-model
vn-id="model"
url="InvoiceIns/negativeBases"
auto-load="true"
params="$ctrl.params">
</vn-crud-model>
<vn-portal slot="topbar">
</vn-portal>
<vn-card>
<smart-table
model="model"
options="$ctrl.smartTableOptions"
expr-builder="$ctrl.exprBuilder(param, value)">
<slot-actions>
<vn-date-picker
vn-one
label="From"
ng-model="$ctrl.params.from"
on-change="model.refresh()">
</vn-date-picker>
<vn-date-picker
vn-one
label="To"
ng-model="$ctrl.params.to"
on-change="model.refresh()">
</vn-date-picker>
<vn-button
disabled="model._orgData.length == 0"
icon="download"
ng-click="$ctrl.downloadCSV()"
vn-tooltip="Download as CSV">
</vn-button>
</slot-actions>
<slot-table>
<table>
<thead>
<tr>
<th field="company">
<span translate>Company</span>
</th>
<th field="country">
<span translate>Country</span>
</th>
<th field="clientId">
<span translate>Id Client</span>
</th>
<th field="clientSocialName">
<span translate>Client</span>
</th>
<th field="amount">
<span translate>Amount</span>
</th>
<th field="taxableBase">
<span translate>Base</span>
</th>
<th field="ticketFk">
<span translate>Id Ticket</span>
</th>
<th field="isActive">
<span translate>Active</span>
</th>
<th field="hasToInvoice">
<span translate>Has To Invoice</span>
</th>
<th field="isTaxDataChecked">
<span translate>Verified data</span>
</th>
<th field="comercialName">
<span translate>Comercial</span>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="client in model.data">
<td>{{client.company | dashIfEmpty}}</td>
<td>{{client.country | dashIfEmpty}}</td>
<td>
<vn-span
class="link"
ng-click="clientDescriptor.show($event, client.clientId)">
{{::client.clientId | dashIfEmpty}}
</vn-span>
</td>
<td>{{client.clientSocialName | dashIfEmpty}}</td>
<td>{{client.amount | currency: 'EUR':2 | dashIfEmpty}}</td>
<td>{{client.taxableBase | dashIfEmpty}}</td>
<td>
<vn-span
class="link"
ng-click="ticketDescriptor.show($event, client.ticketFk)">
{{::client.ticketFk | dashIfEmpty}}
</vn-span>
</td>
<td>
<vn-check
disabled="true"
ng-model="client.isActive">
</vn-check>
</td>
<td>
<vn-check
disabled="true"
ng-model="client.hasToInvoice">
</vn-check>
</td>
<td>
<vn-check
disabled="true"
ng-model="client.isTaxDataChecked">
</vn-check>
</td>
<td>
<vn-span
class="link"
ng-click="workerDescriptor.show($event, client.comercialId)">
{{::client.comercialName | dashIfEmpty}}
</vn-span>
</td>
</tr>
</tbody>
</table>
</slot-table>
</smart-table>
</vn-card>
<vn-ticket-descriptor-popover
vn-id="ticket-descriptor">
</vn-ticket-descriptor-popover>
<vn-client-descriptor-popover
vn-id="client-descriptor">
</vn-client-descriptor-popover>
<vn-worker-descriptor-popover
vn-id="worker-descriptor">
</vn-worker-descriptor-popover>

View File

@ -0,0 +1,84 @@
import ngModule from '../module';
import Section from 'salix/components/section';
import './style.scss';
export default class Controller extends Section {
constructor($element, $, vnReport) {
super($element, $);
this.vnReport = vnReport;
const now = new Date();
const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
this.params = {
from: firstDayOfMonth,
to: lastDayOfMonth
};
this.$checkAll = false;
this.smartTableOptions = {
activeButtons: {
search: true,
}, columns: [
{
field: 'isActive',
searchable: false
},
{
field: 'hasToInvoice',
searchable: false
},
{
field: 'isTaxDataChecked',
searchable: false
},
]
};
}
exprBuilder(param, value) {
switch (param) {
case 'company':
return {'company': value};
case 'country':
return {'country': value};
case 'clientId':
return {'clientId': value};
case 'clientSocialName':
return {'clientSocialName': value};
case 'amount':
return {'amount': value};
case 'taxableBase':
return {'taxableBase': value};
case 'ticketFk':
return {'ticketFk': value};
case 'comercialName':
return {'comercialName': value};
}
}
downloadCSV() {
const data = [];
this.$.model._orgData.forEach(element => {
data.push(Object.keys(element).map(key => {
return {newName: this.$t(key), value: element[key]};
}).filter(item => item !== null)
.reduce((result, item) => {
result[item.newName] = item.value;
return result;
}, {}));
});
this.vnReport.show('InvoiceIns/negativeBasesCsv', {
negativeBases: data,
from: this.params.from,
to: this.params.to
});
}
}
Controller.$inject = ['$element', '$scope', 'vnReport'];
ngModule.vnComponent('vnNegativeBases', {
template: require('./index.html'),
controller: Controller
});

View File

@ -0,0 +1,14 @@
Has To Invoice: Facturar
Download as CSV: Descargar como CSV
company: Compañía
country: País
clientId: Id Cliente
clientSocialName: Cliente
amount: Importe
taxableBase: Base
ticketFk: Id Ticket
isActive: Activo
hasToInvoice: Facturar
isTaxDataChecked: Datos comprobados
comercialId: Id Comercial
comercialName: Comercial

View File

@ -0,0 +1,10 @@
@import "./variables";
vn-negative-bases {
vn-date-picker{
padding-right: 5%;
}
slot-actions{
align-items: center;
}
}

View File

@ -9,10 +9,9 @@
],
"menus": {
"main": [
{
"state": "invoiceIn.index",
"icon": "icon-invoice-in"
}
{ "state": "invoiceIn.index", "icon": "icon-invoice-in"},
{ "state": "invoiceIn.serial", "icon": "icon-invoice-in"},
{ "state": "invoiceIn.negative-bases", "icon": "icon-ticket"}
],
"card": [
{
@ -54,6 +53,24 @@
"administrative"
]
},
{
"url": "/negative-bases",
"state": "invoiceIn.negative-bases",
"component": "vn-negative-bases",
"description": "Negative bases",
"acl": [
"administrative"
]
},
{
"url": "/serial",
"state": "invoiceIn.serial",
"component": "vn-invoice-in-serial",
"description": "InvoiceIn Serial",
"acl": [
"administrative"
]
},
{
"url": "/:id",
"state": "invoiceIn.card",
@ -133,4 +150,4 @@
]
}
]
}
}

View File

@ -0,0 +1,27 @@
<vn-side-menu side="right">
<vn-horizontal class="input">
<vn-input-number
label="Days ago"
ng-model="$ctrl.filter.daysAgo"
vn-focus
ng-keydown="$ctrl.onKeyPress($event)"
min="0">
</vn-input-number>
</vn-horizontal>
<vn-horizontal class="input">
<vn-textfield
label="Serial"
ng-model="$ctrl.filter.serial"
ng-keydown="$ctrl.onKeyPress($event)">
</vn-textfield>
</vn-horizontal>
<div class="chips">
<vn-chip
ng-if="$ctrl.filter.serial"
removable="true"
on-remove="$ctrl.removeItemFilter('serial')"
class="colored">
<span>{{$ctrl.$t('Serial')}}: {{$ctrl.filter.serial}}</span>
</vn-chip>
</div>
</vn-side-menu>

View File

@ -0,0 +1,44 @@
import ngModule from '../module';
import SearchPanel from 'core/components/searchbar/search-panel';
import './style.scss';
class Controller extends SearchPanel {
constructor($element, $) {
super($element, $);
this.filter = {};
const filter = {
fields: ['daysAgo']
};
this.$http.get('InvoiceInConfigs', {filter}).then(res => {
if (res.data) {
this.invoiceInConfig = res.data[0];
this.addFilters();
}
});
}
removeItemFilter(param) {
this.filter[param] = null;
this.addFilters();
}
onKeyPress($event) {
if ($event.key === 'Enter')
this.addFilters();
}
addFilters() {
if (!this.filter.daysAgo)
this.filter.daysAgo = this.invoiceInConfig.daysAgo;
return this.model.addFilter({}, this.filter);
}
}
ngModule.component('vnInvoiceInSerialSearchPanel', {
template: require('./index.html'),
controller: Controller,
bindings: {
model: '<'
}
});

View File

@ -0,0 +1,43 @@
import './index.js';
describe('InvoiceIn', () => {
describe('Component serial-search-panel', () => {
let controller;
let $scope;
beforeEach(ngModule('invoiceIn'));
beforeEach(inject(($componentController, $rootScope) => {
$scope = $rootScope.$new();
const $element = angular.element('<vn-invoice-in-serial-search-panel></vn-invoice-in-serial-search-panel>');
controller = $componentController('vnInvoiceInSerialSearchPanel', {$element, $scope});
controller.model = {
addFilter: jest.fn(),
};
controller.invoiceInConfig = {
daysAgo: 45,
};
}));
describe('addFilters()', () => {
it('should add default daysAgo if it is not already set', () => {
controller.filter = {
serial: 'R',
};
controller.addFilters();
expect(controller.filter.daysAgo).toEqual(controller.invoiceInConfig.daysAgo);
});
it('should not add default daysAgo if it is already set', () => {
controller.filter = {
daysAgo: 1,
serial: 'R',
};
controller.addFilters();
expect(controller.filter.daysAgo).toEqual(1);
});
});
});
});

View File

@ -0,0 +1,24 @@
@import "variables";
vn-invoice-in-serial-search-panel vn-side-menu div {
& > .input {
padding-left: $spacing-md;
padding-right: $spacing-md;
border-color: $color-spacer;
border-bottom: $border-thin;
}
& > .horizontal {
grid-auto-flow: column;
grid-column-gap: $spacing-sm;
align-items: center;
}
& > .chips {
display: flex;
flex-wrap: wrap;
padding: $spacing-md;
overflow: hidden;
max-width: 100%;
border-color: $color-spacer;
border-top: $border-thin;
}
}

View File

@ -0,0 +1,40 @@
<vn-crud-model
vn-id="model"
url="InvoiceIns/getSerial"
limit="20">
</vn-crud-model>
<vn-portal slot="topbar">
</vn-portal>
<vn-invoice-in-serial-search-panel
model="model">
</vn-invoice-in-serial-search-panel>
<vn-data-viewer
model="model"
class="vn-w-lg">
<vn-card>
<vn-table model="model">
<vn-thead>
<vn-tr>
<vn-th field="serial">Serial</vn-th>
<vn-th field="pending">Pending</vn-th>
<vn-th field="total">Total</vn-th>
<vn-th></vn-th>
</vn-tr>
</vn-thead>
<vn-tbody>
<vn-tr ng-repeat="invoiceIn in model.data">
<vn-td>{{::invoiceIn.serial}}</vn-td>
<vn-td>{{::invoiceIn.pending}}</vn-td>
<vn-td>{{::invoiceIn.total}}</vn-td>
<vn-td shrink>
<vn-icon-button
vn-click-stop="$ctrl.goToIndex(model.userParams.daysAgo, invoiceIn.serial)"
vn-tooltip="Go to InvoiceIn"
icon="icon-invoice-in">
</vn-icon-button>
</vn-td>
</vn-tr>
</vn-tbody>
</vn-table>
</vn-card>
</vn-data-viewer>

View File

@ -0,0 +1,22 @@
import ngModule from '../module';
import Section from 'salix/components/section';
export default class Controller extends Section {
constructor($element, $) {
super($element, $);
}
goToIndex(daysAgo, serial) {
const issued = Date.vnNew();
issued.setDate(issued.getDate() - daysAgo);
this.$state.go('invoiceIn.index',
{q: `{"serial": "${serial}", "isBooked": false, "from": ${issued.getTime()}}`});
}
}
Controller.$inject = ['$element', '$scope'];
ngModule.vnComponent('vnInvoiceInSerial', {
template: require('./index.html'),
controller: Controller
});

View File

@ -0,0 +1,3 @@
Serial: Serie
Pending: Pendientes
Go to InvoiceIn: Ir al listado de facturas recibidas

View File

@ -0,0 +1,96 @@
module.exports = Self => {
Self.remoteMethodCtx('editFixedPrice', {
description: 'Updates a column for one or more fixed price',
accessType: 'WRITE',
accepts: [{
arg: 'field',
type: 'string',
required: true,
description: `the column to edit`
},
{
arg: 'newValue',
type: 'any',
required: true,
description: `The new value to save`
},
{
arg: 'lines',
type: ['object'],
required: true,
description: `the buys which will be modified`
},
{
arg: 'filter',
type: 'object',
description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string'
}],
returns: {
type: 'object',
root: true
},
http: {
path: `/editFixedPrice`,
verb: 'POST'
}
});
Self.editFixedPrice = async(ctx, field, newValue, lines, filter, options) => {
let tx;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
if (!myOptions.transaction) {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
let modelName;
let identifier;
switch (field) {
case 'hasMinPrice':
case 'minPrice':
modelName = 'Item';
identifier = 'itemFk';
break;
case 'rate2':
case 'rate3':
case 'started':
case 'ended':
case 'warehouseFk':
modelName = 'FixedPrice';
identifier = 'id';
}
const models = Self.app.models;
const model = models[modelName];
try {
const promises = [];
const value = {};
value[field] = newValue;
if (filter) {
filter = {where: filter};
lines = await models.FixedPrice.filter(ctx, filter, myOptions);
}
const targets = lines.map(line => {
return line[identifier];
});
for (let target of targets)
promises.push(model.upsertWithWhere({id: target}, value, myOptions));
const result = await Promise.all(promises);
if (tx) await tx.commit();
return result;
} catch (e) {
if (tx) await tx.rollback();
throw e;
}
};
};

View File

@ -184,8 +184,7 @@ module.exports = Self => {
}
}
stmt.merge(conn.makeWhere(filter.where));
stmt.merge(conn.makePagination(filter));
stmt.merge(conn.makeSuffix(filter));
const fixedPriceIndex = stmts.push(stmt) - 1;
const sql = ParameterizedSQL.join(stmts, ';');

View File

@ -0,0 +1,63 @@
const models = require('vn-loopback/server/server').models;
describe('Item editFixedPrice()', () => {
it('should change the value of a given column for the selected buys', async() => {
const tx = await models.FixedPrice.beginTransaction({});
const options = {transaction: tx};
try {
const ctx = {
args: {
search: '1'
},
req: {accessToken: {userId: 1}}
};
const [original] = await models.FixedPrice.filter(ctx, null, options);
const field = 'rate2';
const newValue = 99;
const lines = [{itemFk: original.itemFk, id: original.id}];
await models.FixedPrice.editFixedPrice(ctx, field, newValue, lines, null, options);
const [result] = await models.FixedPrice.filter(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', async() => {
const tx = await models.FixedPrice.beginTransaction({});
const options = {transaction: tx};
try {
const filter = {'it.categoryFk': 1};
const ctx = {
args: {
filter: filter
},
req: {accessToken: {userId: 1}}
};
const field = 'rate2';
const newValue = 88;
await models.FixedPrice.editFixedPrice(ctx, field, newValue, null, filter, options);
const [result] = await models.FixedPrice.filter(ctx, filter, options);
expect(result[field]).toEqual(newValue);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
});
});

View File

@ -42,7 +42,7 @@ describe('upsertFixedPrice()', () => {
delete ctx.args.started;
delete ctx.args.ended;
ctx.args.hasMinPrice = true;
ctx.args.hasMinPrice = false;
expect(result).toEqual(jasmine.objectContaining(ctx.args));
@ -74,7 +74,7 @@ describe('upsertFixedPrice()', () => {
delete ctx.args.started;
delete ctx.args.ended;
ctx.args.hasMinPrice = false;
ctx.args.hasMinPrice = true;
expect(result).toEqual(jasmine.objectContaining(ctx.args));
@ -105,7 +105,7 @@ describe('upsertFixedPrice()', () => {
rate2: rate2,
rate3: firstRate3,
minPrice: 0,
hasMinPrice: false
hasMinPrice: true
}};
// create new fixed price

View File

@ -87,7 +87,7 @@ module.exports = Self => {
await targetItem.updateAttributes({
minPrice: args.minPrice,
hasMinPrice: args.minPrice ? true : false
hasMinPrice: args.hasMinPrice
}, myOptions);
const itemFields = [

View File

@ -1,7 +1,7 @@
const axios = require('axios');
const uuid = require('uuid');
const fs = require('fs/promises');
const { createWriteStream } = require('fs');
const {createWriteStream} = require('fs');
const path = require('path');
const gm = require('gm');
@ -15,7 +15,7 @@ module.exports = Self => {
},
});
Self.download = async () => {
Self.download = async() => {
const models = Self.app.models;
const tempContainer = await models.TempContainer.container(
'salix-image'
@ -32,13 +32,13 @@ module.exports = Self => {
let tempFilePath;
let queueRow;
try {
const myOptions = { transaction: tx };
const myOptions = {transaction: tx};
queueRow = await Self.findOne(
{
fields: ['id', 'itemFk', 'url', 'attempts'],
where: {
url: { neq: null },
url: {neq: null},
attempts: {
lt: maxAttempts,
},
@ -59,7 +59,7 @@ module.exports = Self => {
'model',
'property',
],
where: { name: collectionName },
where: {name: collectionName},
include: {
relation: 'sizes',
scope: {
@ -116,16 +116,16 @@ module.exports = Self => {
const collectionDir = path.join(rootPath, collectionName);
// To max size
const { maxWidth, maxHeight } = collection;
const {maxWidth, maxHeight} = collection;
const fullSizePath = path.join(collectionDir, 'full');
const toFullSizePath = `${fullSizePath}/${fileName}`;
await fs.mkdir(fullSizePath, { recursive: true });
await fs.mkdir(fullSizePath, {recursive: true});
await new Promise((resolve, reject) => {
gm(tempFilePath)
.resize(maxWidth, maxHeight, '>')
.setFormat('png')
.write(toFullSizePath, function (err) {
.write(toFullSizePath, function(err) {
if (err) reject(err);
if (!err) resolve();
});
@ -133,12 +133,12 @@ module.exports = Self => {
// To collection sizes
for (const size of collection.sizes()) {
const { width, height } = size;
const {width, height} = size;
const sizePath = path.join(collectionDir, `${width}x${height}`);
const toSizePath = `${sizePath}/${fileName}`;
await fs.mkdir(sizePath, { recursive: true });
await fs.mkdir(sizePath, {recursive: true});
await new Promise((resolve, reject) => {
const gmInstance = gm(tempFilePath);
@ -153,7 +153,7 @@ module.exports = Self => {
gmInstance
.setFormat('png')
.write(toSizePath, function (err) {
.write(toSizePath, function(err) {
if (err) reject(err);
if (!err) resolve();
});

View File

@ -1,105 +0,0 @@
const https = require('https');
const fs = require('fs-extra');
const path = require('path');
const uuid = require('uuid');
module.exports = Self => {
Self.remoteMethod('downloadImages', {
description: 'Returns last entries',
accessType: 'WRITE',
returns: {
type: ['Object'],
root: true
},
http: {
path: `/downloadImages`,
verb: 'POST'
}
});
Self.downloadImages = async() => {
const models = Self.app.models;
const container = await models.TempContainer.container('salix-image');
const tempPath = path.join(container.client.root, container.name);
const maxAttempts = 3;
const images = await Self.find({
where: {attempts: {eq: maxAttempts}}
});
for (let image of images) {
const currentStamp = Date.vnNew().getTime();
const updatedStamp = image.updated.getTime();
const graceTime = Math.abs(currentStamp - updatedStamp);
const maxTTL = 3600 * 48 * 1000; // 48 hours in ms;
if (graceTime >= maxTTL)
await Self.destroyById(image.itemFk);
}
download();
async function download() {
const image = await Self.findOne({
where: {url: {neq: null}, attempts: {lt: maxAttempts}},
order: 'priority, attempts, updated'
});
if (!image) return;
const fileName = `${uuid.v4()}.png`;
const filePath = path.join(tempPath, fileName);
const imageUrl = image.url.replace('http://', 'https://');
https.get(imageUrl, async response => {
if (response.statusCode != 200) {
const error = new Error(`Could not download the image. Status code ${response.statusCode}`);
return await errorHandler(image.itemFk, error, filePath);
}
const writeStream = fs.createWriteStream(filePath);
writeStream.on('open', () => response.pipe(writeStream));
writeStream.on('error', async error =>
await errorHandler(image.itemFk, error, filePath));
writeStream.on('finish', () => writeStream.end());
writeStream.on('close', async function() {
try {
await models.Image.registerImage('catalog', filePath, fileName, image.itemFk);
await image.destroy();
download();
} catch (error) {
await errorHandler(image.itemFk, error, filePath);
}
});
}).on('error', async error => {
await errorHandler(image.itemFk, error, filePath);
});
}
async function errorHandler(rowId, error, filePath) {
try {
const row = await Self.findById(rowId);
if (!row) return;
if (row.attempts < maxAttempts) {
await row.updateAttributes({
error: error,
attempts: row.attempts + 1,
updated: Date.vnNew()
});
}
if (filePath && fs.existsSync(filePath))
await fs.unlink(filePath);
download();
} catch (err) {
throw new Error(`Image download failed: ${err}`);
}
}
};
};

View File

@ -2,4 +2,5 @@ module.exports = Self => {
require('../methods/fixed-price/filter')(Self);
require('../methods/fixed-price/upsertFixedPrice')(Self);
require('../methods/fixed-price/getRate2')(Self);
require('../methods/fixed-price/editFixedPrice')(Self);
};

View File

@ -20,6 +20,9 @@
},
"created": {
"type": "date"
},
"isChecked": {
"type": "boolean"
}
},
"relations": {

View File

@ -1,6 +1,7 @@
<vn-crud-model
vn-id="model"
url="FixedPrices/filter"
user-params="::$ctrl.filterParams"
limit="20"
data="prices"
order="itemFk"
@ -17,6 +18,8 @@
auto-state="false"
panel="vn-fixed-price-search-panel"
info="Search prices by item ID or code"
suggested-filter="$ctrl.filterParams"
filter="$ctrl.filterParams"
placeholder="Search fixed prices"
model="model">
</vn-searchbar>
@ -31,15 +34,21 @@
<table>
<thead>
<tr>
<th shrink>
<vn-multi-check
model="model"
checked="$ctrl.checkAll"
check-field="checked"
check-dummy-enabled="true"
checked-dummy-count="$ctrl.checkedDummyCount">
</vn-multi-check>
</th>
<th field="itemFk">
<span translate>Item ID</span>
</th>
<th field="name">
<span translate>Description</span>
</th>
<th field="warehouseFk">
<span translate>Warehouse</span>
</th>
<th
field="rate2">
<span translate>Grouping price</span>
@ -57,13 +66,24 @@
<th field="ended">
<span translate>Ended</span>
</th>
<th field="warehouseFk">
<span translate>Warehouse</span>
</th>
<th shrink></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="price in prices">
<td>
<vn-check
ng-model="price.checked"
on-change="$ctrl.saveChecked(price.id)"
vn-click-stop>
</vn-check>
</td>
<td shrink-field>
<vn-autocomplete
vn-id="itemFk"
class="dense"
url="Items/withName"
ng-model="price.itemFk"
@ -88,7 +108,7 @@
ng-if="price.itemFk"
ng-click="itemDescriptor.show($event, price.itemFk)"
class="link">
{{price.name}}
{{itemFk.selection.name}}
</span>
<vn-one ng-if="price.subName">
<h3 title="{{price.subName}}">{{price.subName}}</h3>
@ -100,18 +120,11 @@
tabindex="-1">
</vn-fetched-tags>
</td>
<td shrink-field-expand>
<vn-autocomplete
vn-one
ng-model="price.warehouseFk"
data="warehouses"
on-change="$ctrl.upsertPrice(price)"
tabindex="2">
</vn-autocomplete>
</td>
<td shrink-field>
<vn-td-editable number>
<text>{{price.rate2 | currency: 'EUR':2}}</text>
<text>
<strong>{{price.rate2 | currency: 'EUR':2}}</strong>
</text>
<field>
<vn-input-number
class="dense"
@ -125,7 +138,9 @@
</td>
<td shrink-field>
<vn-td-editable number>
<text>{{price.rate3 | currency: 'EUR':2}}</text>
<text>
<strong>{{price.rate3 | currency: 'EUR':2}}</strong>
</text>
<field>
<vn-input-number
class="dense"
@ -140,28 +155,42 @@
<td shrink-field-expand class="minPrice">
<vn-check
vn-one
ng-model="price.hasMinPrice">
ng-model="price.hasMinPrice"
on-change="$ctrl.upsertPrice(price)">
</vn-check>
<vn-input-number
disabled="!price.hasMinPrice"
ng-class="{inactive: !price.hasMinPrice}"
ng-model="price.minPrice"
on-change="$ctrl.upsertPrice(price)"
step="0.01">
</vn-input-number>
</td>
<td shrink-date>
<vn-date-picker
vn-one
ng-model="price.started"
on-change="$ctrl.upsertPrice(price)">
</vn-date-picker>
<vn-chip class="chip {{$ctrl.isBigger(price.started)}} transparent">
<vn-date-picker
vn-one
ng-model="price.started"
on-change="$ctrl.upsertPrice(price)">
</vn-date-picker>
</vn-chip>
</td>
<td shrink-date>
<vn-date-picker
<vn-chip class="chip {{$ctrl.isLower(price.ended)}} transparent">
<vn-date-picker
vn-one
ng-model="price.ended"
on-change="$ctrl.upsertPrice(price)">
</vn-date-picker>
</vn-chip>
</td>
<td expand>
<vn-autocomplete
vn-one
ng-model="price.ended"
on-change="$ctrl.upsertPrice(price)">
</vn-date-picker>
ng-model="price.warehouseFk"
data="warehouses"
on-change="$ctrl.upsertPrice(price)"
tabindex="2">
</vn-autocomplete>
</td>
<td shrink>
<vn-icon-button
@ -185,6 +214,69 @@
</smart-table>
</vn-card>
</div>
<div fixed-bottom-right>
<vn-vertical style="align-items: center;">
<vn-button class="round sm vn-mb-sm"
icon="edit"
ng-show="$ctrl.totalChecked > 0"
ng-click="edit.show($event)"
vn-tooltip="Edit fixed price(s)"
tooltip-position="left">
</vn-button>
</vn-vertical>
</div>
<vn-dialog class="edit"
vn-id="edit"
on-accept="$ctrl.onEditAccept()"
on-close="$ctrl.editedColumn = null">
<tpl-body style="width: 400px;">
<span translate>Edit</span>
<span class="countLines">
{{::$ctrl.totalChecked}}
</span>
<span translate>buy(s)</span>
<vn-horizontal>
<vn-autocomplete
vn-one
ng-model="$ctrl.editedColumn.field"
data="$ctrl.columns"
value-field="field"
show-field="displayName"
label="Field to edit">
</vn-autocomplete>
<vn-input-number
vn-one
ng-if="$ctrl.editedColumn.field == 'rate2' || $ctrl.editedColumn.field == 'rate3' || $ctrl.editedColumn.field == 'minPrice'"
label="Value"
ng-model="$ctrl.editedColumn.newValue">
</vn-input-number>
<vn-check
vn-one
ng-if="$ctrl.editedColumn.field == 'hasMinPrice'"
ng-model="$ctrl.editedColumn.newValue">
</vn-check>
<vn-date-picker
vn-one
ng-if="$ctrl.editedColumn.field == 'started' || $ctrl.editedColumn.field == 'ended'"
label="Date"
ng-model="$ctrl.editedColumn.newValue">
</vn-date-picker>
<vn-autocomplete
vn-one
ng-if="$ctrl.editedColumn.field == 'warehouseFk'"
label="Warehouse"
ng-model="$ctrl.editedColumn.newValue"
data="warehouses">
</vn-autocomplete>
</vn-horizontal>
</tpl-body>
<tpl-buttons>
<input type="button" response="cancel" translate-attr="{value: 'Cancel'}"/>
<button response="accept" translate>Save</button>
</tpl-buttons>
</vn-dialog>
<vn-item-descriptor-popover
vn-id="item-descriptor"
warehouse-fk="$ctrl.vnConfig.warehouseFk">

View File

@ -5,6 +5,9 @@ import './style.scss';
export default class Controller extends Section {
constructor($element, $) {
super($element, $);
this.editedColumn;
this.checkAll = false;
this.checkedFixedPrices = [];
this.smartTableOptions = {
activeButtons: {
@ -30,13 +33,146 @@ export default class Controller extends Section {
}
]
};
this.filterParams = {
warehouseFk: this.vnConfig.warehouseFk
};
}
getFilterParams() {
return {
warehouseFk: this.vnConfig.warehouseFk
};
}
get columns() {
if (this._columns) return this._columns;
this._columns = [
{field: 'rate2', displayName: this.$t('Grouping price')},
{field: 'rate3', displayName: this.$t('Packing price')},
{field: 'hasMinPrice', displayName: this.$t('Has min price')},
{field: 'minPrice', displayName: this.$t('Min price')},
{field: 'started', displayName: this.$t('Started')},
{field: 'ended', displayName: this.$t('Ended')},
{field: 'warehouseFk', displayName: this.$t('Warehouse')}
];
return this._columns;
}
get checked() {
const fixedPrices = this.$.model.data || [];
const checkedBuys = [];
for (let fixedPrice of fixedPrices) {
if (fixedPrice.checked)
checkedBuys.push(fixedPrice);
}
return checkedBuys;
}
uncheck() {
this.checkAll = false;
this.checkedFixedPrices = [];
}
get totalChecked() {
if (this.checkedDummyCount)
return this.checkedDummyCount;
return this.checked.length;
}
saveChecked(fixedPriceId) {
const index = this.checkedFixedPrices.indexOf(fixedPriceId);
if (index !== -1)
return this.checkedFixedPrices.splice(index, 1);
return this.checkedFixedPrices.push(fixedPriceId);
}
reCheck() {
if (!this.$.model.data) return;
if (!this.checkedFixedPrices.length) return;
this.$.model.data.forEach(fixedPrice => {
if (this.checkedFixedPrices.includes(fixedPrice.id))
fixedPrice.checked = true;
});
}
onEditAccept() {
const rowsToEdit = [];
for (let row of this.checked)
rowsToEdit.push({id: row.id, itemFk: row.itemFk});
const data = {
field: this.editedColumn.field,
newValue: this.editedColumn.newValue,
lines: rowsToEdit
};
if (this.checkedDummyCount && this.checkedDummyCount > 0) {
const params = {};
if (this.$.model.userParams) {
const userParams = this.$.model.userParams;
for (let param in userParams) {
let newParam = this.exprBuilder(param, userParams[param]);
if (!newParam)
newParam = {[param]: userParams[param]};
Object.assign(params, newParam);
}
}
if (this.$.model.userFilter)
Object.assign(params, this.$.model.userFilter.where);
data.filter = params;
}
return this.$http.post('FixedPrices/editFixedPrice', data)
.then(() => {
this.uncheck();
this.$.model.refresh();
});
}
isBigger(date) {
let today = Date.vnNew();
today.setHours(0, 0, 0, 0);
date = new Date(date);
date.setHours(0, 0, 0, 0);
const timeDifference = today - date;
if (timeDifference < 0) return 'warning';
}
isLower(date) {
let today = Date.vnNew();
today.setHours(0, 0, 0, 0);
date = new Date(date);
date.setHours(0, 0, 0, 0);
const timeDifference = today - date;
if (timeDifference > 0) return 'warning';
}
add() {
if (!this.$.model.data || this.$.model.data.length == 0) {
this.$.model.data = [];
this.$.model.proxiedData = [];
this.$.model.insert({});
const today = Date.vnNew();
const millisecsInDay = 86400000;
const daysInWeek = 7;
const nextWeek = new Date(today.getTime() + daysInWeek * millisecsInDay);
this.$.model.insert({
started: today,
ended: nextWeek
});
return;
}
@ -66,10 +202,8 @@ export default class Controller extends Section {
if (resetMinPrice)
delete price['minPrice'];
price.hasMinPrice = price.minPrice ? true : false;
let requiredFields = ['itemFk', 'started', 'ended', 'rate2', 'rate3'];
for (let field of requiredFields)
const requiredFields = ['itemFk', 'started', 'ended', 'rate2', 'rate3'];
for (const field of requiredFields)
if (price[field] == undefined) return;
const query = 'FixedPrices/upsertFixedPrice';

View File

@ -12,8 +12,92 @@ describe('fixed price', () => {
const $scope = $rootScope.$new();
const $element = angular.element('<vn-fixed-price></vn-fixed-price>');
controller = $componentController('vnFixedPrice', {$element, $scope});
controller.$ = {
model: {refresh: () => {}},
edit: {hide: () => {}}
};
}));
describe('get columns', () => {
it(`should return a set of columns`, () => {
let result = controller.columns;
let length = result.length;
let anyColumn = Object.keys(result[Math.floor(Math.random() * Math.floor(length))]);
expect(anyColumn).toContain('field', 'displayName');
});
});
describe('get checked', () => {
it(`should return a set of checked lines`, () => {
controller.$.model.data = [
{checked: true, id: 1},
{checked: true, id: 2},
{checked: true, id: 3},
{checked: false, id: 4},
];
let result = controller.checked;
expect(result.length).toEqual(3);
});
});
describe('reCheck()', () => {
it(`should recheck buys`, () => {
controller.$.model.data = [
{checked: false, id: 1},
{checked: false, id: 2},
{checked: false, id: 3},
{checked: false, id: 4},
];
controller.checkedFixedPrices = [1, 2];
controller.reCheck();
expect(controller.$.model.data[0].checked).toEqual(true);
expect(controller.$.model.data[1].checked).toEqual(true);
expect(controller.$.model.data[2].checked).toEqual(false);
expect(controller.$.model.data[3].checked).toEqual(false);
});
});
describe('saveChecked()', () => {
it(`should check buy`, () => {
const buyCheck = 3;
controller.checkedFixedPrices = [1, 2];
controller.saveChecked(buyCheck);
expect(controller.checkedFixedPrices[2]).toEqual(buyCheck);
});
it(`should uncheck buy`, () => {
const buyUncheck = 3;
controller.checkedFixedPrices = [1, 2, 3];
controller.saveChecked(buyUncheck);
expect(controller.checkedFixedPrices[2]).toEqual(undefined);
});
});
describe('onEditAccept()', () => {
it(`should perform a query to update columns`, () => {
controller.editedColumn = {field: 'my field', newValue: 'the new value'};
const query = 'FixedPrices/editFixedPrice';
$httpBackend.expectPOST(query).respond();
controller.onEditAccept();
$httpBackend.flush();
const result = controller.checked;
expect(result.length).toEqual(0);
});
});
describe('upsertPrice()', () => {
it('should do nothing if one or more required arguments are missing', () => {
jest.spyOn(controller.vnApp, 'showSuccess');

View File

@ -3,3 +3,5 @@ Search prices by item ID or code: Buscar por ID de artículo o código
Search fixed prices: Buscar precios fijados
Add fixed price: Añadir precio fijado
This row will be removed: Esta linea se eliminará
Edit fixed price(s): Editar precio(s) fijado(s)
Has min price: Tiene precio mínimo

View File

@ -1,20 +1,46 @@
@import "variables";
smart-table table{
[shrink-field]{
width: 80px;
max-width: 80px;
vn-fixed-price{
smart-table table{
[shrink-field]{
width: 80px;
max-width: 80px;
}
[shrink-field-expand]{
width: 150px;
max-width: 150px;
}
}
[shrink-field-expand]{
width: 150px;
max-width: 150px;
.minPrice {
align-items: center;
text-align: center;
vn-input-number {
width: 90px;
max-width: 90px;
}
}
smart-table table tbody > * > td .chip {
padding: 0px;
}
smart-table table tbody > * > td{
padding: 0px;
padding-left: 5px;
padding-right: 5px;
}
smart-table table tbody > * > td .chip.warning {
color: $color-font-bg
}
.vn-field > .container > .infix > .control > input {
color: inherit;
}
vn-input-number.inactive{
input {
color: $color-font-light !important;
}
}
}
.minPrice {
align-items: center;
text-align: center;
vn-input-number {
width: 90px;
max-width: 90px;
}
}

View File

@ -40,11 +40,11 @@ Create: Crear
Client card: Ficha del cliente
Shipped: F. envío
stems: Tallos
Weight/Piece: Peso/tallo
Weight/Piece: Peso (gramos)/tallo
Search items by id, name or barcode: Buscar articulos por identificador, nombre o codigo de barras
SalesPerson: Comercial
Concept: Concepto
Units/Box: Unidades/Caja
Units/Box: Unidades/caja
# Sections
Items: Artículos

View File

@ -38,6 +38,19 @@
url="Warehouses">
</vn-autocomplete>
</vn-horizontal>
<vn-horizontal class="vn-px-lg">
<vn-autocomplete
vn-one
ng-model="filter.requesterFk"
url="Workers/activeWithRole"
search-function="{firstName: $search}"
value-field="id"
where="{role: 'salesPerson'}"
label="Comercial">
<tpl-item>{{firstName}} {{lastName}}</tpl-item>
</vn-autocomplete>
</vn-horizontal>
<section class="vn-px-md">
<vn-horizontal class="manifold-panel vn-pa-md">
<vn-date-picker

View File

@ -367,20 +367,37 @@ module.exports = Self => {
return {'t.alertLevel': value};
case 'pending':
if (value) {
return {and: [
{'t.alertLevel': 0},
{'t.alertLevelCode': {nin: [
'OK',
'BOARDING',
'PRINTED',
'PRINTED_AUTO',
'PICKER_DESIGNED'
]}}
]};
return {'t.alertLevelCode': {inq: [
'FIXING',
'FREE',
'NOT_READY',
'BLOCKED',
'EXPANDABLE',
'CHAINED',
'WAITING_FOR_PAYMENT'
]}};
} else {
return {and: [
{'t.alertLevel': {gt: 0}}
]};
return {'t.alertLevelCode': {inq: [
'ON_PREPARATION',
'ON_CHECKING',
'CHECKED',
'PACKING',
'PACKED',
'INVOICED',
'ON_DELIVERY',
'PREPARED',
'WAITING_FOR_PICKUP',
'DELIVERED',
'PRINTED_BACK',
'LAST_CALL',
'PREVIOUS_PREPARATION',
'ASSISTED_PREPARATION',
'BOARD',
'PRINTED STOWAWAY',
'OK STOWAWAY',
'HALF_PACKED',
'COOLER_PREPARATION'
]}};
}
case 'agencyModeFk':
case 'warehouseFk':

View File

@ -5,4 +5,5 @@ M3 Price: Precio M3
Route Price: Precio ruta
Minimum Km: Km minimos
Remove row: Eliminar fila
Add row: Añadir fila
Add row: Añadir fila
New autonomous: Nuevo autónomo

View File

@ -37,6 +37,10 @@ module.exports = Self => {
type: 'number',
description: `Search requests attended by a given worker id`
},
{
arg: 'requesterFk',
type: 'number'
},
{
arg: 'mine',
type: 'boolean',
@ -89,6 +93,8 @@ module.exports = Self => {
return {'t.id': value};
case 'attenderFk':
return {'tr.attenderFk': value};
case 'requesterFk':
return {'tr.requesterFk': value};
case 'state':
switch (value) {
case 'pending':
@ -125,6 +131,7 @@ module.exports = Self => {
tr.description,
tr.response,
tr.saleFk,
tr.requesterFk,
tr.isOk,
s.quantity AS saleQuantity,
s.itemFk,

View File

@ -1,4 +1,4 @@
Status log: Hitorial de estados
Status log: Historial de estados
Expedition removed: Expedición eliminada
Move: Mover
New ticket without route: Nuevo ticket sin ruta

View File

@ -28,8 +28,9 @@
</vn-button-menu>
<vn-button icon="keyboard_arrow_down"
label="More"
ng-click="moreOptions.show($event)"
ng-show="$ctrl.hasSelectedSales()">
disabled="!$ctrl.hasSelectedSales()"
vn-tooltip="Select lines to see the options"
ng-click="moreOptions.show($event)">
</vn-button>
<vn-button
disabled="!$ctrl.hasSelectedSales() || !$ctrl.isEditable"

View File

@ -40,3 +40,4 @@ Refund: Abono
Promotion mana: Maná promoción
Claim mana: Maná reclamación
History: Historial
Select lines to see the options: Seleccione lineas para ver las opciones

View File

@ -6,6 +6,6 @@ Phy. KG: KG físico
Vol. KG: KG Vol.
Search by travel id or reference: Buscar por id de travel o referencia
Search by extra community travel: Buscar por envío extra comunitario
Continent Out: Continente salida
Continent Out: Cont. salida
W. Shipped: F. envío
W. Landed: F. llegada
W. Landed: F. llegada

View File

@ -2,6 +2,15 @@
<vn-auto-search
model="model">
</vn-auto-search>
<vn-travel-search-panel
model="model">
</vn-travel-search-panel>
<vn-crud-model
vn-id="model"
url="Travels/filter"
limit="20"
order="shipped DESC, landed DESC">
</vn-crud-model>
<vn-data-viewer
model="model"
class="vn-mb-xl vn-w-xl">
@ -9,23 +18,22 @@
<vn-table model="model">
<vn-thead>
<vn-tr>
<vn-th field="id" number filter-enabled="false">Id</vn-th>
<vn-th field="ref">Reference</vn-th>
<vn-th field="agencyModeFk">Agency</vn-th>
<vn-th field="warehouseOutFk">Warehouse Out</vn-th>
<vn-th field="shipped" center shrink-date>Shipped</vn-th>
<vn-th field="isDelivered" center>Delivered</vn-th>
<vn-th shrink></vn-th>
<vn-th field="warehouseInFk">Warehouse In</vn-th>
<vn-th field="landed" center shrink-date>Landed</vn-th>
<vn-th field="isReceived" center>Received</vn-th>
<vn-th shrink></vn-th>
<vn-th shrink field="totalEntries">Total entries</vn-th>
<vn-th shrink></vn-th>
</vn-tr>
</vn-thead>
<vn-tbody>
<a ng-repeat="travel in model.data"
<a ng-repeat="travel in model.data"
class="clickable vn-tr search-result"
ui-sref="travel.card.summary({id: {{::travel.id}}})">
<vn-td number>{{::travel.id}}</vn-td>
<vn-td>{{::travel.ref}}</vn-td>
<vn-td>{{::travel.agencyModeName}}</vn-td>
<vn-td>{{::travel.warehouseOutName}}</vn-td>
@ -34,14 +42,27 @@
{{::travel.shipped | date:'dd/MM/yyyy'}}
</span>
</vn-td>
<vn-td center><vn-check ng-model="travel.isDelivered" disabled="true"></vn-check></vn-td>
<vn-td shrink>
<vn-icon
icon="flight_takeoff"
translate-attr="{title: 'Delivered'}"
ng-class="{active: travel.isDelivered}">
</vn-icon>
</vn-td>
<vn-td expand>{{::travel.warehouseInName}}</vn-td>
<vn-td center shrink-date>
<span class="chip {{$ctrl.compareDate(travel.landed)}}">
{{::travel.landed | date:'dd/MM/yyyy'}}
</span>
</vn-td>
<vn-td center><vn-check ng-model="travel.isReceived" disabled="true"></vn-check></vn-td>
<vn-td shrink>
<vn-icon
icon="flight_land"
translate-attr="{title: 'Received'}"
ng-class="{active: travel.isReceived}">
</vn-icon>
</vn-td>
<vn-td shrink>{{::travel.totalEntries}}</vn-td>
<vn-td shrink>
<vn-horizontal class="buttons">
<vn-icon-button
@ -49,7 +70,7 @@
vn-tooltip="Clone"
icon="icon-clone">
</vn-icon-button>
<vn-icon-button
<vn-icon-button
vn-anchor="::{state: 'entry.create', params: {travelFk: travel.id}}"
vn-tooltip="Add entry"
icon="icon-ticket">
@ -78,38 +99,9 @@
fixed-bottom-right>
<vn-float-button icon="add"></vn-float-button>
</a>
<vn-confirm
<vn-confirm
vn-id="clone"
on-accept="$ctrl.onCloneAccept($data)"
question="Do you want to clone this travel?"
message="All it's properties will be copied">
</vn-confirm>
<vn-contextmenu vn-id="contextmenu" targets="['vn-data-viewer']" model="model"
expr-builder="$ctrl.exprBuilder(param, value)">
<slot-menu>
<vn-item translate
ng-if="contextmenu.isFilterAllowed()"
ng-click="contextmenu.filterBySelection()">
Filter by selection
</vn-item>
<vn-item translate
ng-if="contextmenu.isFilterAllowed()"
ng-click="contextmenu.excludeSelection()">
Exclude selection
</vn-item>
<vn-item translate
ng-if="contextmenu.isFilterAllowed()"
ng-click="contextmenu.removeFilter()">
Remove filter
</vn-item>
<vn-item translate
ng-click="contextmenu.removeAllFilters()" >
Remove all filters
</vn-item>
<vn-item translate
ng-if="contextmenu.isActionAllowed()"
ng-click="contextmenu.copyValue()">
Copy value
</vn-item>
</slot-menu>
</vn-contextmenu>

View File

@ -1,5 +1,6 @@
import ngModule from '../module';
import Section from 'salix/components/section';
import './style.scss';
export default class Controller extends Section {
preview(travel) {
@ -30,37 +31,6 @@ export default class Controller extends Section {
if (timeDifference == 0) return 'warning';
if (timeDifference < 0) return 'success';
}
exprBuilder(param, value) {
switch (param) {
case 'search':
return /^\d+$/.test(value)
? {'t.id': value}
: {'t.ref': {like: `%${value}%`}};
case 'ref':
return {'t.ref': {like: `%${value}%`}};
case 'shipped':
return {'t.shipped': {between: this.dateRange(value)}};
case 'landed':
return {'t.landed': {between: this.dateRange(value)}};
case 'id':
case 'agencyModeFk':
case 'warehouseOutFk':
case 'warehouseInFk':
case 'totalEntries':
param = `t.${param}`;
return {[param]: value};
}
}
dateRange(value) {
const minHour = new Date(value);
minHour.setHours(0, 0, 0, 0);
const maxHour = new Date(value);
maxHour.setHours(23, 59, 59, 59);
return [minHour, maxHour];
}
}
ngModule.vnComponent('vnTravelIndex', {

View File

@ -0,0 +1,11 @@
@import "variables";
vn-travel-index {
vn-icon {
color: $color-font-secondary
}
vn-icon.active {
color: $color-success
}
}

View File

@ -1,7 +1,7 @@
#Ordenar alfabeticamente
Reference: Referencia
Warehouse Out: Almacén salida
Warehouse In: Almacén llegada
Warehouse Out: Alm salida
Warehouse In: Alm llegada
Shipped from: Salida desde
Shipped to: Salida hasta
Landed from: Llegada desde
@ -10,12 +10,12 @@ Shipped: F. salida
Landed: F. llegada
Delivered: Enviado
Received: Recibido
Travel id: Id envío
Search travels by id: Buscar envíos por identificador
Travel id: Id
Search travels by id: Buscar envíos por identificador o referencia
New travel: Nuevo envío
travel: envío
# Sections
Travels: Envíos
Log: Historial
Thermographs: Termógrafos
Thermographs: Termógrafos

View File

@ -1,20 +1,6 @@
<vn-crud-model
vn-id="model"
url="Travels/filter"
limit="20"
order="shipped DESC, landed DESC">
</vn-crud-model>
<vn-portal slot="topbar">
<vn-searchbar
vn-focus
panel="vn-travel-search-panel"
info="Search travels by id"
model="model"
fetch-params="$ctrl.fetchParams($params)"
suggested-filter="$ctrl.filterParams">
</vn-searchbar>
</vn-portal>
<vn-portal slot="menu">
<vn-left-menu></vn-left-menu>
</vn-portal>
<ui-view></ui-view>
<ui-view></ui-view>

View File

@ -4,28 +4,6 @@ import ModuleMain from 'salix/components/module-main';
export default class Travel extends ModuleMain {
constructor() {
super();
this.filterParams = {
scopeDays: 1
};
}
fetchParams($params) {
if (!Object.entries($params).length)
$params.scopeDays = 1;
if (typeof $params.scopeDays === 'number') {
const shippedFrom = Date.vnNew();
shippedFrom.setHours(0, 0, 0, 0);
const shippedTo = new Date(shippedFrom.getTime());
shippedTo.setDate(shippedTo.getDate() + $params.scopeDays);
shippedTo.setHours(23, 59, 59, 999);
Object.assign($params, {shippedFrom, shippedTo});
}
return $params;
}
}

View File

@ -1,49 +0,0 @@
import './index.js';
describe('Travel Component vnTravel', () => {
let controller;
beforeEach(ngModule('travel'));
beforeEach(inject($componentController => {
let $element = angular.element(`<div></div>`);
controller = $componentController('vnTravel', {$element});
}));
describe('fetchParams()', () => {
it('should return a range of dates with passed scope days', () => {
let params = controller.fetchParams({
scopeDays: 2
});
const shippedFrom = Date.vnNew();
shippedFrom.setHours(0, 0, 0, 0);
const shippedTo = new Date(shippedFrom.getTime());
shippedTo.setDate(shippedTo.getDate() + params.scopeDays);
shippedTo.setHours(23, 59, 59, 999);
const expectedParams = {
shippedFrom,
scopeDays: params.scopeDays,
shippedTo
};
expect(params).toEqual(expectedParams);
});
it('should return default value for scope days', () => {
let params = controller.fetchParams({
scopeDays: 1
});
expect(params.scopeDays).toEqual(1);
});
it('should return the given scope days', () => {
let params = controller.fetchParams({
scopeDays: 2
});
expect(params.scopeDays).toEqual(2);
});
});
});

View File

@ -1,109 +1,146 @@
<div class="search-panel">
<form ng-submit="$ctrl.onSearch()" id="manifold-form">
<vn-horizontal class="vn-px-lg vn-pt-lg">
<vn-textfield
vn-one
label="General search"
ng-model="filter.search"
info="Search travels by id"
vn-focus>
</vn-textfield>
</vn-horizontal>
<vn-horizontal class="vn-px-lg">
<vn-textfield
vn-one
label="Reference"
ng-model="filter.ref">
</vn-textfield>
<vn-textfield
vn-one
label="Total entries"
ng-model="filter.totalEntries">
</vn-textfield>
</vn-horizontal>
<vn-horizontal class="vn-px-lg">
<vn-textfield
vn-one
label="Travel id"
ng-model="filter.id">
</vn-textfield>
<vn-autocomplete vn-one
label="Agency"
ng-model="filter.agencyModeFk"
url="AgencyModes"
show-field="name"
value-field="id">
</vn-autocomplete>
</vn-horizontal>
<section class="vn-px-md">
<vn-horizontal class="manifold-panel vn-pa-md">
<vn-date-picker
vn-one
label="Shipped from"
ng-model="filter.shippedFrom"
on-change="$ctrl.shippedFrom = value">
</vn-date-picker>
<vn-date-picker
vn-one
label="Shipped to"
ng-model="filter.shippedTo"
on-change="$ctrl.shippedTo = value">
</vn-date-picker>
<vn-none class="or vn-px-md" translate>Or</vn-none>
<vn-input-number
vn-one
min="0"
step="1"
label="Days onward"
ng-model="filter.scopeDays"
on-change="$ctrl.scopeDays = value"
display-controls="true">
</vn-input-number>
<vn-icon color-marginal
icon="info"
vn-tooltip="Cannot choose a range of dates and days onward at the same time">
</vn-icon>
</vn-horizontal>
</section>
<vn-horizontal class="vn-px-lg">
<vn-date-picker
vn-one
label="Landed from"
ng-model="filter.landedFrom">
</vn-date-picker>
<vn-date-picker
vn-one
label="Landed to"
ng-model="filter.landedTo">
</vn-date-picker>
</vn-horizontal>
<vn-horizontal class="vn-px-lg">
<vn-autocomplete vn-one
label="Warehouse Out"
ng-model="filter.warehouseOutFk"
url="Warehouses"
show-field="name"
value-field="id">
</vn-autocomplete>
<vn-autocomplete vn-one
label="Warehouse In"
ng-model="filter.warehouseInFk"
url="Warehouses"
show-field="name"
value-field="id">
</vn-autocomplete>
</vn-horizontal>
<vn-horizontal class="vn-px-lg">
<vn-autocomplete vn-one
label="Continent Out"
ng-model="filter.continent"
url="Continents"
show-field="name"
value-field="code">
</vn-autocomplete>
</vn-horizontal>
<vn-horizontal class="vn-px-lg vn-pb-lg vn-mt-lg">
<vn-submit label="Search"></vn-submit>
</vn-horizontal>
</form>
</div>
<vn-side-menu side="right">
<vn-horizontal class="input">
<vn-textfield
label="General search"
info="Search travels by id"
ng-model="$ctrl.search"
ng-keydown="$ctrl.onKeyPress($event, 'search')">
</vn-textfield>
</vn-horizontal>
<vn-horizontal class="input horizontal">
<vn-autocomplete
vn-id="agency"
label="Agency"
ng-model="$ctrl.filter.agencyModeFk"
data="$ctrl.agencyModes"
show-field="name"
value-field="id"
on-change="$ctrl.applyFilters()">
</vn-autocomplete>
</vn-horizontal>
<vn-horizontal class="input horizontal">
<vn-autocomplete
vn-id="warehouseOut"
label="Warehouse Out"
ng-model="$ctrl.filter.warehouseOutFk"
data="$ctrl.warehouses"
show-field="name"
value-field="id"
on-change="$ctrl.applyFilters()">
</vn-autocomplete>
<vn-autocomplete
vn-id="warehouseIn"
label="Warehouse In"
ng-model="$ctrl.filter.warehouseInFk"
data="$ctrl.warehouses"
show-field="name"
value-field="id"
on-change="$ctrl.applyFilters()">
</vn-autocomplete>
</vn-horizontal>
<vn-horizontal class="input horizontal">
<vn-input-number
min="0"
step="1"
label="Days onward"
ng-model="$ctrl.filter.scopeDays"
on-change="$ctrl.applyFilters()"
display-controls="true"
info="Cannot choose a range of dates and days onward at the same time">
</vn-input-number>
</vn-horizontal>
<vn-horizontal class="input horizontal">
<vn-date-picker
label="Landed from"
ng-model="$ctrl.filter.landedFrom"
on-change="$ctrl.applyFilters()">
</vn-date-picker>
<vn-date-picker
label="Landed to"
ng-model="$ctrl.filter.landedTo"
on-change="$ctrl.applyFilters()">
</vn-date-picker>
</vn-horizontal>
<vn-horizontal class="input horizontal">
<vn-autocomplete
vn-id="continent"
label="Continent Out"
ng-model="$ctrl.filter.continent"
data="$ctrl.continents"
show-field="name"
value-field="code"
on-change="$ctrl.applyFilters()">
</vn-autocomplete>
<vn-input-number
min="0"
label="Total entries"
ng-model="$ctrl.totalEntries"
ng-keydown="$ctrl.onKeyPress($event, 'totalEntries')">
</vn-input-number>
</vn-horizontal>
<div class="chips">
<vn-chip
ng-if="$ctrl.filter.search"
removable="true"
on-remove="$ctrl.removeParamFilter('search')"
class="colored">
<span>Id/{{$ctrl.$t('Reference')}}: {{$ctrl.filter.search}}</span>
</vn-chip>
<vn-chip
ng-if="agency.selection"
removable="true"
on-remove="$ctrl.removeParamFilter('agencyModeFk')"
class="colored">
<span>{{$ctrl.$t('Agency')}}: {{agency.selection.name}}</span>
</vn-chip>
<vn-chip
ng-if="warehouseOut.selection"
removable="true"
on-remove="$ctrl.removeParamFilter('warehouseOutFk')"
class="colored">
<span>{{$ctrl.$t('Warehouse Out')}}: {{warehouseOut.selection.name}}</span>
</vn-chip>
<vn-chip
ng-if="warehouseIn.selection"
removable="true"
on-remove="$ctrl.removeParamFilter('warehouseInFk')"
class="colored">
<span>{{$ctrl.$t('Warehouse In')}}: {{warehouseIn.selection.name}}</span>
</vn-chip>
<vn-chip
ng-if="$ctrl.filter.scopeDays"
removable="true"
on-remove="$ctrl.removeParamFilter('scopeDays')"
class="colored">
<span>{{$ctrl.$t('Days onward')}}: {{$ctrl.filter.scopeDays}}</span>
</vn-chip>
<vn-chip
ng-if="$ctrl.filter.landedFrom"
removable="true"
on-remove="$ctrl.removeParamFilter('landedFrom')"
class="colored">
<span>{{$ctrl.$t('Landed from')}}: {{$ctrl.filter.landedFrom | date:'dd/MM/yyyy'}}</span>
</vn-chip>
<vn-chip
ng-if="$ctrl.filter.landedTo"
removable="true"
on-remove="$ctrl.removeParamFilter('landedTo')"
class="colored">
<span>{{$ctrl.$t('Landed to')}}: {{$ctrl.filter.landedTo | date:'dd/MM/yyyy'}}</span>
</vn-chip>
<vn-chip
ng-if="continent.selection"
removable="true"
on-remove="$ctrl.removeParamFilter('continent')"
class="colored">
<span>{{$ctrl.$t('Continent Out')}}: {{continent.selection.name}}</span>
</vn-chip>
<vn-chip
ng-if="$ctrl.filter.totalEntries"
removable="true"
on-remove="$ctrl.removeParamFilter('totalEntries')"
class="colored">
<span>{{$ctrl.$t('Total entries')}}: {{$ctrl.filter.totalEntries}}</span>
</vn-chip>
</div>
</vn-side-menu>

View File

@ -1,43 +1,69 @@
import ngModule from '../module';
import SearchPanel from 'core/components/searchbar/search-panel';
import './style.scss';
class Controller extends SearchPanel {
constructor($, $element) {
super($, $element);
this.filter = this.$.filter;
this.initFilter();
this.fetchData();
}
get shippedFrom() {
return this._shippedFrom;
$onChanges() {
if (this.model)
this.applyFilters();
}
set shippedFrom(value) {
this._shippedFrom = value;
this.filter.scopeDays = null;
fetchData() {
this.$http.get('AgencyModes').then(res => {
this.agencyModes = res.data;
});
this.$http.get('Warehouses').then(res => {
this.warehouses = res.data;
});
this.$http.get('Continents').then(res => {
this.continents = res.data;
});
}
get shippedTo() {
return this._shippedTo;
initFilter() {
this.filter = {};
if (this.$params.q) {
this.filter = JSON.parse(this.$params.q);
this.search = this.filter.search;
this.totalEntries = this.filter.totalEntries;
}
if (!this.filter.scopeDays) this.filter.scopeDays = 7;
}
set shippedTo(value) {
this._shippedTo = value;
this.filter.scopeDays = null;
applyFilters(param) {
this.model.applyFilter({}, this.filter)
.then(() => {
if (param && this.model._orgData.length === 1)
this.$state.go('travel.card.summary', {id: this.model._orgData[0].id});
else
this.$state.go(this.$state.current.name, {q: JSON.stringify(this.filter)}, {location: 'replace'});
});
}
get scopeDays() {
return this._scopeDays;
removeParamFilter(param) {
if (this[param]) delete this[param];
delete this.filter[param];
this.applyFilters();
}
set scopeDays(value) {
this._scopeDays = value;
this.filter.shippedFrom = null;
this.filter.shippedTo = null;
onKeyPress($event, param) {
if ($event.key === 'Enter') {
this.filter[param] = this[param];
this.applyFilters(param === 'search');
}
}
}
ngModule.vnComponent('vnTravelSearchPanel', {
template: require('./index.html'),
controller: Controller
controller: Controller,
bindings: {
model: '<'
}
});

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