- {{price.rate3 | currency: 'EUR':2}}
+
+ {{price.rate3 | currency: 'EUR':2}}
+
+ ng-model="price.hasMinPrice"
+ on-change="$ctrl.upsertPrice(price)">
|
-
-
+
+
+
+
|
-
+
+
+
+ |
+
+
-
+ ng-model="price.warehouseFk"
+ data="warehouses"
+ on-change="$ctrl.upsertPrice(price)"
+ tabindex="2">
+
|
+
+
+
+
+
+
+
+
+
+ Edit
+
+ {{::$ctrl.totalChecked}}
+
+ buy(s)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/modules/item/front/fixed-price/index.js b/modules/item/front/fixed-price/index.js
index df2989043..a39cd6602 100644
--- a/modules/item/front/fixed-price/index.js
+++ b/modules/item/front/fixed-price/index.js
@@ -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';
diff --git a/modules/item/front/fixed-price/index.spec.js b/modules/item/front/fixed-price/index.spec.js
index 42dd898b3..ae24da60b 100644
--- a/modules/item/front/fixed-price/index.spec.js
+++ b/modules/item/front/fixed-price/index.spec.js
@@ -12,8 +12,92 @@ describe('fixed price', () => {
const $scope = $rootScope.$new();
const $element = angular.element('');
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');
diff --git a/modules/item/front/fixed-price/locale/es.yml b/modules/item/front/fixed-price/locale/es.yml
index 6bdfcb678..6dacf96c9 100644
--- a/modules/item/front/fixed-price/locale/es.yml
+++ b/modules/item/front/fixed-price/locale/es.yml
@@ -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
diff --git a/modules/item/front/fixed-price/style.scss b/modules/item/front/fixed-price/style.scss
index ba3878dba..97ceaf7cd 100644
--- a/modules/item/front/fixed-price/style.scss
+++ b/modules/item/front/fixed-price/style.scss
@@ -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;
- }
-}
\ No newline at end of file
diff --git a/modules/item/front/request-search-panel/index.html b/modules/item/front/request-search-panel/index.html
index 8c9d04b64..a431d4fd6 100644
--- a/modules/item/front/request-search-panel/index.html
+++ b/modules/item/front/request-search-panel/index.html
@@ -38,6 +38,19 @@
url="Warehouses">
+
+
+ {{firstName}} {{lastName}}
+
+
+
{
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,
diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js
index ab1c32d1b..39347f418 100644
--- a/modules/ticket/back/methods/ticket/saveSign.js
+++ b/modules/ticket/back/methods/ticket/saveSign.js
@@ -34,6 +34,8 @@ module.exports = Self => {
const models = Self.app.models;
const myOptions = {};
let tx;
+ let dms;
+ let gestDocCreated = false;
if (typeof options == 'object')
Object.assign(myOptions, options);
@@ -96,11 +98,12 @@ module.exports = Self => {
warehouseId: ticket.warehouseFk,
companyId: ticket.companyFk,
dmsTypeId: dmsType.id,
- reference: id,
- description: `Ticket ${id} Cliente ${ticket.client().name} Ruta ${ticket.route().id}`,
+ reference: '',
+ description: `Firma del cliente - Ruta ${ticket.route().id}`,
hasFile: true
};
- await models.Ticket.uploadFile(ctxUploadFile, id, myOptions);
+ dms = await models.Dms.uploadFile(ctxUploadFile, myOptions);
+ gestDocCreated = true;
}
try {
@@ -118,12 +121,16 @@ module.exports = Self => {
throw new UserError('This ticket cannot be signed because it has not been boxed');
else if (!await gestDocExists(args.tickets[i])) {
if (args.location) setLocation(args.tickets[i]);
- await createGestDoc(args.tickets[i]);
+ if (!gestDocCreated) await createGestDoc(args.tickets[i]);
+ await models.TicketDms.create({ticketFk: args.tickets[i], dmsFk: dms[0].id}, myOptions);
+ const ticket = await models.Ticket.findById(args.tickets[i], null, myOptions);
+ await ticket.updateAttribute('isSigned', true, myOptions);
await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [args.tickets[i], 'DELIVERED'], myOptions);
}
}
if (tx) await tx.commit();
+ return;
} catch (e) {
if (tx) await tx.rollback();
throw e;
diff --git a/modules/worker/back/methods/worker-time-control/addTimeEntry.js b/modules/worker/back/methods/worker-time-control/addTimeEntry.js
index fef3cf223..c8c08d9b1 100644
--- a/modules/worker/back/methods/worker-time-control/addTimeEntry.js
+++ b/modules/worker/back/methods/worker-time-control/addTimeEntry.js
@@ -51,6 +51,8 @@ module.exports = Self => {
if (response[0] && response[0].error)
throw new UserError(response[0].error);
+ await models.WorkerTimeControl.resendWeeklyHourEmail(ctx, workerId, args.timed, myOptions);
+
return response;
};
};
diff --git a/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js b/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js
index c80dcab81..e33d6b790 100644
--- a/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js
+++ b/modules/worker/back/methods/worker-time-control/deleteTimeEntry.js
@@ -38,7 +38,11 @@ module.exports = Self => {
if (isSubordinate === false || (isSubordinate && isHimself && !isTeamBoss))
throw new UserError(`You don't have enough privileges`);
- return Self.rawSql('CALL vn.workerTimeControl_remove(?, ?)', [
+ const response = await Self.rawSql('CALL vn.workerTimeControl_remove(?, ?)', [
targetTimeEntry.userFk, targetTimeEntry.timed], myOptions);
+
+ await models.WorkerTimeControl.resendWeeklyHourEmail(ctx, targetTimeEntry.userFk, targetTimeEntry.timed, myOptions);
+
+ return response;
};
};
diff --git a/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js b/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js
new file mode 100644
index 000000000..2452a29f9
--- /dev/null
+++ b/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js
@@ -0,0 +1,68 @@
+module.exports = Self => {
+ Self.remoteMethodCtx('resendWeeklyHourEmail', {
+ description: 'Adds a new hour registry',
+ accessType: 'WRITE',
+ accepts: [{
+ arg: 'id',
+ type: 'number',
+ description: 'The worker id',
+ http: {source: 'path'}
+ },
+ {
+ arg: 'dated',
+ type: 'date',
+ required: true
+ }],
+ returns: [{
+ type: 'Object',
+ root: true
+ }],
+ http: {
+ path: `/:id/resendWeeklyHourEmail`,
+ verb: 'POST'
+ }
+ });
+
+ Self.resendWeeklyHourEmail = async(ctx, workerId, dated, options) => {
+ const models = Self.app.models;
+ const myOptions = {};
+
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
+
+ const yearNumber = dated.getFullYear();
+ const weekNumber = getWeekNumber(dated);
+ const workerTimeControlMail = await models.WorkerTimeControlMail.findOne({
+ where: {
+ workerFk: workerId,
+ year: yearNumber,
+ week: weekNumber
+ }
+ }, myOptions);
+
+ if (workerTimeControlMail && workerTimeControlMail.state != 'SENDED') {
+ const worker = await models.EmailUser.findById(workerId, null, myOptions);
+ ctx.args = {
+ recipient: worker.email,
+ year: yearNumber,
+ week: weekNumber,
+ workerId: workerId,
+ state: 'SENDED'
+ };
+ return models.WorkerTimeControl.weeklyHourRecordEmail(ctx, myOptions);
+ }
+
+ return false;
+ };
+
+ function getWeekNumber(date) {
+ const tempDate = new Date(date);
+ let dayOfWeek = tempDate.getDay();
+ dayOfWeek = (dayOfWeek === 0) ? 7 : dayOfWeek;
+ const firstDayOfWeek = new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate() - (dayOfWeek - 1));
+ const firstDayOfYear = new Date(tempDate.getFullYear(), 0, 1);
+ const differenceInMilliseconds = firstDayOfWeek.getTime() - firstDayOfYear.getTime();
+ const weekNumber = Math.floor(differenceInMilliseconds / (1000 * 60 * 60 * 24 * 7)) + 1;
+ return weekNumber;
+ }
+};
diff --git a/modules/worker/back/methods/worker-time-control/sendMail.js b/modules/worker/back/methods/worker-time-control/sendMail.js
index 4962e96f8..2c827e320 100644
--- a/modules/worker/back/methods/worker-time-control/sendMail.js
+++ b/modules/worker/back/methods/worker-time-control/sendMail.js
@@ -82,14 +82,9 @@ module.exports = Self => {
updated: Date.vnNew(), state: 'SENDED'
}, myOptions);
- stmt = new ParameterizedSQL(
- `CALL vn.timeControl_calculateByUser(?, ?, ?)
- `, [args.workerId, started, ended]);
+ stmt = new ParameterizedSQL('DROP TEMPORARY TABLE IF EXISTS tmp.`user`');
stmts.push(stmt);
-
- stmt = new ParameterizedSQL(
- `CALL vn.timeBusiness_calculateByUser(?, ?, ?)
- `, [args.workerId, started, ended]);
+ stmt = new ParameterizedSQL('CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk FROM account.user WHERE id = ?', [args.workerId]);
stmts.push(stmt);
} else {
await models.WorkerTimeControl.destroyAll({
@@ -105,13 +100,38 @@ module.exports = Self => {
updated: Date.vnNew(), state: 'SENDED'
}, myOptions);
- stmt = new ParameterizedSQL(`CALL vn.timeControl_calculateAll(?, ?)`, [started, ended]);
+ stmt = new ParameterizedSQL('DROP TEMPORARY TABLE IF EXISTS tmp.`user`');
stmts.push(stmt);
-
- stmt = new ParameterizedSQL(`CALL vn.timeBusiness_calculateAll(?, ?)`, [started, ended]);
+ stmt = new ParameterizedSQL('CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT userFk FROM vn.worker w JOIN account.`user` u ON u.id = w.userFk WHERE userFk IS NOT NULL');
stmts.push(stmt);
}
+ stmt = new ParameterizedSQL(
+ `CALL vn.timeControl_calculate(?, ?)
+ `, [started, ended]);
+ stmts.push(stmt);
+
+ stmt = new ParameterizedSQL(
+ `CALL vn.timeBusiness_calculate(?, ?)
+ `, [started, ended]);
+ stmts.push(stmt);
+
+ stmt = new ParameterizedSQL(
+ `CALL vn.timeControl_getError(?, ?)
+ `, [started, ended]);
+ stmts.push(stmt);
+
+ stmt = new ParameterizedSQL(`INSERT INTO mail (receiver, subject, body)
+ SELECT CONCAT(u.name, '@verdnatura.es'),
+ CONCAT('Error registro de horas semana ', ?, ' año ', ?) ,
+ CONCAT('No se ha podido enviar el registro de horas al empleado/s: ', GROUP_CONCAT(DISTINCT CONCAT(' ', w.id, ' ', w.firstName, ' ', w.lastName)))
+ FROM tmp.timeControlError tce
+ JOIN vn.workerTimeControl wtc ON wtc.id = tce.id
+ JOIN worker w ON w.id = wtc.userFK
+ JOIN account.user u ON u.id = w.bossFk
+ GROUP BY w.bossFk`, [args.week, args.year]);
+ stmts.push(stmt);
+
stmt = new ParameterizedSQL(`
SELECT CONCAT(u.name, '@verdnatura.es') receiver,
u.id workerFk,
@@ -131,20 +151,16 @@ module.exports = Self => {
JOIN business b ON b.id = tb.businessFk
LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = tb.userFk AND tc.dated = tb.dated
LEFT JOIN worker w ON w.id = u.id
- JOIN (SELECT tb.userFk,
- SUM(IF(tb.type IS NULL,
- IF(tc.timeWorkDecimal > 0, FALSE, IF(tb.timeWorkDecimal > 0, TRUE, FALSE)),
- TRUE))isTeleworkingWeek
- FROM tmp.timeBusinessCalculate tb
- LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = tb.userFk
- AND tc.dated = tb.dated
- GROUP BY tb.userFk
- HAVING isTeleworkingWeek > 0
- )sub ON sub.userFk = u.id
- WHERE d.hasToRefill
+ LEFT JOIN (
+ SELECT DISTINCT wtc.userFk
+ FROM tmp.timeControlError tce
+ JOIN vn.workerTimeControl wtc ON wtc.id = tce.id
+ )sub ON sub.userFk = tb.userFk
+ WHERE sub.userFK IS NULL
AND IFNULL(?, u.id) = u.id
AND b.companyCodeFk = 'VNL'
AND w.businessFk
+ AND d.isTeleworking
ORDER BY u.id, tb.dated
`, [args.workerId]);
const index = stmts.push(stmt) - 1;
@@ -332,23 +348,18 @@ module.exports = Self => {
const lastDay = days[index][days[index].length - 1];
if (day.workerFk != previousWorkerFk || day == lastDay) {
- await models.WorkerTimeControlMail.create({
- workerFk: previousWorkerFk,
+ const query = `INSERT IGNORE INTO workerTimeControlMail (workerFk, year, week)
+ VALUES(?, ?, ?);`;
+ await Self.rawSql(query, [previousWorkerFk, args.year, args.week]);
+
+ ctx.args = {
+ recipient: previousReceiver,
year: args.year,
- week: args.week
- }, myOptions);
-
- const salix = await models.Url.findOne({
- where: {
- appName: 'salix',
- environment: process.env.NODE_ENV || 'dev'
- }
- }, myOptions);
-
- const timestamp = started.getTime() / 1000;
- const url = `${salix.url}worker/${previousWorkerFk}/time-control?timestamp=${timestamp}`;
-
- await models.WorkerTimeControl.weeklyHourRecordEmail(ctx, previousReceiver, args.week, args.year, url);
+ week: args.week,
+ workerId: previousWorkerFk,
+ state: 'SENDED'
+ };
+ await models.WorkerTimeControl.weeklyHourRecordEmail(ctx, myOptions);
previousWorkerFk = day.workerFk;
previousReceiver = day.receiver;
diff --git a/modules/worker/back/methods/worker-time-control/specs/sendMail.spec.js b/modules/worker/back/methods/worker-time-control/specs/sendMail.spec.js
deleted file mode 100644
index 24bfd6904..000000000
--- a/modules/worker/back/methods/worker-time-control/specs/sendMail.spec.js
+++ /dev/null
@@ -1,120 +0,0 @@
-const models = require('vn-loopback/server/server').models;
-
-describe('workerTimeControl sendMail()', () => {
- const workerId = 18;
- const activeCtx = {
- getLocale: () => {
- return 'en';
- }
- };
- const ctx = {req: activeCtx, args: {}};
-
- it('should fill time control of a worker without records in Journey and with rest', async() => {
- const tx = await models.WorkerTimeControl.beginTransaction({});
-
- try {
- const options = {transaction: tx};
-
- await models.WorkerTimeControl.sendMail(ctx, options);
-
- const workerTimeControl = await models.WorkerTimeControl.find({
- where: {userFk: workerId}
- }, options);
-
- expect(workerTimeControl[0].timed.getHours()).toEqual(8);
- expect(workerTimeControl[1].timed.getHours()).toEqual(9);
- expect(`${workerTimeControl[2].timed.getHours()}:${workerTimeControl[2].timed.getMinutes()}`).toEqual('9:20');
- expect(workerTimeControl[3].timed.getHours()).toEqual(16);
-
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- throw e;
- }
- });
-
- it('should fill time control of a worker without records in Journey and without rest', async() => {
- const workdayOf20Hours = 3;
- const tx = await models.WorkerTimeControl.beginTransaction({});
-
- try {
- const options = {transaction: tx};
- query = `UPDATE business b
- SET b.calendarTypeFk = ?
- WHERE b.workerFk = ?; `;
- await models.WorkerTimeControl.rawSql(query, [workdayOf20Hours, workerId], options);
-
- await models.WorkerTimeControl.sendMail(ctx, options);
-
- const workerTimeControl = await models.WorkerTimeControl.find({
- where: {userFk: workerId}
- }, options);
-
- expect(workerTimeControl[0].timed.getHours()).toEqual(8);
- expect(workerTimeControl[1].timed.getHours()).toEqual(12);
-
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- throw e;
- }
- });
-
- it('should fill time control of a worker with records in Journey and with rest', async() => {
- const tx = await models.WorkerTimeControl.beginTransaction({});
-
- try {
- const options = {transaction: tx};
- query = `INSERT INTO postgresql.journey(journey_id, day_id, start, end, business_id)
- VALUES
- (1, 1, '09:00:00', '13:00:00', ?),
- (2, 1, '14:00:00', '19:00:00', ?);`;
- await models.WorkerTimeControl.rawSql(query, [workerId, workerId, workerId], options);
-
- await models.WorkerTimeControl.sendMail(ctx, options);
-
- const workerTimeControl = await models.WorkerTimeControl.find({
- where: {userFk: workerId}
- }, options);
-
- expect(workerTimeControl[0].timed.getHours()).toEqual(9);
- expect(workerTimeControl[2].timed.getHours()).toEqual(10);
- expect(`${workerTimeControl[3].timed.getHours()}:${workerTimeControl[3].timed.getMinutes()}`).toEqual('10:20');
- expect(workerTimeControl[1].timed.getHours()).toEqual(13);
- expect(workerTimeControl[4].timed.getHours()).toEqual(14);
- expect(workerTimeControl[5].timed.getHours()).toEqual(19);
-
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- throw e;
- }
- });
-
- it('should fill time control of a worker with records in Journey and without rest', async() => {
- const tx = await models.WorkerTimeControl.beginTransaction({});
-
- try {
- const options = {transaction: tx};
- query = `INSERT INTO postgresql.journey(journey_id, day_id, start, end, business_id)
- VALUES
- (1, 1, '12:30:00', '14:00:00', ?);`;
- await models.WorkerTimeControl.rawSql(query, [workerId, workerId, workerId], options);
-
- await models.WorkerTimeControl.sendMail(ctx, options);
-
- const workerTimeControl = await models.WorkerTimeControl.find({
- where: {userFk: workerId}
- }, options);
-
- expect(`${workerTimeControl[0].timed.getHours()}:${workerTimeControl[0].timed.getMinutes()}`).toEqual('12:30');
- expect(workerTimeControl[1].timed.getHours()).toEqual(14);
-
- await tx.rollback();
- } catch (e) {
- await tx.rollback();
- throw e;
- }
- });
-});
-
diff --git a/modules/worker/back/methods/worker-time-control/updateTimeEntry.js b/modules/worker/back/methods/worker-time-control/updateTimeEntry.js
index a99a61770..83349ea63 100644
--- a/modules/worker/back/methods/worker-time-control/updateTimeEntry.js
+++ b/modules/worker/back/methods/worker-time-control/updateTimeEntry.js
@@ -46,8 +46,12 @@ module.exports = Self => {
if (notAllowed)
throw new UserError(`You don't have enough privileges`);
- return targetTimeEntry.updateAttributes({
+ const timeEntryUpdated = await targetTimeEntry.updateAttributes({
direction: args.direction
}, myOptions);
+
+ await models.WorkerTimeControl.resendWeeklyHourEmail(ctx, targetTimeEntry.userFk, targetTimeEntry.timed, myOptions);
+
+ return timeEntryUpdated;
};
};
diff --git a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js
index 642ff90d2..6f794511f 100644
--- a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js
+++ b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js
@@ -47,10 +47,6 @@ module.exports = Self => {
if (typeof options == 'object')
Object.assign(myOptions, options);
- const isHimself = userId == args.workerId;
- if (!isHimself)
- throw new UserError(`You don't have enough privileges`);
-
const workerTimeControlMail = await models.WorkerTimeControlMail.findOne({
where: {
workerFk: args.workerId,
@@ -69,6 +65,12 @@ module.exports = Self => {
reason: args.reason || null
}, myOptions);
+ if (args.state == 'SENDED') {
+ await workerTimeControlMail.updateAttributes({
+ sendedCounter: workerTimeControlMail.sendedCounter + 1
+ }, myOptions);
+ }
+
const logRecord = {
originFk: args.workerId,
userFk: userId,
diff --git a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js
index 6feadb936..f44080559 100644
--- a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js
+++ b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js
@@ -1,5 +1,3 @@
-const {Email} = require('vn-print');
-
module.exports = Self => {
Self.remoteMethodCtx('weeklyHourRecordEmail', {
description: 'Sends the weekly hour record',
@@ -22,7 +20,12 @@ module.exports = Self => {
required: true
},
{
- arg: 'url',
+ arg: 'workerId',
+ type: 'number',
+ required: true
+ },
+ {
+ arg: 'state',
type: 'string',
required: true
}
@@ -37,17 +40,48 @@ module.exports = Self => {
}
});
- Self.weeklyHourRecordEmail = async(ctx, recipient, week, year, url) => {
- const params = {
- recipient: recipient,
- lang: ctx.req.getLocale(),
- week: week,
- year: year,
- url: url
- };
+ Self.weeklyHourRecordEmail = async(ctx, options) => {
+ const models = Self.app.models;
+ const args = ctx.args;
+ const myOptions = {};
- const email = new Email('weekly-hour-record', params);
+ if (typeof options == 'object')
+ Object.assign(myOptions, options);
- return email.send();
+ const salix = await models.Url.findOne({
+ where: {
+ appName: 'salix',
+ environment: process.env.NODE_ENV || 'dev'
+ }
+ }, myOptions);
+
+ const dated = getMondayDateFromYearWeek(args.year, args.week);
+ const timestamp = dated.getTime() / 1000;
+
+ const url = `${salix.url}worker/${args.workerId}/time-control?timestamp=${timestamp}`;
+ ctx.args.url = url;
+
+ Self.sendTemplate(ctx, 'weekly-hour-record');
+
+ return models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, myOptions);
};
+
+ function getMondayDateFromYearWeek(yearNumber, weekNumber) {
+ const yearStart = new Date(yearNumber, 0, 1);
+ const firstMonday = new Date(yearStart.getTime() + ((7 - yearStart.getDay() + 1) % 7) * 86400000);
+ const firstMondayWeekNumber = getWeekNumber(firstMonday);
+
+ if (firstMondayWeekNumber > 1)
+ firstMonday.setDate(firstMonday.getDate() + 7);
+
+ firstMonday.setDate(firstMonday.getDate() + (weekNumber - 1) * 7);
+
+ return firstMonday;
+ }
+
+ function getWeekNumber(date) {
+ const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
+ const daysPassed = (date - firstDayOfYear) / 86400000;
+ return Math.ceil((daysPassed + firstDayOfYear.getDay() + 1) / 7);
+ }
};
diff --git a/modules/worker/back/model-config.json b/modules/worker/back/model-config.json
index 63fc65827..145934700 100644
--- a/modules/worker/back/model-config.json
+++ b/modules/worker/back/model-config.json
@@ -53,6 +53,9 @@
"Worker": {
"dataSource": "vn"
},
+ "WorkerObservation": {
+ "dataSource": "vn"
+ },
"WorkerConfig": {
"dataSource": "vn"
},
diff --git a/modules/worker/back/models/worker-observation.js b/modules/worker/back/models/worker-observation.js
new file mode 100644
index 000000000..cccc2cfbd
--- /dev/null
+++ b/modules/worker/back/models/worker-observation.js
@@ -0,0 +1,12 @@
+module.exports = function(Self) {
+ Self.validatesPresenceOf('text', {
+ message: 'Description cannot be blank'
+ });
+
+ Self.observe('before save', async function(ctx) {
+ ctx.instance.created = new Date();
+ let token = ctx.options.accessToken;
+ let userId = token && token.userId;
+ ctx.instance.userFk = userId;
+ });
+};
diff --git a/modules/worker/back/models/worker-observation.json b/modules/worker/back/models/worker-observation.json
new file mode 100644
index 000000000..90eb35837
--- /dev/null
+++ b/modules/worker/back/models/worker-observation.json
@@ -0,0 +1,39 @@
+{
+ "name": "WorkerObservation",
+ "base": "VnModel",
+ "options": {
+ "mysql": {
+ "table": "workerObservation"
+ }
+ },
+ "properties": {
+ "id": {
+ "id": true,
+ "type": "number"
+ },
+ "workerFk": {
+ "type": "number"
+ },
+ "userFk": {
+ "type": "number"
+ },
+ "text": {
+ "type": "string"
+ },
+ "created": {
+ "type": "date"
+ }
+ },
+ "relations": {
+ "worker": {
+ "type": "belongsTo",
+ "model": "Worker",
+ "foreignKey": "workerFk"
+ },
+ "user":{
+ "type": "belongsTo",
+ "model": "Account",
+ "foreignKey": "userFk"
+ }
+ }
+}
diff --git a/modules/worker/back/models/worker-time-control-mail.json b/modules/worker/back/models/worker-time-control-mail.json
index 78b99881d..87eae9217 100644
--- a/modules/worker/back/models/worker-time-control-mail.json
+++ b/modules/worker/back/models/worker-time-control-mail.json
@@ -28,6 +28,9 @@
},
"reason": {
"type": "string"
+ },
+ "sendedCounter": {
+ "type": "number"
}
},
"acls": [
diff --git a/modules/worker/back/models/worker-time-control.js b/modules/worker/back/models/worker-time-control.js
index 5b13e17f2..d5da680cf 100644
--- a/modules/worker/back/models/worker-time-control.js
+++ b/modules/worker/back/models/worker-time-control.js
@@ -9,6 +9,7 @@ module.exports = Self => {
require('../methods/worker-time-control/updateWorkerTimeControlMail')(Self);
require('../methods/worker-time-control/weeklyHourRecordEmail')(Self);
require('../methods/worker-time-control/getMailStates')(Self);
+ require('../methods/worker-time-control/resendWeeklyHourEmail')(Self);
Self.rewriteDbError(function(err) {
if (err.code === 'ER_DUP_ENTRY')
diff --git a/modules/worker/front/index.js b/modules/worker/front/index.js
index 657f6a8c6..8fad2c0df 100644
--- a/modules/worker/front/index.js
+++ b/modules/worker/front/index.js
@@ -18,3 +18,6 @@ import './log';
import './dms/index';
import './dms/create';
import './dms/edit';
+import './note/index';
+import './note/create';
+
diff --git a/modules/worker/front/locale/es.yml b/modules/worker/front/locale/es.yml
index b5bcfefa4..a25377122 100644
--- a/modules/worker/front/locale/es.yml
+++ b/modules/worker/front/locale/es.yml
@@ -31,3 +31,5 @@ Deallocate PDA: Desasignar PDA
PDA deallocated: PDA desasignada
PDA allocated: PDA asignada
New PDA: Nueva PDA
+Notes: Notas
+New note: Nueva nota
diff --git a/modules/worker/front/note/create/index.html b/modules/worker/front/note/create/index.html
new file mode 100644
index 000000000..d09fc2da5
--- /dev/null
+++ b/modules/worker/front/note/create/index.html
@@ -0,0 +1,30 @@
+
+
+
\ No newline at end of file
diff --git a/modules/worker/front/note/create/index.js b/modules/worker/front/note/create/index.js
new file mode 100644
index 000000000..81ee247db
--- /dev/null
+++ b/modules/worker/front/note/create/index.js
@@ -0,0 +1,21 @@
+import ngModule from '../../module';
+import Section from 'salix/components/section';
+
+export default class Controller extends Section {
+ constructor($element, $) {
+ super($element, $);
+ this.note = {
+ workerFk: parseInt(this.$params.id),
+ text: null
+ };
+ }
+
+ cancel() {
+ this.$state.go('worker.card.note.index', {id: this.$params.id});
+ }
+}
+
+ngModule.vnComponent('vnNoteWorkerCreate', {
+ template: require('./index.html'),
+ controller: Controller
+});
diff --git a/modules/worker/front/note/create/index.spec.js b/modules/worker/front/note/create/index.spec.js
new file mode 100644
index 000000000..d900c8ee0
--- /dev/null
+++ b/modules/worker/front/note/create/index.spec.js
@@ -0,0 +1,22 @@
+import './index';
+
+describe('Worker', () => {
+ describe('Component vnNoteWorkerCreate', () => {
+ let $state;
+ let controller;
+
+ beforeEach(ngModule('worker'));
+
+ beforeEach(inject(($componentController, _$state_) => {
+ $state = _$state_;
+ $state.params.id = '1234';
+ const $element = angular.element('');
+ controller = $componentController('vnNoteWorkerCreate', {$element, $state});
+ }));
+
+ it('should define workerFk using $state.params.id', () => {
+ expect(controller.note.workerFk).toBe(1234);
+ expect(controller.note.worker).toBe(undefined);
+ });
+ });
+});
diff --git a/modules/worker/front/note/create/locale/es.yml b/modules/worker/front/note/create/locale/es.yml
new file mode 100644
index 000000000..bfe773f48
--- /dev/null
+++ b/modules/worker/front/note/create/locale/es.yml
@@ -0,0 +1,2 @@
+New note: Nueva nota
+Note: Nota
\ No newline at end of file
diff --git a/modules/worker/front/note/index/index.html b/modules/worker/front/note/index/index.html
new file mode 100644
index 000000000..9f5c27008
--- /dev/null
+++ b/modules/worker/front/note/index/index.html
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+ {{::note.user.nickname}}
+ {{::note.created | date:'dd/MM/yyyy HH:mm'}}
+
+
+ {{::note.text}}
+
+
+
+
+
+
+
diff --git a/modules/worker/front/note/index/index.js b/modules/worker/front/note/index/index.js
new file mode 100644
index 000000000..d20971413
--- /dev/null
+++ b/modules/worker/front/note/index/index.js
@@ -0,0 +1,22 @@
+import ngModule from '../../module';
+import Section from 'salix/components/section';
+import './style.scss';
+
+export default class Controller extends Section {
+ constructor($element, $) {
+ super($element, $);
+ this.filter = {
+ order: 'created DESC',
+ };
+ }
+}
+
+Controller.$inject = ['$element', '$scope'];
+
+ngModule.vnComponent('vnWorkerNote', {
+ template: require('./index.html'),
+ controller: Controller,
+ bindings: {
+ worker: '<'
+ }
+});
diff --git a/modules/worker/front/note/index/style.scss b/modules/worker/front/note/index/style.scss
new file mode 100644
index 000000000..5ff6baf4f
--- /dev/null
+++ b/modules/worker/front/note/index/style.scss
@@ -0,0 +1,5 @@
+vn-worker-note {
+ .note:last-child {
+ margin-bottom: 0;
+ }
+}
\ No newline at end of file
diff --git a/modules/worker/front/routes.json b/modules/worker/front/routes.json
index 64b98bfca..64cb186d6 100644
--- a/modules/worker/front/routes.json
+++ b/modules/worker/front/routes.json
@@ -11,6 +11,7 @@
],
"card": [
{"state": "worker.card.basicData", "icon": "settings"},
+ {"state": "worker.card.note.index", "icon": "insert_drive_file"},
{"state": "worker.card.timeControl", "icon": "access_time"},
{"state": "worker.card.calendar", "icon": "icon-calendar"},
{"state": "worker.card.pda", "icon": "phone_android"},
@@ -72,6 +73,24 @@
"component": "vn-worker-log",
"description": "Log",
"acl": ["salesAssistant"]
+ }, {
+ "url": "/note",
+ "state": "worker.card.note",
+ "component": "ui-view",
+ "abstract": true
+ }, {
+ "url": "/index",
+ "state": "worker.card.note.index",
+ "component": "vn-worker-note",
+ "description": "Notes",
+ "params": {
+ "worker": "$ctrl.worker"
+ }
+ }, {
+ "url": "/create",
+ "state": "worker.card.note.create",
+ "component": "vn-note-worker-create",
+ "description": "New note"
}, {
"url": "/pbx",
"state": "worker.card.pbx",
diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html
index bd7e68b89..044ea4038 100644
--- a/modules/worker/front/time-control/index.html
+++ b/modules/worker/front/time-control/index.html
@@ -204,7 +204,7 @@
vn-id="sendEmailConfirmation"
on-accept="$ctrl.resendEmail()"
message="Send time control email">
-
+
Are you sure you want to send it?
diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js
index 9ed454d31..85ddcedfe 100644
--- a/modules/worker/front/time-control/index.js
+++ b/modules/worker/front/time-control/index.js
@@ -303,7 +303,10 @@ class Controller extends Section {
const query = `WorkerTimeControls/${this.worker.id}/addTimeEntry`;
this.$http.post(query, entry)
- .then(() => this.fetchHours());
+ .then(() => {
+ this.fetchHours();
+ this.getMailStates(this.date);
+ });
} catch (e) {
this.vnApp.showError(this.$t(e.message));
return false;
@@ -324,6 +327,7 @@ class Controller extends Section {
this.$http.post(`WorkerTimeControls/${entryId}/deleteTimeEntry`).then(() => {
this.fetchHours();
+ this.getMailStates(this.date);
this.vnApp.showSuccess(this.$t('Entry removed'));
});
}
@@ -395,23 +399,24 @@ class Controller extends Section {
this.$http.post(query, {direction: entry.direction})
.then(() => this.vnApp.showSuccess(this.$t('Data saved!')))
.then(() => this.$.editEntry.hide())
- .then(() => this.fetchHours());
+ .then(() => this.fetchHours())
+ .then(() => this.getMailStates(this.date));
} catch (e) {
this.vnApp.showError(this.$t(e.message));
}
}
resendEmail() {
- const timestamp = this.date.getTime() / 1000;
- const url = `${window.location.origin}/#!/worker/${this.worker.id}/time-control?timestamp=${timestamp}`;
const params = {
recipient: this.worker.user.emailUser.email,
week: this.weekNumber,
year: this.date.getFullYear(),
- url: url,
+ workerId: this.worker.id,
+ state: 'SENDED'
};
this.$http.post(`WorkerTimeControls/weekly-hour-hecord-email`, params)
.then(() => {
+ this.getMailStates(this.date);
this.vnApp.showSuccess(this.$t('Email sended'));
});
}
diff --git a/modules/worker/front/time-control/index.spec.js b/modules/worker/front/time-control/index.spec.js
index 0f9b48f6b..94f9d3d48 100644
--- a/modules/worker/front/time-control/index.spec.js
+++ b/modules/worker/front/time-control/index.spec.js
@@ -120,6 +120,13 @@ describe('Component vnWorkerTimeControl', () => {
describe('save() ', () => {
it(`should make a query an then call to the fetchHours() method`, () => {
+ const today = Date.vnNew();
+
+ jest.spyOn(controller, 'getWeekData').mockReturnThis();
+ jest.spyOn(controller, 'getMailStates').mockReturnThis();
+
+ controller.$.model = {applyFilter: jest.fn().mockReturnValue(Promise.resolve())};
+ controller.date = today;
controller.fetchHours = jest.fn();
controller.selectedRow = {id: 1, timed: Date.vnNew(), direction: 'in'};
controller.$.editEntry = {
@@ -240,7 +247,9 @@ describe('Component vnWorkerTimeControl', () => {
describe('resendEmail() ', () => {
it(`should make a query an then call showSuccess method`, () => {
const today = Date.vnNew();
+
jest.spyOn(controller, 'getWeekData').mockReturnThis();
+ jest.spyOn(controller, 'getMailStates').mockReturnThis();
jest.spyOn(controller.vnApp, 'showSuccess');
controller.$.model = {applyFilter: jest.fn().mockReturnValue(Promise.resolve())};
diff --git a/package.json b/package.json
index 9af083934..5ab8991fc 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "salix-back",
- "version": "23.12.01",
+ "version": "23.14.01",
"author": "Verdnatura Levante SL",
"description": "Salix backend",
"license": "GPL-3.0",
|