2510-client-address-create-test #418

Merged
jgallego merged 11 commits from 2510-client-address-create-test into dev 2020-11-02 07:53:55 +00:00
46 changed files with 7033 additions and 1457 deletions
Showing only changes of commit ef7a886d86 - Show all commits

View File

@ -110,13 +110,15 @@ BEGIN
SELECT `name` FROM `user` WHERE id = OLD.id; SELECT `name` FROM `user` WHERE id = OLD.id;
END$$ END$$
CREATE TRIGGER role_beforeInsert DROP TRIGGER IF EXISTS account.role_beforeInsert$$
CREATE DEFINER=`root`@`%` TRIGGER role_beforeInsert
BEFORE INSERT ON `role` FOR EACH ROW BEFORE INSERT ON `role` FOR EACH ROW
BEGIN BEGIN
CALL role_checkName(NEW.`name`); CALL role_checkName(NEW.`name`);
END$$ END
CREATE TRIGGER role_beforeUpdate DROP TRIGGER IF EXISTS account.role_beforeUpdate$$
CREATE DEFINER=`root`@`%` TRIGGER role_beforeUpdate
BEFORE UPDATE ON `role` FOR EACH ROW BEFORE UPDATE ON `role` FOR EACH ROW
BEGIN BEGIN
IF !(NEW.`name` <=> OLD.`name`) THEN IF !(NEW.`name` <=> OLD.`name`) THEN

View File

@ -1,7 +1,7 @@
DROP PROCEDURE IF EXISTS account.role_checkName; DROP PROCEDURE IF EXISTS account.role_checkName;
DELIMITER $$ DELIMITER $$
CREATE PROCEDURE account.role_checkName(vRoleName VARCHAR(255)) CREATE DEFINER=`root`@`%` PROCEDURE account.role_checkName(vRoleName VARCHAR(255))
BEGIN BEGIN
/** /**
* Checks that role name meets the necessary syntax requirements, otherwise it * Checks that role name meets the necessary syntax requirements, otherwise it

View File

@ -0,0 +1,3 @@
UPDATE `salix`.`ACL` SET `principalId` = 'deliveryBoss' WHERE (`id` = '194');
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Town', '*', 'WRITE', 'ALLOW', 'ROLE', 'deliveryBoss');
INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Province', '*', 'WRITE', 'ALLOW', 'ROLE', 'deliveryBoss');

File diff suppressed because one or more lines are too long

View File

@ -400,12 +400,13 @@ INSERT INTO `vn`.`clientObservation`(`id`, `clientFk`, `workerFk`, `text`, `crea
(9, 109, 18, 'HULK SMASH! ...', CURDATE()), (9, 109, 18, 'HULK SMASH! ...', CURDATE()),
(10, 110, 18, 'They say everyone is born a hero. But if you let it, life will push you over the line until you are the villain.', CURDATE()); (10, 110, 18, 'They say everyone is born a hero. But if you let it, life will push you over the line until you are the villain.', CURDATE());
INSERT INTO `vn`.`observationType`(`id`,`description`) INSERT INTO `vn`.`observationType`(`id`,`description`, `code`)
VALUES VALUES
(1,'observation one'), (1, 'observation one', 'observation one'),
(2,'observation two'), (2, 'observation two', 'observation two'),
(3,'observation three'), (3, 'observation three', 'observation three'),
(4,'comercial'); (4, 'comercial', 'salesPerson'),
(5, 'delivery', 'delivery');
INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`)
VALUES VALUES
@ -2116,4 +2117,18 @@ INSERT INTO `vn`.`tabletDepartment`(`tabletFk`, `departmentFk`)
(1, 23), (1, 23),
(2, 1); (2, 1);
INSERT INTO `vn`.`campaign`(`code`, `dated`)
VALUES
('valentinesDay', CONCAT(YEAR(CURDATE()), '-02-14')),
('valentinesDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -1 YEAR)), '-02-14')),
('valentinesDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -2 YEAR)), '-02-14')),
('valentinesDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -3 YEAR)), '-02-14')),
('mothersDay', CONCAT(YEAR(CURDATE()), '-05-05')),
('mothersDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -1 YEAR)), '-05-05')),
('mothersDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -2 YEAR)), '-05-05')),
('mothersDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -3 YEAR)), '-05-05')),
('allSaints', CONCAT(YEAR(CURDATE()), '-11-01')),
('allSaints', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -1 YEAR)), '-11-01')),
('allSaints', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -2 YEAR)), '-11-01')),
('allSaints', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -3 YEAR)), '-11-01'));

File diff suppressed because it is too large Load Diff

View File

@ -82,3 +82,10 @@ TABLES=(
workcenter workcenter
) )
dump_tables ${TABLES[@]} dump_tables ${TABLES[@]}
TABLES=(
sage
TiposIva
TiposTransacciones
)
dump_tables ${TABLES[@]}

View File

@ -9,6 +9,7 @@ SCHEMAS=(
nst nst
pbx pbx
postgresql postgresql
sage
salix salix
stock stock
util util

View File

@ -42,13 +42,24 @@ export default {
taxNumber: 'vn-client-create vn-textfield[ng-model="$ctrl.client.fi"]', taxNumber: 'vn-client-create vn-textfield[ng-model="$ctrl.client.fi"]',
socialName: 'vn-client-create vn-textfield[ng-model="$ctrl.client.socialName"]', socialName: 'vn-client-create vn-textfield[ng-model="$ctrl.client.socialName"]',
street: 'vn-client-create vn-textfield[ng-model="$ctrl.client.street"]', street: 'vn-client-create vn-textfield[ng-model="$ctrl.client.street"]',
addPostCode: 'vn-client-create vn-datalist[ng-model="$ctrl.client.postcode"] vn-icon-button[icon="add_circle"]',
addProvince: 'vn-autocomplete[ng-model="$ctrl.location.provinceFk"] vn-icon-button[icon="add_circle"]',
addCity: 'vn-autocomplete[ng-model="$ctrl.location.townFk"] vn-icon-button[icon="add_circle"]',
newProvinceName: 'vn-textfield[ng-model="$ctrl.province.name"]',
newCityName: 'vn-textfield[ng-model="$ctrl.city.name"]',
newCityProvince: 'vn-autocomplete[ng-model="$ctrl.city.provinceFk"]',
newPostcode: 'vn-textfield[ng-model="$ctrl.location.code"]',
postcode: 'vn-client-create vn-datalist[ng-model="$ctrl.client.postcode"]', postcode: 'vn-client-create vn-datalist[ng-model="$ctrl.client.postcode"]',
city: 'vn-client-create vn-datalist[ng-model="$ctrl.client.city"]', city: 'vn-client-create vn-datalist[ng-model="$ctrl.client.city"]',
province: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.provinceFk"]', province: 'vn-autocomplete[ng-model="$ctrl.client.provinceFk"]',
country: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.countryFk"]', country: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.countryFk"]',
dialogCountry: 'vn-autocomplete[ng-model="$ctrl.province.countryFk"]',
userName: 'vn-client-create vn-textfield[ng-model="$ctrl.client.userName"]', userName: 'vn-client-create vn-textfield[ng-model="$ctrl.client.userName"]',
email: 'vn-client-create vn-textfield[ng-model="$ctrl.client.email"]', email: 'vn-client-create vn-textfield[ng-model="$ctrl.client.email"]',
salesPerson: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.salesPersonFk"]', salesPerson: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.salesPersonFk"]',
saveNewProvicenButton: '#saveProvince',
saveNewCityButton: '#saveCity',
saveNewPoscode: '#savePostcode',
createButton: 'vn-client-create button[type=submit]' createButton: 'vn-client-create button[type=submit]'
}, },
clientDescriptor: { clientDescriptor: {

View File

@ -8,7 +8,7 @@ describe('Client create path', () => {
beforeAll(async() => { beforeAll(async() => {
browser = await getBrowser(); browser = await getBrowser();
page = browser.page; page = browser.page;
await page.loginAndModule('employee', 'client'); await page.loginAndModule(' deliveryBoss', 'client');
}); });
afterAll(async() => { afterAll(async() => {
@ -45,14 +45,40 @@ describe('Client create path', () => {
expect(message.text).toBe('Some fields are invalid'); expect(message.text).toBe('Some fields are invalid');
}); });
it(`should create a new province`, async() => {
await page.waitToClick(selectors.createClientView.addPostCode);
await page.waitToClick(selectors.createClientView.addProvince);
await page.write(selectors.createClientView.newProvinceName, 'Massachusetts');
await page.autocompleteSearch(selectors.createClientView.dialogCountry, 'España');
await page.waitToClick(selectors.createClientView.saveNewProvicenButton);
const message = await page.waitForSnackbar();
expect(message.text).toBe('The province has been created');
});
it(`should create a new city`, async() => {
await page.waitToClick(selectors.createClientView.addCity);
await page.write(selectors.createClientView.newCityName, 'Boston');
await page.autocompleteSearch(selectors.createClientView.newCityProvince, 'Massachusetts');
await page.waitToClick(selectors.createClientView.saveNewCityButton);
const message = await page.waitForSnackbar();
expect(message.text).toBe('The city has been created');
});
it(`should create a new post code`, async() => {
await page.write(selectors.createClientView.newPostcode, '61616');
await page.waitToClick(selectors.createClientView.saveNewPoscode);
const message = await page.waitForSnackbar();
expect(message.text).toBe('The postcode has been created. You can save the data now');
});
it(`should attempt to create a new user with all it's data but wrong email`, async() => { it(`should attempt to create a new user with all it's data but wrong email`, async() => {
await page.write(selectors.createClientView.name, 'Carol Danvers'); await page.write(selectors.createClientView.name, 'Carol Danvers');
await page.write(selectors.createClientView.socialName, 'AVG tax'); await page.write(selectors.createClientView.socialName, 'AVG tax');
await page.write(selectors.createClientView.street, 'Many places'); await page.write(selectors.createClientView.street, 'Many places');
await page.autocompleteSearch(selectors.createClientView.country, 'España');
await page.autocompleteSearch(selectors.createClientView.province, 'Province one');
await page.write(selectors.createClientView.city, 'Valencia');
await page.write(selectors.createClientView.postcode, '46000');
await page.clearInput(selectors.createClientView.email); await page.clearInput(selectors.createClientView.email);
await page.write(selectors.createClientView.email, 'incorrect email format'); await page.write(selectors.createClientView.email, 'incorrect email format');
await page.waitToClick(selectors.createClientView.createButton); await page.waitToClick(selectors.createClientView.createButton);
@ -82,14 +108,14 @@ describe('Client create path', () => {
const clientCountry = await page const clientCountry = await page
.waitToGetProperty(selectors.createClientView.country, 'value'); .waitToGetProperty(selectors.createClientView.country, 'value');
expect(clientCity).toEqual('Valencia'); expect(clientCity).toEqual('Boston');
expect(clientProvince).toContain('Province one'); expect(clientProvince).toContain('Massachusetts');
expect(clientCountry).toEqual('España'); expect(clientCountry).toEqual('España');
}); });
it(`should create a new user with all correct data`, async() => { it(`should create a new user with all correct data`, async() => {
await page.clearInput(selectors.createClientView.postcode); await page.clearInput(selectors.createClientView.postcode);
await page.write(selectors.createClientView.postcode, '46000'); await page.write(selectors.createClientView.postcode, '61616');
await page.waitToClick(selectors.createClientView.createButton); await page.waitToClick(selectors.createClientView.createButton);
const message = await page.waitForSnackbar(); const message = await page.waitForSnackbar();

View File

@ -24,7 +24,7 @@ describe('Worker calendar path', () => {
expect(result).toContain(' 5 '); expect(result).toContain(' 5 ');
}); });
it('should set two days as holidays on the calendar', async() => { it('should set two days as holidays on the calendar and check the total holidays increased by 1.5', async() => {
await page.waitToClick(selectors.workerCalendar.holidays); await page.waitToClick(selectors.workerCalendar.holidays);
await page.waitFor(reasonableTimeBetweenClicks); await page.waitFor(reasonableTimeBetweenClicks);
await page.waitToClick(selectors.workerCalendar.januaryThirtyFirst); await page.waitToClick(selectors.workerCalendar.januaryThirtyFirst);
@ -51,9 +51,7 @@ describe('Worker calendar path', () => {
await page.waitFor(reasonableTimeBetweenClicks); await page.waitFor(reasonableTimeBetweenClicks);
await page.waitToClick(selectors.workerCalendar.mayEighth); await page.waitToClick(selectors.workerCalendar.mayEighth);
await page.waitFor(reasonableTimeBetweenClicks); await page.waitFor(reasonableTimeBetweenClicks);
});
it('should check the total holidays increased by 1.5', async() => {
const result = await page.waitToGetProperty(selectors.workerCalendar.totalHolidaysUsed, 'innerText'); const result = await page.waitToGetProperty(selectors.workerCalendar.totalHolidaysUsed, 'innerText');
expect(result).toContain(' 6.5 '); expect(result).toContain(' 6.5 ');

View File

@ -26,7 +26,9 @@ describe('Entry create path', () => {
await page.autocompleteSearch(selectors.entryIndex.newEntryCompany, 'ORN'); await page.autocompleteSearch(selectors.entryIndex.newEntryCompany, 'ORN');
await page.waitToClick(selectors.entryIndex.saveNewEntry); await page.waitToClick(selectors.entryIndex.saveNewEntry);
await page.waitFor(500); await page.waitForNavigation({
waitUntil: 'load',
});
await page.waitForState('entry.card.basicData'); await page.waitForState('entry.card.basicData');
}); });
}); });

View File

@ -57,12 +57,12 @@
"The postcode doesn't exist. Please enter a correct one": "The postcode doesn't exist. Please enter a correct one", "The postcode doesn't exist. Please enter a correct one": "The postcode doesn't exist. Please enter a correct one",
"Can't create stowaway for this ticket": "Can't create stowaway for this ticket", "Can't create stowaway for this ticket": "Can't create stowaway for this ticket",
"Swift / BIC can't be empty": "Swift / BIC can't be empty", "Swift / BIC can't be empty": "Swift / BIC can't be empty",
"MESSAGE_BOUGHT_UNITS": "Bought {{quantity}} units of {{concept}} (#{{itemId}}) for the ticket id [#{{ticketId}}]({{{url}}})", "MESSAGE_BOUGHT_UNITS": "Bought {{quantity}} units of {{concept}} ({{itemId}}) for the ticket id [{{ticketId}}]({{{url}}})",
"MESSAGE_INSURANCE_CHANGE": "I have changed the insurence credit of client [{{clientName}} (#{{clientId}})]({{{url}}}) to *{{credit}} €*", "MESSAGE_INSURANCE_CHANGE": "I have changed the insurence credit of client [{{clientName}} ({{clientId}})]({{{url}}}) to *{{credit}} €*",
"MESSAGE_CHANGED_PAYMETHOD": "I have changed the pay method for client [{{clientName}} (#{{clientId}})]({{{url}}})", "MESSAGE_CHANGED_PAYMETHOD": "I have changed the pay method for client [{{clientName}} ({{clientId}})]({{{url}}})",
"Sent units from ticket": "I sent *{{quantity}}* units of [{{concept}} (#{{itemId}})]({{{itemUrl}}}) to *\"{{nickname}}\"* coming from ticket id [#{{ticketId}}]({{{ticketUrl}}})", "Sent units from ticket": "I sent *{{quantity}}* units of [{{concept}} ({{itemId}})]({{{itemUrl}}}) to *\"{{nickname}}\"* coming from ticket id [{{ticketId}}]({{{ticketUrl}}})",
"Claim will be picked": "The product from the claim (#{{claimId}})]({{{claimUrl}}}) from the client *{{clientName}}* will be picked", "Claim will be picked": "The product from the claim ({{claimId}})]({{{claimUrl}}}) from the client *{{clientName}}* will be picked",
"This ticket is not an stowaway anymore": "The ticket id [#{{ticketId}}]({{{ticketUrl}}}) is not an stowaway anymore", "This ticket is not an stowaway anymore": "The ticket id [{{ticketId}}]({{{ticketUrl}}}) is not an stowaway anymore",
"Customs agent is required for a non UEE member": "Customs agent is required for a non UEE member", "Customs agent is required for a non UEE member": "Customs agent is required for a non UEE member",
"Incoterms is required for a non UEE member": "Incoterms is required for a non UEE member", "Incoterms is required for a non UEE member": "Incoterms is required for a non UEE member",
"Client checked as validated despite of duplication": "Client checked as validated despite of duplication from client id {{clientId}}", "Client checked as validated despite of duplication": "Client checked as validated despite of duplication from client id {{clientId}}",
@ -70,6 +70,7 @@
"NOT_ZONE_WITH_THIS_PARAMETERS": "There's no zone available for this day", "NOT_ZONE_WITH_THIS_PARAMETERS": "There's no zone available for this day",
"Created absence": "The worker <strong>{{author}}</strong> has added an absence of type '{{absenceType}}' to <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> for day {{dated}}.", "Created absence": "The worker <strong>{{author}}</strong> has added an absence of type '{{absenceType}}' to <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> for day {{dated}}.",
"Deleted absence": "The worker <strong>{{author}}</strong> has deleted an absence of type '{{absenceType}}' to <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> for day {{dated}}.", "Deleted absence": "The worker <strong>{{author}}</strong> has deleted an absence of type '{{absenceType}}' to <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> for day {{dated}}.",
"I have deleted the ticket id": "I have deleted the ticket id [#{{id}}]({{{url}}})", "I have deleted the ticket id": "I have deleted the ticket id [{{id}}]({{{url}}})",
"I have restored the ticket id": "I have restored the ticket id [#{{id}}]({{{url}}})" "I have restored the ticket id": "I have restored the ticket id [{{id}}]({{{url}}})",
"Changed this data from the ticket": "I have changed the data from the ticket [{{ticketId}}]({{{ticketUrl}}}): ```{{{changes}}}```"
} }

View File

@ -121,12 +121,12 @@
"Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío",
"Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios",
"Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios", "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios",
"MESSAGE_BOUGHT_UNITS": "Se ha comprado {{quantity}} unidades de {{concept}} (#{{itemId}}) para el ticket id [#{{ticketId}}]({{{url}}})", "MESSAGE_BOUGHT_UNITS": "Se ha comprado {{quantity}} unidades de {{concept}} (#{{itemId}}) para el ticket id [{{ticketId}}]({{{url}}})",
"MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} (#{{clientId}})]({{{url}}}) a *{{credit}} €*", "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} (#{{clientId}})]({{{url}}}) a *{{credit}} €*",
"MESSAGE_CHANGED_PAYMETHOD": "He cambiado la forma de pago del cliente [{{clientName}} (#{{clientId}})]({{{url}}})", "MESSAGE_CHANGED_PAYMETHOD": "He cambiado la forma de pago del cliente [{{clientName}} (#{{clientId}})]({{{url}}})",
"Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} (#{{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [#{{ticketId}}]({{{ticketUrl}}})", "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} (#{{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})",
"Claim will be picked": "Se recogerá el género de la reclamación (#{{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", "Claim will be picked": "Se recogerá el género de la reclamación (#{{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*",
"This ticket is not an stowaway anymore": "El ticket id [#{{ticketId}}]({{{ticketUrl}}}) ha dejado de ser un polizón", "This ticket is not an stowaway anymore": "El ticket id [{{ticketId}}]({{{ticketUrl}}}) ha dejado de ser un polizón",
"Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}",
"ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto",
"Distance must be lesser than 1000": "La distancia debe ser inferior a 1000", "Distance must be lesser than 1000": "La distancia debe ser inferior a 1000",
@ -146,7 +146,8 @@
"Absence change notification on the labour calendar": "Notificacion de cambio de ausencia en el calendario laboral", "Absence change notification on the labour calendar": "Notificacion de cambio de ausencia en el calendario laboral",
"Created absence": "El empleado <strong>{{author}}</strong> ha añadido una ausencia de tipo '{{absenceType}}' a <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> para el día {{dated}}.", "Created absence": "El empleado <strong>{{author}}</strong> ha añadido una ausencia de tipo '{{absenceType}}' a <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> para el día {{dated}}.",
"Deleted absence": "El empleado <strong>{{author}}</strong> ha eliminado una ausencia de tipo '{{absenceType}}' a <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> del día {{dated}}.", "Deleted absence": "El empleado <strong>{{author}}</strong> ha eliminado una ausencia de tipo '{{absenceType}}' a <a href='{{{workerUrl}}}'><strong>{{employee}}</strong></a> del día {{dated}}.",
"I have deleted the ticket id": "He eliminado el ticket id [#{{id}}]({{{url}}})", "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})",
"I have restored the ticket id": "He restaurado el ticket id [#{{id}}]({{{url}}})", "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})",
"You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación" "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación",
"Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): ```{{{changes}}}```"
} }

View File

@ -7,7 +7,7 @@ describe('Client activeWorkersWithRole', () => {
let isSalesPerson = await app.models.Account.hasRole(result[0].id, 'salesPerson'); let isSalesPerson = await app.models.Account.hasRole(result[0].id, 'salesPerson');
expect(result.length).toEqual(16); expect(result.length).toEqual(17);
expect(isSalesPerson).toBeTruthy(); expect(isSalesPerson).toBeTruthy();
}); });

View File

@ -104,7 +104,7 @@ describe('Address createAddress', () => {
address = await app.models.Client.createAddress(ctx, clientFk); address = await app.models.Client.createAddress(ctx, clientFk);
expect(address.__data).toEqual(jasmine.objectContaining(ctx.args)); expect(address).toEqual(jasmine.objectContaining(ctx.args));
// restores // restores
const client = await app.models.Client.findById(clientFk); const client = await app.models.Client.findById(clientFk);
await client.updateAttributes({defaultAddressFk: 1}); await client.updateAttributes({defaultAddressFk: 1});

View File

@ -6,7 +6,7 @@ describe('Client listWorkers', () => {
.then(result => { .then(result => {
let amountOfEmployees = Object.keys(result).length; let amountOfEmployees = Object.keys(result).length;
expect(amountOfEmployees).toEqual(51); expect(amountOfEmployees).toEqual(53);
done(); done();
}) })
.catch(done.fail); .catch(done.fail);

View File

@ -15,6 +15,10 @@
"description": { "description": {
"type": "String", "type": "String",
"required": true "required": true
},
"code": {
"type": "String",
"required": true
} }
}, },
"acls": [ "acls": [

View File

@ -153,9 +153,9 @@
</form> </form>
<!-- New postcode dialog --> <!-- New postcode dialog -->
<vn-client-postcode vn-id="postcode" <vn-geo-postcode vn-id="postcode"
on-response="$ctrl.onResponse($response)"> on-response="$ctrl.onResponse($response)">
</vn-client-postcode> </vn-geo-postcode>
<!-- Create custom agent dialog --> <!-- Create custom agent dialog -->
<vn-dialog class="edit" <vn-dialog class="edit"

View File

@ -74,6 +74,8 @@ export default class Controller extends Section {
onResponse(response) { onResponse(response) {
this.address.postalCode = response.code; this.address.postalCode = response.code;
this.address.city = response.city;
this.address.provinceFk = response.provinceFk;
} }
} }

View File

@ -191,9 +191,9 @@
</form> </form>
<!-- New postcode dialog --> <!-- New postcode dialog -->
<vn-client-postcode vn-id="postcode" <vn-geo-postcode vn-id="postcode"
on-response="$ctrl.onResponse($response)"> on-response="$ctrl.onResponse($response)">
</vn-client-postcode> </vn-geo-postcode>
<!-- Create custom agent dialog --> <!-- Create custom agent dialog -->
<vn-dialog class="edit" <vn-dialog class="edit"

View File

@ -78,6 +78,8 @@ export default class Controller extends Section {
onResponse(response) { onResponse(response) {
this.address.postalCode = response.code; this.address.postalCode = response.code;
this.address.city = response.city;
this.address.provinceFk = response.provinceFk;
} }
} }

View File

@ -5,12 +5,6 @@
insert-mode="true" insert-mode="true"
form="form"> form="form">
</vn-watcher> </vn-watcher>
<vn-crud-model
auto-load="true"
url="Towns/location"
data="townLocations"
order="name">
</vn-crud-model>
<form name="form" vn-http-submit="$ctrl.onSubmit()" class="vn-w-md"> <form name="form" vn-http-submit="$ctrl.onSubmit()" class="vn-w-md">
<vn-card class="vn-pa-lg"> <vn-card class="vn-pa-lg">
<vn-horizontal> <vn-horizontal>
@ -82,7 +76,7 @@
label="City" label="City"
ng-model="$ctrl.client.city" ng-model="$ctrl.client.city"
selection="$ctrl.town" selection="$ctrl.town"
data="townsLocation" url="Towns/location"
fields="['id', 'name', 'provinceFk']" fields="['id', 'name', 'provinceFk']"
value-field="name"> value-field="name">
<tpl-item> <tpl-item>
@ -136,7 +130,7 @@
</vn-button-bar> </vn-button-bar>
</form> </form>
<!-- New postcode dialog --> <!-- New postcode dialog -->
<vn-client-postcode <vn-geo-postcode
vn-id="postcode" vn-id="postcode"
on-response="$ctrl.onResponse($response)"> on-response="$ctrl.onResponse($response)">
</vn-client-postcode> </vn-geo-postcode>

View File

@ -81,6 +81,9 @@ export default class Controller extends Section {
onResponse(response) { onResponse(response) {
this.client.postcode = response.code; this.client.postcode = response.code;
this.client.city = response.city;
this.client.provinceFk = response.provinceFk;
this.client.countryFk = response.countryFk;
} }
} }

View File

@ -173,7 +173,7 @@
on-accept="$ctrl.onAcceptDuplication()"> on-accept="$ctrl.onAcceptDuplication()">
</vn-confirm> </vn-confirm>
<!-- New postcode dialog --> <!-- New postcode dialog -->
<vn-client-postcode <vn-geo-postcode
vn-id="postcode" vn-id="postcode"
on-response="$ctrl.onResponse($response)"> on-response="$ctrl.onResponse($response)">
</vn-client-postcode> </vn-geo-postcode>

View File

@ -159,6 +159,9 @@ export default class Controller extends Section {
onResponse(response) { onResponse(response) {
this.client.postcode = response.code; this.client.postcode = response.code;
this.client.city = response.city;
this.client.provinceFk = response.provinceFk;
this.client.countryFk = response.countryFk;
} }
} }

View File

@ -37,6 +37,8 @@ import './web-payment';
import './log'; import './log';
import './sms'; import './sms';
import './postcode'; import './postcode';
import './postcode/province';
import './postcode/city';
import './dms/index'; import './dms/index';
import './dms/create'; import './dms/create';
import './dms/edit'; import './dms/edit';

View File

@ -0,0 +1,27 @@
<vn-dialog class="edit"
vn-id="cityDialog"
on-open="$ctrl.onOpen()"
on-accept="$ctrl.onAccept()"
message="New city">
<tpl-body>
<p translate>Please, ensure you put the correct data!</p>
<vn-horizontal>
<vn-textfield vn-one
vn-focus
ng-model="$ctrl.city.name"
label="Name">
</vn-textfield>
<vn-autocomplete vn-one
ng-model="$ctrl.city.provinceFk"
url="Provinces"
show-field="name"
value-field="id"
label="Province">
</vn-autocomplete>
</vn-horizontal>
</tpl-body>
<tpl-buttons>
<input type="button" response="cancel" translate-attr="{value: 'Cancel'}"/>
<button id="saveCity" response="accept" translate>Save</button>
</tpl-buttons>
</vn-dialog>

View File

@ -0,0 +1,37 @@
import ngModule from '../../module';
import Component from 'core/lib/component';
class Controller extends Component { // Comprobar funcionamiento añadir ciudad
open($event) {
if ($event.defaultPrevented) return;
this.$.cityDialog.show();
$event.preventDefault();
}
onAccept() {
try {
if (!this.city.name)
throw new Error(`The city name can't be empty`);
if (!this.city.provinceFk)
throw new Error(`The province can't be empty`);
this.$http.patch(`towns`, this.city).then(res => {
this.vnApp.showMessage(this.$t('The city has been created'));
this.emit('response', {$response: res.data});
});
} catch (e) {
this.vnApp.showError(this.$t(e.message));
return false;
}
return true;
}
}
ngModule.vnComponent('vnGeoCity', {
template: require('./index.html'),
controller: Controller,
bindings: {
data: '<',
}
});

View File

@ -0,0 +1,34 @@
import './index';
describe('Client', () => {
describe('Component vnGeoCity', () => {
let controller;
let $httpBackend;
let $scope;
beforeEach(ngModule('client'));
beforeEach(inject(($componentController, _$httpBackend_, $rootScope) => {
$httpBackend = _$httpBackend_;
$scope = $rootScope.$new();
const $element = angular.element('<vn-dialog></vn-dialog>');
controller = $componentController('vnGeoCity', {$element, $scope});
controller.client = {id: 101};
}));
describe('onAccept()', () => {
it('should perform a POST query and show a success snackbar', () => {
let params = {name: 'Gotham City', provinceFk: 1};
controller.city = {name: 'Gotham City', provinceFk: 1};
jest.spyOn(controller.vnApp, 'showMessage');
$httpBackend.expect('PATCH', `towns`, params).respond(200, params);
controller.onAccept();
$httpBackend.flush();
expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The city has been created');
});
});
});
});

View File

@ -11,7 +11,7 @@
vn-focus vn-focus
vn-id="postcode" vn-id="postcode"
label="Postcode" label="Postcode"
ng-model="$ctrl.data.code" ng-model="$ctrl.location.code"
required="true"> required="true">
</vn-textfield> </vn-textfield>
<vn-autocomplete vn-one <vn-autocomplete vn-one
@ -19,23 +19,39 @@
url="Towns/location" url="Towns/location"
show-field="name" show-field="name"
value-field="id" value-field="id"
ng-model="$ctrl.data.townFk" ng-model="$ctrl.location.townFk"
selection="$ctrl.townSelection" selection="$ctrl.townSelection"
required="true"> required="true">
<append>
<vn-icon-button
icon="add_circle"
vn-tooltip="New city"
ng-click="city.open($event)"
vn-acl="deliveryBoss"
vn-acl-action="remove">
</vn-icon-button>
</append>
</vn-autocomplete> </vn-autocomplete>
</vn-horizontal> </vn-horizontal>
<vn-horizontal> <vn-horizontal>
<vn-autocomplete vn-one <vn-autocomplete vn-one
disabled="true" ng-model="$ctrl.location.provinceFk"
ng-model="$ctrl.data.provinceFk"
url="Provinces" url="Provinces"
show-field="name" show-field="name"
value-field="id" value-field="id"
label="Province"> label="Province">
<append>
<vn-icon-button
icon="add_circle"
vn-tooltip="New province"
ng-click="province.open($event)"
vn-acl="deliveryBoss"
vn-acl-action="remove">
</vn-icon-button>
</append>
</vn-autocomplete> </vn-autocomplete>
<vn-autocomplete vn-one <vn-autocomplete vn-one
disabled="true" ng-model="$ctrl.location.countryFk"
ng-model="$ctrl.data.countryFk"
url="Countries" url="Countries"
show-field="country" show-field="country"
value-field="id" value-field="id"
@ -45,6 +61,16 @@
</tpl-body> </tpl-body>
<tpl-buttons> <tpl-buttons>
<input type="button" response="cancel" translate-attr="{value: 'Cancel'}"/> <input type="button" response="cancel" translate-attr="{value: 'Cancel'}"/>
<button response="accept" translate>Save</button> <button id= "savePostcode" response="accept" translate>Save</button>
</tpl-buttons> </tpl-buttons>
</vn-dialog> </vn-dialog>
<!-- New province dialog -->
<vn-geo-province
vn-id="province"
on-response="$ctrl.onProvinceResponse($response)">
</vn-geo-province>
<!-- New city dialog -->
<vn-geo-city
vn-id="city"
on-response="$ctrl.onCityResponse($response)">
</vn-geo-city>

View File

@ -15,8 +15,9 @@ class Controller extends Component {
const province = selection.province; const province = selection.province;
const country = province.country; const country = province.country;
this.data.provinceFk = province.id; this.location.city = selection.name;
this.data.countryFk = country.id; this.location.provinceFk = province.id;
this.location.countryFk = country.id;
} }
open() { open() {
@ -24,19 +25,35 @@ class Controller extends Component {
} }
onOpen() { onOpen() {
this.location = {};
this.$.postcode.focus(); this.$.postcode.focus();
} }
onProvinceResponse(response) {
this.location.provinceFk = response.id;
this.location.countryFk = response.countryFk;
}
onCityResponse(response) {
this.location.townFk = response.id;
this.location.provinceFk = response.provinceFk;
this.location.countryFk = response.countryFk;
}
onAccept() { onAccept() {
try { try {
if (!this.data.code) if (!this.location.code)
throw new Error(`The postcode can't be empty`); throw new Error(`The postcode can't be empty`);
if (!this.data.townFk) if (!this.location.townFk)
throw new Error(`The town can't be empty`); throw new Error(`The town can't be empty`);
if (!this.location.provinceFk)
throw new Error(`The province can't be empty`);
if (!this.location.provinceFk)
throw new Error(`The country can't be empty`);
this.$http.patch(`postcodes`, this.data).then(res => { this.$http.patch(`postcodes`, this.location).then(() => {
this.vnApp.showMessage(this.$t('The postcode has been saved')); this.vnApp.showMessage(this.$t('The postcode has been created. You can save the data now'));
this.emit('response', {$response: res.data}); this.emit('response', {$response: this.location});
}); });
} catch (e) { } catch (e) {
this.vnApp.showError(this.$t(e.message)); this.vnApp.showError(this.$t(e.message));
@ -46,7 +63,7 @@ class Controller extends Component {
} }
} }
ngModule.vnComponent('vnClientPostcode', { ngModule.vnComponent('vnGeoPostcode', {
template: require('./index.html'), template: require('./index.html'),
controller: Controller, controller: Controller,
bindings: { bindings: {

View File

@ -1,7 +1,7 @@
import './index'; import './index';
describe('Client', () => { describe('Client', () => {
describe('Component vnClientPostcode', () => { describe('Component vnGeoPostcode', () => {
let controller; let controller;
let $httpBackend; let $httpBackend;
let $scope; let $scope;
@ -12,14 +12,14 @@ describe('Client', () => {
$httpBackend = _$httpBackend_; $httpBackend = _$httpBackend_;
$scope = $rootScope.$new(); $scope = $rootScope.$new();
const $element = angular.element('<vn-dialog></vn-dialog>'); const $element = angular.element('<vn-dialog></vn-dialog>');
controller = $componentController('vnClientPostcode', {$element, $scope}); controller = $componentController('vnGeoPostcode', {$element, $scope});
controller.client = {id: 101}; controller.client = {id: 101};
})); }));
describe('onAccept()', () => { describe('onAccept()', () => {
it('should perform a POST query and show a success snackbar', () => { it('should perform a POST query and show a success snackbar', () => {
let params = {townFk: 1, provinceFk: 1, countryFk: 1, code: '46460'}; let params = {townFk: 1, provinceFk: 1, countryFk: 1, code: '46460'};
controller.data = {townFk: 1, provinceFk: 1, countryFk: 1, code: '46460'}; controller.location = {townFk: 1, provinceFk: 1, countryFk: 1, code: '46460'};
jest.spyOn(controller.vnApp, 'showMessage'); jest.spyOn(controller.vnApp, 'showMessage');
$httpBackend.expect('PATCH', `postcodes`, params).respond(200, params); $httpBackend.expect('PATCH', `postcodes`, params).respond(200, params);
@ -27,7 +27,7 @@ describe('Client', () => {
controller.onAccept(); controller.onAccept();
$httpBackend.flush(); $httpBackend.flush();
expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The postcode has been saved'); expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The postcode has been created. You can save the data now');
}); });
}); });
}); });

View File

@ -1,5 +1,11 @@
New postcode: Nuevo código postal New postcode: Nuevo código postal
New city: Nueva ciudad
New province: Nueva provincia
Please, ensure you put the correct data!: ¡Por favor, asegúrate de poner los datos correctos! Please, ensure you put the correct data!: ¡Por favor, asegúrate de poner los datos correctos!
The postcode can't be empty: El código postal no puede quedar vacío The postcode can't be empty: El código postal no puede quedar vacío
The town can't be empty: La población no puede quedar vacía The town can't be empty: La población no puede quedar vacía
The postcode has been saved: El código postal ha sido guardado The province can't be empty: La provincia no puede quedar vacía
The country can't be empty: El país no puede quedar vacío
The postcode has been created. You can save the data now: Se ha creado el código postal. Ahora puedes guardar los datos
The city has been created: Se ha creado la ciudad
The province has been created: Se ha creado la provincia

View File

@ -0,0 +1,27 @@
<vn-dialog class="edit"
vn-id="provinceDialog"
on-open="$ctrl.onOpen()"
on-accept="$ctrl.onAccept()"
message="New province">
<tpl-body>
<p translate>Please, ensure you put the correct data!</p>
<vn-horizontal>
<vn-textfield vn-one
vn-focus
ng-model="$ctrl.province.name"
label="Name">
</vn-textfield>
<vn-autocomplete vn-one
ng-model="$ctrl.province.countryFk"
url="Countries"
show-field="country"
value-field="id"
label="Country">
</vn-autocomplete>
</vn-horizontal>
</tpl-body>
<tpl-buttons>
<input type="button" response="cancel" translate-attr="{value: 'Cancel'}"/>
<button id="saveProvince" response="accept" translate>Save</button>
</tpl-buttons>
</vn-dialog>

View File

@ -0,0 +1,37 @@
import ngModule from '../../module';
import Component from 'core/lib/component';
class Controller extends Component {
open($event) {
if ($event.defaultPrevented) return;
this.$.provinceDialog.show();
$event.preventDefault();
}
onAccept() {
try {
if (!this.province.name)
throw new Error(`The province name can't be empty`);
if (!this.province.countryFk)
throw new Error(`The country can't be empty`);
this.$http.patch(`provinces`, this.province).then(res => {
this.vnApp.showMessage(this.$t('The province has been created'));
this.emit('response', {$response: res.data});
});
} catch (e) {
this.vnApp.showError(this.$t(e.message));
return false;
}
return true;
}
}
ngModule.vnComponent('vnGeoProvince', {
template: require('./index.html'),
controller: Controller,
bindings: {
data: '<',
}
});

View File

@ -0,0 +1,34 @@
import './index';
describe('Client', () => {
describe('Component vnGeoProvince', () => {
let controller;
let $httpBackend;
let $scope;
beforeEach(ngModule('client'));
beforeEach(inject(($componentController, _$httpBackend_, $rootScope) => {
$httpBackend = _$httpBackend_;
$scope = $rootScope.$new();
const $element = angular.element('<vn-dialog></vn-dialog>');
controller = $componentController('vnGeoProvince', {$element, $scope});
controller.client = {id: 101};
}));
describe('onAccept()', () => {
it('should perform a POST query and show a success snackbar', () => {
let params = {name: 'New Jersey', countryFk: 1};
controller.province = {name: 'New Jersey', countryFk: 1};
jest.spyOn(controller.vnApp, 'showMessage');
$httpBackend.expect('PATCH', `provinces`, params).respond(200, params);
controller.onAccept();
$httpBackend.flush();
expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The province has been created');
});
});
});
});

View File

@ -1,6 +1,6 @@
@import "variables"; @import "variables";
vn-client-postcode { vn-geo-postcode {
vn-dialog { vn-dialog {
p { p {
color: $color-alert color: $color-alert

View File

@ -76,6 +76,7 @@ module.exports = Self => {
companyFk, shipped, landed, isDeleted, option) => { companyFk, shipped, landed, isDeleted, option) => {
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const models = Self.app.models; const models = Self.app.models;
const $t = ctx.req.__; // $translate
const isEditable = await models.Ticket.isEditable(ctx, id); const isEditable = await models.Ticket.isEditable(ctx, id);
if (!isEditable) if (!isEditable)
@ -97,40 +98,22 @@ module.exports = Self => {
'warehouseFk', 'companyFk', 'shipped', 'landed', 'isDeleted'], 'warehouseFk', 'companyFk', 'shipped', 'landed', 'isDeleted'],
include: [ include: [
{ {
relation: 'address', relation: 'client',
scope: { scope: {
include: { fields: 'salesPersonFk'
relation: 'observations',
scope: {
where: {observationTypeFk: observationTypeDelivery.id},
include: {
relation: 'observationType'
}
}
}
} }
}] }]
}); });
const updatedTicket = Object.assign({}, ctx.args); const updatedTicket = Object.assign({}, ctx.args);
delete updatedTicket.ctx; delete updatedTicket.ctx;
delete updatedTicket.option; delete updatedTicket.option;
// Force unroute // Force unroute
const hasToBeUnrouted = true; const hasToBeUnrouted = true;
const propertiesChange = diff(originalTicket, updatedTicket); const changedProperties = diff(originalTicket, updatedTicket);
let logRecord = { const query = 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
originFk: id, const res = await Self.rawSql(query, [
userFk: userId,
action: 'update',
changedModel: 'Ticket',
changedModelId: id,
oldInstance: originalTicket,
newInstance: propertiesChange
};
let query = 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
let res = await Self.rawSql(query, [
id, id,
clientFk, clientFk,
agencyModeFk, agencyModeFk,
@ -155,7 +138,20 @@ module.exports = Self => {
if (ticketObservation) if (ticketObservation)
await ticketObservation.destroy(); await ticketObservation.destroy();
const [observation] = originalTicket.address().observations(); const address = await models.Address.findOne({
where: {id: addressFk},
include: {
relation: 'observations',
scope: {
where: {observationTypeFk: observationTypeDelivery.id},
include: {
relation: 'observationType'
}
}
}
});
const [observation] = address.observations();
if (observation) { if (observation) {
await models.TicketObservation.upsert({ await models.TicketObservation.upsert({
ticketFk: id, ticketFk: id,
@ -164,7 +160,46 @@ module.exports = Self => {
}); });
} }
} }
await models.TicketLog.create(logRecord);
await models.TicketLog.create({
originFk: id,
userFk: userId,
action: 'update',
changedModel: 'Ticket',
changedModelId: id,
oldInstance: originalTicket,
newInstance: changedProperties
});
const salesPersonId = originalTicket.client().salesPersonFk;
if (salesPersonId) {
const origin = ctx.req.headers.origin;
let changesMade = '';
for (let change in changedProperties) {
let value = changedProperties[change];
if (value instanceof Date) {
value = new Intl.DateTimeFormat('es', {
year: '2-digit',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
}).format(value);
}
changesMade += `${change}: ${value}\r\n`;
}
const message = $t('Changed this data from the ticket', {
ticketId: id,
ticketUrl: `${origin}/#!/ticket/${id}/summary`,
changes: changesMade
});
await models.Chat.sendCheckingPresence(ctx, salesPersonId, message);
}
return res; return res;
}; };
}; };

View File

@ -47,7 +47,14 @@ describe('ticket componentUpdate()', () => {
let ctx = { let ctx = {
args: {clientFk: clientID, args: {clientFk: clientID,
agencyModeFk: agencyModeID}, agencyModeFk: agencyModeID},
req: {accessToken: {userId: userID}}}; req: {
accessToken: {userId: userID},
headers: {origin: 'http://localhost'},
__: (value, params) => {
return params.nickname;
}
}
};
await app.models.Ticket.componentUpdate(ctx, ticketID, clientID, agencyModeID, addressID, await app.models.Ticket.componentUpdate(ctx, ticketID, clientID, agencyModeID, addressID,
zoneID, warehouseID, companyID, shipped, landed, isDeleted, option); zoneID, warehouseID, companyID, shipped, landed, isDeleted, option);

View File

@ -56,8 +56,16 @@ class Controller extends Component {
set warehouseId(value) { set warehouseId(value) {
if (value != this.ticket.warehouseFk) { if (value != this.ticket.warehouseFk) {
this.ticket.warehouseFk = value; this.ticket.warehouseFk = value;
this.ticket.agencyModeFk = null;
this.ticket.zoneFk = null; this.getShipped({
landed: this.ticket.landed,
addressFk: this.ticket.addressFk,
agencyModeFk: this.ticket.agencyModeFk,
warehouseFk: value
}).then(() => {
if (this.zoneId == null)
this.ticket.agencyModeFk = null;
});
} }
} }
@ -177,8 +185,8 @@ class Controller extends Component {
); );
} }
let query = `tickets/${this.ticket.id}/priceDifference`; const query = `tickets/${this.ticket.id}/priceDifference`;
let params = { const params = {
landed: this.ticket.landed, landed: this.ticket.landed,
addressId: this.ticket.addressFk, addressId: this.ticket.addressFk,
agencyModeId: this.ticket.agencyModeFk, agencyModeId: this.ticket.agencyModeFk,
@ -202,9 +210,13 @@ class Controller extends Component {
* Returns a landing date * Returns a landing date
*/ */
getLanded(params) { getLanded(params) {
const validParams = this.shipped && this.addressId
&& this.agencyModeId && this.warehouseId;
if (!validParams) return this.$q.resolve();
this.ticket.zoneFk = null; this.ticket.zoneFk = null;
const query = `Agencies/getLanded`; const query = `Agencies/getLanded`;
this.$http.get(query, {params}).then(res => { return this.$http.get(query, {params}).then(res => {
if (res.data) { if (res.data) {
this.ticket.zoneFk = res.data.zoneFk; this.ticket.zoneFk = res.data.zoneFk;
this.ticket.landed = res.data.landed; this.ticket.landed = res.data.landed;
@ -221,9 +233,13 @@ class Controller extends Component {
* Returns a shipment date * Returns a shipment date
*/ */
getShipped(params) { getShipped(params) {
const validParams = this.landed && this.addressId
&& this.agencyModeId && this.warehouseId;
if (!validParams) return this.$q.resolve();
this.ticket.zoneFk = null; this.ticket.zoneFk = null;
const query = `Agencies/getShipped`; const query = `Agencies/getShipped`;
this.$http.get(query, {params}).then(res => { return this.$http.get(query, {params}).then(res => {
if (res.data) { if (res.data) {
this.ticket.zoneFk = res.data.zoneFk; this.ticket.zoneFk = res.data.zoneFk;
this.ticket.landed = params.landed; this.ticket.landed = params.landed;

View File

@ -323,6 +323,7 @@ describe('Ticket', () => {
warehouseFk: 1 warehouseFk: 1
}; };
const serializedParams = $httpParamSerializer(params); const serializedParams = $httpParamSerializer(params);
controller.ticket.shipped = shipped;
$httpBackend.expect('GET', `Agencies/getLanded?${serializedParams}`).respond(200, expectedResult); $httpBackend.expect('GET', `Agencies/getLanded?${serializedParams}`).respond(200, expectedResult);
controller.getLanded(params); controller.getLanded(params);
@ -344,6 +345,7 @@ describe('Ticket', () => {
warehouseFk: 1 warehouseFk: 1
}; };
const serializedParams = $httpParamSerializer(params); const serializedParams = $httpParamSerializer(params);
controller.ticket.landed = landed;
$httpBackend.expect('GET', `Agencies/getShipped?${serializedParams}`).respond(200, expectedResult); $httpBackend.expect('GET', `Agencies/getShipped?${serializedParams}`).respond(200, expectedResult);
controller.getShipped(params); controller.getShipped(params);

View File

@ -37,9 +37,12 @@ module.exports = Self => {
Self.getLanded = async(ctx, shipped, addressFk, agencyModeFk, warehouseFk) => { Self.getLanded = async(ctx, shipped, addressFk, agencyModeFk, warehouseFk) => {
const userId = ctx.req.accessToken.userId; const userId = ctx.req.accessToken.userId;
const models = Self.app.models; const models = Self.app.models;
const isProductionBoss = await models.Account.hasRole(userId, 'productionBoss'); const roles = await models.Account.getRoles(userId);
const canSeeExpired = roles.filter(role =>
role == 'productionBoss' || role == 'administrative'
);
let showExpired = false; let showExpired = false;
if (isProductionBoss) showExpired = true; if (canSeeExpired.length) showExpired = true;
let stmts = []; let stmts = [];
stmts.push(new ParameterizedSQL( stmts.push(new ParameterizedSQL(

View File

@ -32,9 +32,12 @@ module.exports = Self => {
&& where.agencyModeFk && where.warehouseFk; && where.agencyModeFk && where.warehouseFk;
if (filterByAvailability) { if (filterByAvailability) {
const isProductionBoss = await models.Account.hasRole(userId, 'productionBoss'); const roles = await models.Account.getRoles(userId);
const canSeeExpired = roles.filter(role =>
role == 'productionBoss' || role == 'administrative'
);
let showExpired = false; let showExpired = false;
if (isProductionBoss) showExpired = true; if (canSeeExpired.length) showExpired = true;
stmt = new ParameterizedSQL(`CALL vn.zone_getLanded(?, ?, ?, ?, ?)`, [ stmt = new ParameterizedSQL(`CALL vn.zone_getLanded(?, ?, ?, ?, ?)`, [
where.shipped, where.shipped,

View File

@ -3,6 +3,7 @@ const Component = require(`${appPath}/core/component`);
const reportHeader = new Component('report-header'); const reportHeader = new Component('report-header');
const reportFooter = new Component('report-footer'); const reportFooter = new Component('report-footer');
const md5 = require('md5'); const md5 = require('md5');
const fs = require('fs-extra');
module.exports = { module.exports = {
name: 'delivery-note', name: 'delivery-note',
@ -24,11 +25,14 @@ module.exports = {
}, },
computed: { computed: {
dmsPath() { dmsPath() {
const pathHash = md5(this.signature.id.toString()).substring(0, 3); if (!this.signature) return;
const hostPath = `file:///${config.storage.root}/${pathHash}`;
if (this.signature && this.signature.id) const hash = md5(this.signature.id.toString()).substring(0, 3);
return `${hostPath}/${this.signature.id}.png`; const file = `${config.storage.root}/${hash}/${this.signature.id}.png`;
const src = fs.readFileSync(file);
const base64 = Buffer.from(src, 'utf8').toString('base64');
return `data:image/png;base64, ${base64}`;
}, },
serviceTotal() { serviceTotal() {
let total = 0.00; let total = 0.00;