2018-04-18 12:37:17 +00:00
|
|
|
let UserError = require('../../helpers').UserError;
|
2018-02-22 12:40:23 +00:00
|
|
|
|
|
|
|
module.exports = Self => {
|
|
|
|
Self.remoteMethod('clone', {
|
|
|
|
description: 'clone item',
|
|
|
|
accessType: 'WRITE',
|
|
|
|
accepts: [{
|
|
|
|
arg: 'id',
|
|
|
|
type: 'number',
|
|
|
|
required: true,
|
|
|
|
description: 'origin itemId',
|
|
|
|
http: {source: 'path'}
|
|
|
|
}],
|
|
|
|
returns: {
|
|
|
|
arg: 'id',
|
|
|
|
description: 'new cloned itemId'
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/:id/clone`,
|
|
|
|
verb: 'post'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2018-03-13 13:46:39 +00:00
|
|
|
Self.clone = async itemId => {
|
2018-02-22 12:40:23 +00:00
|
|
|
let filter = {
|
|
|
|
where: {
|
|
|
|
id: itemId
|
|
|
|
},
|
|
|
|
include: [
|
2018-04-26 14:41:08 +00:00
|
|
|
{relation: 'tags', scope: {order: 'priority ASC', include: {relation: 'tag'}}}
|
2018-02-22 12:40:23 +00:00
|
|
|
]
|
|
|
|
};
|
2018-03-13 13:46:39 +00:00
|
|
|
|
2018-02-22 12:40:23 +00:00
|
|
|
try {
|
|
|
|
let origin = await Self.findOne(filter);
|
|
|
|
let copy = JSON.parse(JSON.stringify(origin));
|
|
|
|
|
|
|
|
delete copy.id;
|
|
|
|
delete copy.itemTag;
|
2018-05-16 11:02:19 +00:00
|
|
|
delete copy.description;
|
2018-02-22 12:40:23 +00:00
|
|
|
|
|
|
|
let newItem = await Self.create(copy);
|
|
|
|
let promises = [];
|
|
|
|
|
|
|
|
let createBotanical = `INSERT INTO vn.itemBotanical (itemFk, botanical, genusFk, specieFk)
|
|
|
|
SELECT ?, botanical, genusFk, specieFk
|
|
|
|
FROM vn.itemBotanical ib WHERE itemFk = ?`;
|
|
|
|
promises.push(Self.rawSql(createBotanical, [newItem.id, origin.id]));
|
|
|
|
|
2018-06-05 06:24:53 +00:00
|
|
|
let createTags = `INSERT INTO vn.itemTag(itemFk, tagFk, value, priority)
|
|
|
|
SELECT ?, i.tagFk, i.value,i.priority
|
|
|
|
FROM vn.itemTag i WHERE i.itemFk = ?
|
|
|
|
ON DUPLICATE KEY UPDATE value = i.value, priority = i.priority`;
|
2018-02-22 12:40:23 +00:00
|
|
|
promises.push(Self.rawSql(createTags, [newItem.id, origin.id]));
|
|
|
|
|
2018-05-15 12:02:16 +00:00
|
|
|
let createTax = `REPLACE INTO vn.itemTaxCountry (itemFk, countryFk, taxClassFk)
|
|
|
|
SELECT ?, countryFk, taxClassFk
|
|
|
|
FROM vn.itemTaxCountry WHERE itemFk = ?`;
|
|
|
|
promises.push(Self.rawSql(createTax, [newItem.id, origin.id]));
|
|
|
|
|
2018-02-22 12:40:23 +00:00
|
|
|
await Promise.all(promises);
|
|
|
|
return newItem.id;
|
|
|
|
} catch (err) {
|
|
|
|
throw new UserError(err);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|