Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix into 2014-remove_bi_from_db
gitea/salix/2014-remove_bi_from_db This commit looks good Details

This commit is contained in:
Bernat Exposito Domenech 2020-01-23 12:58:47 +01:00
commit 6700daf0e3
27 changed files with 649 additions and 55 deletions

View File

@ -22,8 +22,10 @@ module.exports = Self => {
Self.removeFile = async(ctx, id) => {
const models = Self.app.models;
const trashDmsType = await models.DmsType.findOne({where: {code: 'trash'}});
const dms = await models.Dms.findById(id);
const trashDmsType = await models.DmsType.findOne({
where: {code: 'trash'}
});
const hasWriteRole = await models.DmsType.hasWriteRole(ctx, dms.dmsTypeFk);
if (!hasWriteRole)

View File

@ -3,6 +3,9 @@
"name": "Dms",
"description": "Documental Managment system",
"base": "VnModel",
"log": {
"showField": "reference"
},
"options": {
"mysql": {
"table": "dms"

View File

@ -0,0 +1,7 @@
ALTER TABLE `vn`.`travelThermograph`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`id`);
ALTER TABLE `vn`.`travelThermograph`
ADD UNIQUE INDEX `thermograph_created` (`thermographFk` ASC, `created` ASC) VISIBLE;

View File

@ -1950,11 +1950,14 @@ INSERT INTO `vn`.`thermograph`(`id`, `model`)
VALUES
('TMM190901395', 'TEMPMATE'),
('TL.BBA85422', 'TL30'),
('TZ1905012010', 'DISPOSABLE');
('TZ1905012010', 'DISPOSABLE'),
('138350-0', 'DISPOSABLE');
INSERT INTO `vn`.`travelThermograph`(`thermographFk`, `created`, `warehouseFk`, `travelFk`, `temperature`, `result`, `dmsFk`)
VALUES
('TMM190901395', CURDATE(), 1, 1, 'WARM', 'Ok', NULL),
('TL.BBA85422', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 2, 2, 'COOL', 'Ok', NULL),
('TL.BBA85422', CURDATE(), 2, 1, 'COOL', 'can not read the temperature', NULL),
('TZ1905012010', CURDATE(), 1, 1, 'WARM', 'Temperature in range', 5);
('TMM190901395', CURDATE(), 1, 1, 'WARM', 'Ok', NULL),
('TL.BBA85422', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 2, 2, 'COOL', 'Ok', NULL),
('TL.BBA85422', CURDATE(), 2, 1, 'COOL', 'can not read the temperature', NULL),
('TZ1905012010', CURDATE(), 1, 1, 'WARM', 'Temperature in range', 5),
('138350-0', DATE_ADD(CURDATE(), INTERVAL -1 MONTH), 1, 1, 'WARM', NULL, 5),
('138350-0', CURDATE(), 1, NULL, 'COOL', NULL, NULL);

View File

@ -219,7 +219,7 @@ module.exports = function(Self) {
userFk: userFk,
action: action,
changedModel: ctx.Model.definition.name,
changedModelId: changedModelId,
changedModelId: changedModelId, // Model property with an different data type will throw a NaN error
changedModelValue: where,
oldInstance: oldInstance,
newInstance: newInstance

View File

@ -206,9 +206,9 @@ describe('claim', () => {
return resolve({id: freightPickUpPrice});
}));
controller.onUpdateGreugeResponse('accept').then(res => {
console.log('asdas');
}).catch(error => {
console.log('errorrrr!!');
});
$httpBackend.flush();

View File

@ -0,0 +1,23 @@
module.exports = Self => {
Self.remoteMethodCtx('allowedContentTypes', {
description: 'Returns a list of allowed contentTypes',
accessType: 'READ',
returns: {
type: ['Object'],
root: true
},
http: {
path: `/allowedContentTypes`,
verb: 'GET'
}
});
Self.allowedContentTypes = async() => {
const storageConnector = Self.app.dataSources.storage.connector;
const allowedContentTypes = storageConnector.allowedContentTypes;
const modelAllowedContentTypes = Self.definition.settings.allowedContentTypes;
return modelAllowedContentTypes || allowedContentTypes;
};
};

View File

@ -0,0 +1,84 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('createThermograph', {
description: 'Upload and attach a document',
accessType: 'WRITE',
accepts: [{
arg: 'id',
type: 'Number',
description: 'The travel id',
http: {source: 'path'}
}, {
arg: 'thermographId',
type: 'String',
description: 'The thermograph id',
required: true
}, {
arg: 'warehouseId',
type: 'Number',
description: 'The warehouse id',
required: true
}, {
arg: 'companyId',
type: 'Number',
description: 'The company id',
required: true
}, {
arg: 'dmsTypeId',
type: 'Number',
description: 'The dms type id',
required: true
}, {
arg: 'reference',
type: 'String',
required: true
}, {
arg: 'description',
type: 'String',
required: true
}],
returns: {
type: 'Object',
root: true
},
http: {
path: `/:id/createThermograph`,
verb: 'POST'
}
});
Self.createThermograph = async(ctx, id, thermographId) => {
const models = Self.app.models;
const tx = await Self.beginTransaction({});
try {
const options = {transaction: tx};
const travelThermograph = await models.TravelThermograph.findOne({
where: {
thermographFk: thermographId,
travelFk: null
}
}, options);
if (!travelThermograph)
throw new UserError('No valid travel thermograph found');
const uploadedFiles = await models.Dms.uploadFile(ctx, options);
const firstDms = uploadedFiles[0];
await travelThermograph.updateAttributes({
dmsFk: firstDms.id,
travelFk: id
}, options);
await tx.commit();
return travelThermograph;
} catch (err) {
await tx.rollback();
throw err;
}
};
};

View File

@ -0,0 +1,53 @@
module.exports = Self => {
Self.remoteMethodCtx('deleteThermograph', {
description: 'Deletes a travel thermograph',
accessType: 'WRITE',
accepts: {
arg: 'id',
type: 'Number',
description: 'The thermograph id',
required: true
},
returns: {
type: 'object',
root: true
},
http: {
path: '/deleteThermograph',
verb: 'DELETE'
}
});
Self.deleteThermograph = async(ctx, id) => {
const models = Self.app.models;
const userId = ctx.req.accessToken.userId;
const travelThermograph = await models.TravelThermograph.findById(id);
await models.Dms.removeFile(ctx, travelThermograph.dmsFk);
await Self.rawSql(`
UPDATE travelThermograph
SET travelFk = NULL, dmsFk = NULL
WHERE id = ?`, [id]);
const oldInstance = {
travelFk: travelThermograph.travelFk,
dmsFk: travelThermograph.dmsFk
};
await models.TravelLog.create({
originFk: travelThermograph.travelFk,
userFk: userId,
action: 'delete',
changedModel: 'TravelThermograph',
changedModelId: id,
oldInstance: oldInstance,
newInstance: {}
});
travelThermograph.travelFk = null;
travelThermograph.dmsFk = null;
return travelThermograph;
};
};

View File

@ -0,0 +1,50 @@
const app = require('vn-loopback/server/server');
describe('Travel createThermograph()', () => {
const models = app.models;
const travelId = 3;
const currentUserId = 102;
const thermographId = '138350-0';
const ctx = {req: {accessToken: {userId: currentUserId}}, args: {dmsTypeId: 1}};
let travelThermographBefore;
afterAll(async done => {
await app.models.TravelThermograph.rawSql(`
UPDATE travelThermograph
SET travelFk = NULL, dmsFk = NULL
WHERE id = ?`, [travelThermographBefore.id]);
done();
});
it(`should set the travelFk and dmsFk properties to the travel thermograph`, async() => {
spyOn(app.models.Dms, 'uploadFile').and.returnValue([{id: 5}]);
travelThermographBefore = await models.TravelThermograph.findOne({
where: {
thermographFk: thermographId,
travelFk: null
}
});
await models.Travel.createThermograph(ctx, travelId, thermographId);
const travelThermographAfter = await models.TravelThermograph.findOne({
where: {
thermographFk: thermographId,
travelFk: travelId
}
});
expect(app.models.Dms.uploadFile).toHaveBeenCalledWith(ctx, jasmine.any(Object));
expect(travelThermographBefore).toBeDefined();
expect(travelThermographBefore.thermographFk).toEqual(thermographId);
expect(travelThermographBefore.travelFk).toBeNull();
expect(travelThermographAfter).toBeDefined();
expect(travelThermographAfter.thermographFk).toEqual(thermographId);
expect(travelThermographAfter.travelFk).toEqual(travelId);
expect(travelThermographAfter.dmsFk).toEqual(5);
});
});

View File

@ -0,0 +1,56 @@
const app = require('vn-loopback/server/server');
describe('Travel deleteThermograph()', () => {
const models = app.models;
const travelId = 1;
const currentUserId = 102;
const thermographId = 'TZ1905012010';
const travelThermographId = 4;
const dmsId = 5;
const ctx = {req: {accessToken: {userId: currentUserId}}};
let travelThermographBefore;
afterAll(async done => {
await app.models.TravelThermograph.rawSql(`
UPDATE travelThermograph
SET travelFk = ?, dmsFk = ?
WHERE id = ?`, [
travelThermographBefore.travelFk,
travelThermographBefore.dmsFk,
travelThermographBefore.id
]);
done();
});
it(`should set the travelFk and dmsFk properties to null for travel thermograph removal`, async() => {
spyOn(app.models.Dms, 'removeFile').and.returnValue([{id: 5}]);
travelThermographBefore = await models.TravelThermograph.findOne({
where: {
thermographFk: thermographId,
travelFk: travelId
}
});
await models.Travel.deleteThermograph(ctx, travelThermographId);
const travelThermographAfter = await models.TravelThermograph.findOne({
where: {
thermographFk: thermographId,
travelFk: null
}
});
expect(app.models.Dms.removeFile).toHaveBeenCalledWith(ctx, dmsId);
expect(travelThermographBefore).toBeDefined();
expect(travelThermographBefore.thermographFk).toEqual(thermographId);
expect(travelThermographBefore.travelFk).toEqual(travelId);
expect(travelThermographBefore.dmsFk).toEqual(5);
expect(travelThermographAfter).toBeDefined();
expect(travelThermographAfter.thermographFk).toEqual(thermographId);
expect(travelThermographAfter.travelFk).toBeNull();
});
});

View File

@ -36,7 +36,7 @@
"type": "Date"
},
"changedModelId": {
"type": "Number"
"type": "String"
},
"changedModelValue": {
"type": "String"

View File

@ -0,0 +1,4 @@
module.exports = Self => {
require('../methods/travel-thermograph/allowedContentTypes')(Self);
};

View File

@ -2,7 +2,9 @@
"name": "TravelThermograph",
"base": "Loggable",
"log": {
"model":"TravelLog"
"model":"TravelLog",
"relation": "travel",
"showField": "ref"
},
"options": {
"mysql": {
@ -10,15 +12,13 @@
}
},
"properties": {
"thermographFk": {
"type": "String",
"id": 1,
"description": "Identifier"
"id": {
"type": "Number",
"description": "Identifier",
"id": true
},
"created": {
"type": "Date",
"id": 2,
"description": "Identifier"
"type": "Date"
},
"temperature": {
"type": "String"

View File

@ -2,4 +2,6 @@ module.exports = Self => {
require('../methods/travel/getTravel')(Self);
require('../methods/travel/getEntries')(Self);
require('../methods/travel/filter')(Self);
require('../methods/travel/createThermograph')(Self);
require('../methods/travel/deleteThermograph')(Self);
};

View File

@ -2,7 +2,8 @@
"name": "Travel",
"base": "Loggable",
"log": {
"model":"TravelLog"
"model":"TravelLog",
"showField": "ref"
},
"options": {
"mysql": {

View File

@ -9,5 +9,6 @@ import './summary';
import './basic-data';
import './log';
import './create';
import './thermograph';
import './thermograph/index/';
import './thermograph/create/';

View File

@ -16,4 +16,4 @@ New travel: Nuevo envío
# Sections
Travels: Envíos
Log: Historial
Thermographs: Termómetros
Thermographs: Termógrafos

View File

@ -11,7 +11,7 @@
"card": [
{"state": "travel.card.basicData", "icon": "settings"},
{"state": "travel.card.log", "icon": "history"},
{"state": "travel.card.thermograph", "icon": "icon-thermometer"}
{"state": "travel.card.thermograph.index", "icon": "icon-thermometer"}
]
},
"routes": [
@ -59,14 +59,28 @@
"component": "vn-travel-create",
"description": "New travel"
}, {
"url" : "/thermograph",
"url": "/thermograph",
"state": "travel.card.thermograph",
"component": "vn-travel-thermograph",
"abstract": true,
"component": "ui-view"
}, {
"url" : "/index",
"state": "travel.card.thermograph.index",
"component": "vn-travel-thermograph-index",
"description": "Thermographs",
"params": {
"travel": "$ctrl.travel"
},
"acl": ["buyer"]
}, {
"url" : "/create",
"state": "travel.card.thermograph.create",
"component": "vn-travel-thermograph-create",
"description": "Add thermograph",
"params": {
"travel": "$ctrl.travel"
},
"acl": ["buyer"]
}
]
}

View File

@ -0,0 +1,79 @@
<vn-watcher
vn-id="watcher"
data="$ctrl.dms">
</vn-watcher>
<form
name="form"
ng-submit="$ctrl.onSubmit()"
class="vn-ma-md"
enctype="multipart/form-data">
<div class="vn-w-md">
<vn-card class="vn-pa-lg">
<vn-horizontal>
<vn-autocomplete vn-one
label="Company"
ng-model="$ctrl.dms.companyId"
url="Companies"
show-field="code"
value-field="id">
</vn-autocomplete>
<vn-autocomplete vn-one
label="Warehouse"
ng-model="$ctrl.dms.warehouseId"
url="Warehouses"
show-field="name"
value-field="id">
</vn-autocomplete>
</vn-horizontal>
<vn-horizontal>
<vn-autocomplete vn-one
label="Type"
ng-model="$ctrl.dms.dmsTypeId"
url="DmsTypes"
show-field="name"
value-field="id">
</vn-autocomplete>
<vn-textfield vn-one
label="Reference"
ng-model="$ctrl.dms.reference"
rule>
</vn-textfield>
<vn-autocomplete vn-one
label="Thermograph"
ng-model="$ctrl.dms.thermographId"
url="TravelThermographs"
where="{travelFk: null}"
show-field="thermographFk"
value-field="thermographFk">
</vn-autocomplete>
</vn-horizontal>
<vn-horizontal>
<vn-textarea vn-one vn-focus
label="Description"
ng-model="$ctrl.dms.description"
rule>
</vn-textarea>
</vn-horizontal>
<vn-horizontal>
<vn-input-file
vn-one
label="File"
ng-model="$ctrl.dms.files"
accept="{{$ctrl.allowedContentTypes}}"
multiple="true">
<append>
<vn-icon vn-none
color-marginal
title="{{$ctrl.contentTypesInfo}}"
icon="info">
</vn-icon>
</append>
</vn-input-file>
</vn-horizontal>
</vn-card>
<vn-button-bar>
<vn-submit label="Upload"></vn-submit>
<vn-button ui-sref="travel.card.thermograph.index" label="Cancel"></vn-button>
</vn-button-bar>
</div>
</form>

View File

@ -0,0 +1,97 @@
import ngModule from '../../module';
class Controller {
constructor($scope, $http, $state, $translate, vnApp, vnConfig) {
this.$ = $scope;
this.$http = $http;
this.$state = $state;
this.$translate = $translate;
this.vnApp = vnApp;
this.vnConfig = vnConfig;
this.dms = {files: []};
}
get travel() {
return this._travel;
}
set travel(value) {
this._travel = value;
if (value) {
this.setDefaultParams();
this.getAllowedContentTypes();
}
}
getAllowedContentTypes() {
this.$http.get('TravelThermographs/allowedContentTypes').then(res => {
const contentTypes = res.data.join(', ');
this.allowedContentTypes = contentTypes;
});
}
get contentTypesInfo() {
return this.$translate.instant('ContentTypesInfo', {
allowedContentTypes: this.allowedContentTypes
});
}
setDefaultParams() {
const params = {filter: {
where: {code: 'miscellaneous'}
}};
this.$http.get('DmsTypes/findOne', {params}).then(res => {
const dmsTypeId = res.data && res.data.id;
const companyId = this.vnConfig.companyFk;
const warehouseId = this.vnConfig.warehouseFk;
const defaultParams = {
reference: this.travel.id,
warehouseId: warehouseId,
companyId: companyId,
dmsTypeId: dmsTypeId,
description: this.$translate.instant('FileDescription', {
travelId: this.travel.id
}).toUpperCase()
};
this.dms = Object.assign(this.dms, defaultParams);
});
}
onSubmit() {
const query = `Travels/${this.travel.id}/createThermograph`;
const options = {
method: 'POST',
url: query,
params: this.dms,
headers: {
'Content-Type': undefined
},
transformRequest: files => {
const formData = new FormData();
for (let i = 0; i < files.length; i++)
formData.append(files[i].name, files[i]);
return formData;
},
data: this.dms.files
};
this.$http(options).then(res => {
this.vnApp.showSuccess(this.$translate.instant('Data saved!'));
this.$.watcher.updateOriginalData();
this.$state.go('travel.card.thermograph.index');
});
}
}
Controller.$inject = ['$scope', '$http', '$state', '$translate', 'vnApp', 'vnConfig'];
ngModule.component('vnTravelThermographCreate', {
template: require('./index.html'),
controller: Controller,
bindings: {
travel: '<'
}
});

View File

@ -0,0 +1,68 @@
import './index';
describe('Ticket', () => {
describe('Component vnTravelThermographCreate', () => {
let controller;
let $scope;
let $httpBackend;
let $httpParamSerializer;
const travelId = 3;
const dmsTypeId = 5;
beforeEach(ngModule('travel'));
beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => {
$scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
$httpParamSerializer = _$httpParamSerializer_;
controller = $componentController('vnTravelThermographCreate', {$scope});
controller._travel = {
id: travelId
};
}));
describe('travel() setter', () => {
it('should set the travel data and then call setDefaultParams() and getAllowedContentTypes()', () => {
spyOn(controller, 'setDefaultParams');
spyOn(controller, 'getAllowedContentTypes');
controller.travel = {
id: travelId
};
expect(controller.travel).toBeDefined();
expect(controller.setDefaultParams).toHaveBeenCalledWith();
expect(controller.getAllowedContentTypes).toHaveBeenCalledWith();
});
});
describe('setDefaultParams()', () => {
it('should perform a GET query and define the dms property on controller', () => {
const params = {filter: {
where: {code: 'miscellaneous'}
}};
let serializedParams = $httpParamSerializer(params);
$httpBackend.when('GET', `DmsTypes/findOne?${serializedParams}`).respond({id: dmsTypeId, code: 'miscellaneous'});
$httpBackend.expect('GET', `DmsTypes/findOne?${serializedParams}`);
controller.setDefaultParams();
$httpBackend.flush();
expect(controller.dms).toBeDefined();
expect(controller.dms.reference).toEqual(travelId);
expect(controller.dms.dmsTypeId).toEqual(dmsTypeId);
});
});
describe('getAllowedContentTypes()', () => {
it('should make an HTTP GET request to get the allowed content types', () => {
const expectedResponse = ['application/pdf', 'image/png', 'image/jpg'];
$httpBackend.when('GET', `TravelThermographs/allowedContentTypes`).respond(expectedResponse);
$httpBackend.expect('GET', `TravelThermographs/allowedContentTypes`);
controller.getAllowedContentTypes();
$httpBackend.flush();
expect(controller.allowedContentTypes).toBeDefined();
expect(controller.allowedContentTypes).toEqual('application/pdf, image/png, image/jpg');
});
});
});
});

View File

@ -1,28 +0,0 @@
import ngModule from '../module';
import './style.scss';
import Component from 'core/lib/component';
class Controller extends Component {
constructor($element, $) {
super($element, $);
this.filter = {
include:
{relation: 'warehouse',
scope: {
fields: ['id', 'name']
}
}
};
}
}
ngModule.component('vnTravelThermograph', {
template: require('./index.html'),
controller: Controller,
require: {
card: '^vnTravelCard'
},
bindings: {
travel: '<'
}
});

View File

@ -28,6 +28,15 @@
<vn-td expand>{{thermograph.result}}</vn-td>
<vn-td>{{thermograph.warehouse.name}}</vn-td>
<vn-td>{{thermograph.created | date: 'dd/MM/yyyy'}}</vn-td>
<vn-td shrink>
<a target="_blank"
href="api/dms/{{::thermograph.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}">
<vn-icon-button
icon="cloud_download"
title="{{'Download file' | translate}}">
</vn-icon-button>
</a>
</vn-td>
<vn-td shrink>
<vn-icon-button
icon="delete"
@ -45,6 +54,14 @@
<vn-confirm
vn-id="confirm"
question="Delete thermograph from travel?"
on-response="$ctrl.removeThermographFromTravel($response)">
question="Are you sure you want to remove the thermograph?"
on-accept="$ctrl.deleteThermograph()">
</vn-confirm>
<a
ui-sref="travel.card.thermograph.create"
vn-tooltip="Add thermograph"
vn-bind="+"
fixed-bottom-right>
<vn-float-button icon="add"></vn-float-button>
</a>

View File

@ -0,0 +1,47 @@
import ngModule from '../../module';
import './style.scss';
import Component from 'core/lib/component';
class Controller extends Component {
constructor($element, $, vnToken) {
super($element, $);
this.accessToken = vnToken.token;
this.filter = {
include:
{relation: 'warehouse',
scope: {
fields: ['id', 'name']
}
}
};
}
showDeleteConfirm(index) {
this.thermographIndex = index;
this.$.confirm.show();
}
deleteThermograph() {
const data = this.travelThermographs;
const thermographId = data[this.thermographIndex].id;
const query = `Travels/deleteThermograph?id=${thermographId}`;
this.$http.delete(query).then(() => {
this.vnApp.showSuccess(this.$translate.instant('Thermograph deleted'));
this.$.model.remove(this.thermographIndex);
this.thermographIndex = null;
});
}
}
Controller.$inject = ['$element', '$scope', 'vnToken'];
ngModule.component('vnTravelThermographIndex', {
template: require('./index.html'),
controller: Controller,
require: {
card: '^vnTravelCard'
},
bindings: {
travel: '<'
}
});

View File

@ -3,4 +3,15 @@ Temperature: Temperatura
State: Estado
Destination: Destino
Created: Creado
Remove thermograph: Eliminar termómetro
Remove thermograph: Eliminar termógrafo
Upload file: Subir fichero
Edit file: Editar fichero
Upload: Subir
File: Fichero
FileDescription: Travel id {{travelId}}
ContentTypesInfo: 'Tipos de archivo permitidos: {{allowedContentTypes}}'
Are you sure you want to continue?: ¿Seguro que quieres continuar?
Add thermograph: Añadir termógrafo
Thermograph deleted: Termógrafo eliminado
Thermograph: Termógrafo
Are you sure you want to remove the thermograph?: ¿Seguro que quieres quitar el termógrafo?