Merge pull request '#6273 register freelance' (!2403) from 6273-registerFreelance into dev
gitea/salix/pipeline/head This commit looks good Details

Reviewed-on: #2403
Reviewed-by: Javi Gallego <jgallego@verdnatura.es>
This commit is contained in:
Jorge Penadés 2024-06-10 13:34:50 +00:00
commit 59474a9dfb
4 changed files with 286 additions and 371 deletions

View File

@ -359,10 +359,11 @@
"Select ticket or client": "Elija un ticket o un client",
"It was not able to create the invoice": "No se pudo crear la factura",
"ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)",
"Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE",
"Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE",
"You can not use the same password": "No puedes usar la misma contraseña",
"This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario",
"You can only have one PDA": "Solo puedes tener un PDA",
"It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF",
"It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono"
}
"It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono",
"Payment method is required": "El método de pago es obligatorio"
}

View File

@ -5,108 +5,80 @@ module.exports = Self => {
Self.remoteMethodCtx('new', {
description: 'Creates a new worker and returns the id',
accessType: 'WRITE',
accepts: [
{
arg: 'fi',
type: 'string',
description: `The worker fi`,
required: true,
},
{
arg: 'name',
type: 'string',
description: `The user name`,
required: true,
},
{
arg: 'firstName',
type: 'string',
description: `The worker firstname`,
required: true,
},
{
arg: 'lastNames',
type: 'string',
description: `The worker lastnames`,
required: true,
},
{
arg: 'email',
type: 'string',
description: `The worker email`,
required: true,
},
{
arg: 'street',
type: 'string',
description: `The worker address`,
required: true,
},
{
arg: 'city',
type: 'string',
description: `The worker city`,
required: true,
},
{
arg: 'provinceFk',
type: 'number',
description: `The worker province`,
required: true,
},
{
arg: 'companyFk',
type: 'number',
description: `The worker company`,
required: true,
},
{
arg: 'postcode',
type: 'string',
description: `The worker postcode`,
required: true,
},
{
arg: 'phone',
type: 'string',
description: `The worker phone`,
required: true,
},
{
arg: 'code',
type: 'string',
description: `The worker code`,
required: true,
},
{
arg: 'bossFk',
type: 'number',
description: `The worker boss`,
required: true,
},
{
arg: 'birth',
type: 'date',
description: `The worker birth`,
required: true,
},
{
arg: 'payMethodFk',
type: 'number',
description: `The client payMethod`,
required: true,
},
{
arg: 'iban',
type: 'string',
description: `The client iban`,
},
{
arg: 'bankEntityFk',
type: 'number',
description: `The client bank entity`,
}
],
accepts: [{
arg: 'fi',
type: 'string',
description: `The worker fi`,
}, {
arg: 'name',
type: 'string',
description: `The user name`,
}, {
arg: 'firstName',
type: 'string',
description: `The worker firstname`,
}, {
arg: 'lastNames',
type: 'string',
description: `The worker lastnames`,
}, {
arg: 'email',
type: 'string',
description: `The worker email`,
required: true,
}, {
arg: 'street',
type: 'string',
description: `The worker address`,
}, {
arg: 'city',
type: 'string',
description: `The worker city`,
}, {
arg: 'provinceFk',
type: 'number',
description: `The worker province`,
}, {
arg: 'companyFk',
type: 'number',
description: `The worker company`,
}, {
arg: 'postcode',
type: 'string',
description: `The worker postcode`,
}, {
arg: 'phone',
type: 'string',
description: `The worker phone`,
}, {
arg: 'code',
type: 'string',
description: `The worker code`,
}, {
arg: 'bossFk',
type: 'number',
description: `The worker boss`,
required: true,
}, {
arg: 'birth',
type: 'date',
description: `The worker birth`,
}, {
arg: 'payMethodFk',
type: 'number',
description: `The client payMethod`,
}, {
arg: 'iban',
type: 'string',
description: `The client iban`,
}, {
arg: 'bankEntityFk',
type: 'number',
description: `The client bank entity`,
}, {
arg: 'isFreelance',
type: 'boolean',
}],
returns: {
type: 'number',
root: true,
@ -117,11 +89,30 @@ module.exports = Self => {
},
});
Self.new = async(ctx, options) => {
Self.new = async(
ctx,
fi,
name,
firstName,
lastNames,
email,
street,
city,
provinceFk,
companyFk,
postcode,
phone,
code,
bossFk,
birth,
payMethodFk,
iban,
bankEntityFk,
isFreelance,
options
) => {
const models = Self.app.models;
const myOptions = {userId: ctx.req.accessToken.userId};
const args = ctx.args;
let tx;
if (typeof options == 'object') Object.assign(myOptions, options);
@ -132,132 +123,105 @@ module.exports = Self => {
}
let client;
let user;
try {
client = await models.Client.findOne(
{
where: {fi: args.fi},
},
myOptions
);
client = await models.Client.findOne({where: {fi}}, myOptions);
const nickname = firstName.concat(' ', lastNames);
const {roleFk, businessTypeFk} = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']});
if (!client) {
const nickname = args.firstName.concat(' ', args.lastNames);
const workerConfig = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']});
const [randomPassword] = await models.Worker.rawSql(
'SELECT account.passwordGenerate() as password;'
);
if (!isFreelance && !payMethodFk) throw new UserError('Payment method is required');
const user = await models.VnUser.create(
{
name: args.name,
nickname,
password: randomPassword.password,
email: args.email,
roleFk: workerConfig.roleFk,
},
myOptions
);
if (isFreelance || !client) {
const [{password}] = await models.Worker.rawSql('SELECT account.passwordGenerate() as password;');
const freelancer = isFreelance && await models.VnRole.findOne({fields: ['id'], where: {name: 'freelancer'}});
await models.Account.create(
{
id: user.id,
},
myOptions
);
user = await models.VnUser.create({
name,
nickname,
password,
email,
roleFk: freelancer ? freelancer.id : roleFk,
}, myOptions);
const payMethod = await models.PayMethod.findById(args.payMethodFk, {fields: ['isIbanRequiredForClients']});
if (payMethod.isIbanRequiredForClients && !args.iban)
throw new UserError(`That payment method requires an IBAN`);
await models.Account.create({
id: user.id
}, myOptions);
} else if (client) user = await models.VnUser.findById(client.id, null, myOptions);
await models.Worker.rawSql(
'CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
if (!client && !isFreelance) {
const payMethod = await models.PayMethod.findById(payMethodFk, {fields: ['isIbanRequiredForClients']});
if (payMethod.isIbanRequiredForClients && !iban) throw new UserError('That payment method requires an IBAN');
await models.Worker.rawSql('CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
[
args.firstName,
args.lastNames,
args.fi,
args.street,
args.postcode,
args.city,
args.provinceFk,
args.companyFk,
args.phone,
args.email,
firstName,
lastNames,
fi,
street,
postcode,
city,
provinceFk,
companyFk,
phone,
email,
user.id,
],
myOptions
);
myOptions);
const address = await models.Address.create(
{
clientFk: user.id,
street: args.street,
city: args.city,
provinceFk: args.provinceFk,
postalCode: args.postcode,
mobile: args.phone,
nickname: nickname,
isDefaultAddress: true,
},
myOptions
);
const address = await models.Address.create({
clientFk: user.id,
street: street,
city: city,
provinceFk: provinceFk,
postalCode: postcode,
mobile: phone,
nickname: nickname,
isDefaultAddress: true,
}, myOptions);
client = await models.Client.findById(
user.id,
{fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi']},
myOptions
);
client = await models.Client.findById(user.id, {
fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi']
}, myOptions);
await client.updateAttributes(
{
payMethod: args.payMethod,
iban: args.iban,
bankEntityFk: args.bankEntityFk,
defaultAddressFk: address.id,
businessTypeFk: workerConfig.businessTypeFk,
},
myOptions
);
await client.updateAttributes({
payMethod: payMethodFk,
iban,
bankEntityFk,
defaultAddressFk: address.id,
businessTypeFk,
}, myOptions);
}
const user = await models.VnUser.findById(client.id, null, myOptions);
await user.updateAttribute('email', args.email, myOptions);
await user.updateAttribute('email', email, myOptions);
await models.Worker.create({
id: client.id,
code: args.code,
firstName: args.firstName,
lastName: args.lastNames,
bossFk: args.bossFk,
fi: args.fi,
birth: args.birth,
id: user.id,
firstName,
lastName: lastNames,
code,
bossFk,
fi,
birth,
}, myOptions);
if (tx) await tx.commit();
} catch (error) {
} catch (e) {
if (tx) await tx.rollback();
const code = error.code;
const message = error.sqlMessage;
const code = e.code;
const message = e.sqlMessage;
if (error.message && error.message.includes(`Email already exists`))
throw new UserError(`This personal mail already exists`);
if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`))
throw new UserError(`This worker code already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`))
throw new UserError(`This worker already exists`);
if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`);
throw error;
throw e;
}
await models.VnUser.resetPassword({
email: args.email,
emailTemplate: 'worker-welcome',
id: client.id
});
await models.VnUser.resetPassword({email, emailTemplate: 'worker-welcome', id: user.id});
return {id: client.id};
return {id: user.id};
};
};

View File

@ -1,189 +1,114 @@
const models = require('vn-loopback/server/server').models;
const {models} = require('vn-loopback/server/server');
const LoopBackContext = require('loopback-context');
describe('Worker new', () => {
beforeAll(async() => {
const activeCtx = {
accessToken: {userId: 9},
http: {
req: {
headers: {origin: 'http://localhost'}
}
}
};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({
active: activeCtx
});
});
const developerId = 9;
const employeeId = 1;
const defaultWorker = {
fi: '78457139E',
name: 'defaulterworker',
firstName: 'DEFAULT',
lastNames: 'WORKER',
email: 'defaultWorker@mydomain.com',
street: 'S/ DEFAULTWORKERSTREET',
city: 'defaultWorkerCity',
provinceFk: 1,
companyFk: 442,
postcode: '46680',
phone: '123456789',
code: 'DWW',
bossFk: 9,
birth: '2022-12-11T23:00:00.000Z',
payMethodFk: 1,
roleFk: 1
};
const bruceWayneId = 1101;
const accessToken = {accessToken: {userId: developerId}};
const ctx = {req: accessToken};
let tx;
let opts;
const req = {accessToken: {userId: 9}};
it('should return error if personal mail already exists', async() => {
const user = await models.VnUser.findById(employeeId, {fields: ['email']});
const tx = await models.Worker.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const ctx = {
args: Object.assign({}, defaultWorker, {email: user.email}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) {
error = e;
await tx.rollback();
}
expect(error.message).toEqual('This personal mail already exists');
beforeAll(async() => {
const activeCtx = {accessToken, http: {req: {headers: {origin: 'http://localhost'}}}};
spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: activeCtx});
});
it('should return error if worker code already exists', async() => {
const worker = await models.Worker.findById(employeeId, {fields: ['code']});
const tx = await models.Worker.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const ctx = {
args: Object.assign({}, defaultWorker, {code: worker.code}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) {
error = e;
await tx.rollback();
}
expect(error.message).toEqual('This worker code already exists');
});
it('should return error if worker already exists', async() => {
const worker = await models.Client.findById(employeeId, {fields: ['fi']});
const tx = await models.Worker.beginTransaction({});
let error;
try {
const options = {transaction: tx};
const ctx = {
args: Object.assign({}, defaultWorker, {fi: worker.fi}),
req
};
await models.Worker.new(ctx, options);
await tx.rollback();
} catch (e) {
error = e;
await tx.rollback();
}
expect(error.message).toEqual('This worker already exists');
});
it('should return error if payMethod require iban', async() => {
const payMethodIbanRequired = await models.PayMethod.findOne({
where: {
isIbanRequiredForClients: true
},
fields: ['id']
describe('should return error', () => {
beforeEach(async() => {
tx = await models.Worker.beginTransaction({});
opts = {transaction: tx};
});
const tx = await models.Worker.beginTransaction({});
afterEach(async() => await tx.rollback());
let error;
try {
const options = {transaction: tx};
const ctx = {
args: Object.assign({}, defaultWorker, {payMethodFk: payMethodIbanRequired.id}),
req
};
await models.Worker.new(ctx, options);
it('if personal mail already exists', async() => {
const user = await models.VnUser.findById(employeeId, {fields: ['email']});
try {
await createWorker(ctx, opts, {email: user.email});
} catch (e) {
expect(e.message).toEqual('This personal mail already exists');
}
});
await tx.rollback();
} catch (e) {
error = e;
await tx.rollback();
}
it('if worker code already exists', async() => {
const worker = await models.Worker.findById(employeeId, {fields: ['code']});
try {
await createWorker(ctx, opts, {code: worker.code});
} catch (e) {
expect(e.message).toEqual('This worker code already exists');
}
});
expect(error.message).toEqual('That payment method requires an IBAN');
it('if worker already exists', async() => {
const worker = await models.Client.findById(employeeId, {fields: ['fi']});
try {
await createWorker(ctx, opts, {fi: worker.fi});
} catch (e) {
expect(e.message).toEqual('This worker already exists');
}
});
it('if payMethod require iban', async() => {
const payMethodIbanRequired = await models.PayMethod.findOne({
fields: ['id'], where: {isIbanRequiredForClients: true}
});
try {
await createWorker(ctx, opts, {payMethodFk: payMethodIbanRequired.id});
} catch (e) {
expect(e.message).toEqual('That payment method requires an IBAN');
}
});
});
it('should create a new worker', async() => {
let newWorker;
try {
newWorker = await models.Worker.new({args: defaultWorker, req});
newWorker = await createWorker(ctx);
expect(newWorker.id).toBeDefined();
} finally {
await removeWorker(newWorker.id);
}
expect(newWorker.id).toBeDefined();
});
it('should create a new client', async() => {
let newWorker;
let client;
try {
newWorker = await models.Worker.new({args: defaultWorker, req});
client = await models.Client.findById(newWorker.id);
newWorker = await createWorker(ctx);
let client = await models.Client.findById(newWorker.id);
expect(client).toBeDefined();
} finally {
await removeWorker(newWorker.id);
}
expect(client).toBeDefined();
});
it('should create a new worker in client', async() => {
const bruceWayneId = 1101;
const client = await models.Client.findById(bruceWayneId, {fields: ['fi', 'email']});
const newWorkerData = {
args: Object.assign(
{},
defaultWorker,
{
fi: client.fi,
email: client.email
}),
req
};
let newWorker;
try {
newWorker = await models.Worker.new(newWorkerData);
newWorker = await createWorker(ctx, undefined, {fi: client.fi, email: client.email});
expect(newWorker.id).toEqual(bruceWayneId);
} finally {
await models.Worker.destroyById(newWorker.id);
}
});
expect(newWorker.id).toEqual(bruceWayneId);
it('should create a new external worker', async() => {
let newWorker;
try {
newWorker = await createWorker(ctx, undefined, {isFreelance: true});
const client = await models.Client.findById(newWorker.id);
expect(newWorker.id).toBeDefined();
expect(client).toBeNull();
} finally {
await removeWorker(newWorker.id);
}
});
});
@ -194,3 +119,28 @@ async function removeWorker(id) {
await models.Client.destroyById(id);
await models.VnUser.destroyById(id);
}
async function createWorker(ctx, opts = undefined, params = {}) {
return models.Worker.new(
ctx,
params.fi ?? '78457139E',
params.name ?? 'defaulterworker',
params.firstName ?? 'DEFAULT',
params.lastNames ?? 'WORKER',
params.email ?? 'defaultWorker@mydomain.com',
params.street ?? 'S/ DEFAULTWORKERSTREET',
params.city ?? 'defaultWorkerCity',
params.provinceFk ?? 1,
params.companyFk ?? 442,
params.postcode ?? '46680',
params.phone ?? '123456789',
params.code ?? 'DWW',
params.bossFk ?? 9,
params.birth ?? '2022-12-11T23:00:00.000Z',
params.payMethodFk ?? 1,
undefined,
undefined,
params.isFreelance ?? false,
opts
);
}

View File

@ -25,43 +25,44 @@
"required": true
},
"phone": {
"type" : "string"
"type": "string"
},
"bossFk": {
"type" : "number"
"type": "number"
},
"maritalStatus": {
"type" : "string"
"type": "string"
},
"originCountryFk": {
"type" : "number"
"type": "number"
},
"educationLevelFk": {
"type" : "number"
"type": "number"
},
"SSN": {
"type" : "string"
"type": "string"
},
"mobileExtension": {
"type" : "number"
"type": "number"
},
"code": {
"type" : "string"
"type": "string",
"required": true
},
"fi": {
"type" : "string"
"type": "string"
},
"birth": {
"type" : "date"
"type": "date"
},
"isF11Allowed": {
"type" : "boolean"
"type": "boolean"
},
"sex": {
"type" : "string"
"type": "string"
},
"isFreelance": {
"type" : "boolean"
"type": "boolean"
},
"fiDueDate": {
"type": "date"
@ -78,7 +79,6 @@
"isSsDiscounted": {
"type": "boolean"
}
},
"relations": {
"user": {
@ -117,7 +117,7 @@
"foreignKey": "workerFk"
}
},
"acls":[
"acls": [
{
"property": "__get__locker",
"accessType": "READ",
@ -126,4 +126,4 @@
"principalId": "$owner"
}
]
}
}