diff --git a/src/api/extensions/budsies/index.js b/src/api/extensions/budsies/index.js index 3c03859e..a464bcdd 100644 --- a/src/api/extensions/budsies/index.js +++ b/src/api/extensions/budsies/index.js @@ -3,6 +3,8 @@ import { apiStatus, getToken } from '../../../lib/util'; import { Router } from 'express'; import { multiStoreConfig } from '../../../platform/magento1/util'; import { getClient } from '../../../lib/elastic'; +import PlatformFactory from '../../../platform/factory'; +import { updateUserAddresses } from '../../user.ts'; const Magento1Client = require('magento1-vsbridge-client').Magento1Client const Magento2Client = require('magento2-rest-client').Magento2Client @@ -19,6 +21,12 @@ module.exports = ({ config, db }) => { return false; } + const _getUserProxy = (req) => { + const platform = config.platform + const factory = new PlatformFactory(config, req) + return factory.getAdapter(platform, 'user') + }; + let budsiesApi = Router(); let bridgeRequestsCache = BridgeRequestsCache({ db }) @@ -231,7 +239,7 @@ module.exports = ({ config, db }) => { let data = await restClient.get(url, customerToken); if (data) { - data = {'storeRating': data[0]}; + data = { 'storeRating': data[0] }; await bridgeRequestsCache.setWithTtl(cacheKey, data, 300); } else { await bridgeRequestsCache.del(cacheKey); @@ -574,16 +582,32 @@ module.exports = ({ config, db }) => { }); budsiesApi.post('/address/create', (req, res) => { - const client = Magento1Client(multiStoreConfig(config.magento1.api, req)); + const client = Magento2Client(multiStoreConfig(config.magento2.api, req)); - client.addMethods('budsies', (restClient) => { + client.addMethods('budsies', () => { let module = {}; module.createAddress = function () { const customerToken = getToken(req); + const userProxy = _getUserProxy(req); - return restClient.post(`address/create?token=${customerToken}`, req.body).then((data) => { - return getResponse(data); + let existingAddressesIds = []; + + return userProxy.me(customerToken).then((result) => { + existingAddressesIds = result.addresses.map((address) => address.id); + + return updateUserAddresses( + customerToken, + userProxy, + result, + [...result.addresses, req.body.address] + ); + }).then((data) => { + const addedAddress = data.addresses.find( + (address) => !existingAddressesIds.includes(address.id) + ); + + return addedAddress; }); } @@ -598,16 +622,60 @@ module.exports = ({ config, db }) => { }); budsiesApi.post('/address/update', (req, res) => { - const client = Magento1Client(multiStoreConfig(config.magento1.api, req)); + const client = Magento2Client(multiStoreConfig(config.magento2.api, req)); - client.addMethods('budsies', (restClient) => { + client.addMethods('budsies', () => { let module = {}; module.updateAddress = function () { const customerToken = getToken(req); + const userProxy = _getUserProxy(req); + const addressForUpdate = req.body.address; + + return userProxy.me(customerToken).then((result) => { + let isAddressForUpdateFound = false; + const updatedAddresses = []; + + result.addresses.forEach( + (address) => { + if (addressForUpdate.id === address.id) { + isAddressForUpdateFound = true; + updatedAddresses.push(addressForUpdate); + return; + } + + if (addressForUpdate.default_shipping) { + address.default_shipping = false; + } + + if (addressForUpdate.default_billing) { + address.default_billing = false + } + + updatedAddresses.push(address); + } + ); + + if (!isAddressForUpdateFound) { + const error = { + code: 404, + result: 'Not Found' + } + throw error; + } - return restClient.post(`address/update?token=${customerToken}`, req.body).then((data) => { - return getResponse(data); + return updateUserAddresses( + customerToken, + userProxy, + result, + updatedAddresses + ); + }).then((data) => { + const updatedAddress = data.addresses.find( + (address) => addressForUpdate.id === address.id + ); + + return updatedAddress; }); } @@ -621,69 +689,40 @@ module.exports = ({ config, db }) => { }); }); - budsiesApi.get('/address/get', (req, res) => { - const client = Magento1Client(multiStoreConfig(config.magento1.api, req)); - - client.addMethods('budsies', (restClient) => { - let module = {}; - - module.getAddress = function () { - const customerToken = getToken(req); - - let url = `address/get?token=${customerToken}`; - - return restClient.get(url).then((data) => { - return getResponse(data); - }); - } - - return module; - }); - - client.budsies.getAddress().then((result) => { - apiStatus(res, result, 200); - }).catch(err => { - apiStatus(res, err, err.code); - }); - }); - - budsiesApi.get('/address/list', (req, res) => { - const client = Magento1Client(multiStoreConfig(config.magento1.api, req)); + budsiesApi.post('/address/delete', (req, res) => { + const client = Magento2Client(multiStoreConfig(config.magento1.api, req)); - client.addMethods('budsies', (restClient) => { + client.addMethods('budsies', () => { let module = {}; - module.listAddress = function () { + module.deleteAddress = function () { + const userProxy = _getUserProxy(req); const customerToken = getToken(req); - let url = `address/list?token=${customerToken}`; - - return restClient.get(url).then((data) => { - return getResponse(data); - }); - } + return userProxy.me(customerToken).then((result) => { + const addressToDeleteIndex = result.addresses.findIndex( + (address) => address.id === req.body.address.id + ); - return module; - }); + if (addressToDeleteIndex === -1) { + const error = { + code: 404, + result: 'Not Found' + }; - client.budsies.listAddress().then((result) => { - apiStatus(res, result, 200); - }).catch(err => { - apiStatus(res, err, err.code); - }); - }); - - budsiesApi.post('/address/delete', (req, res) => { - const client = Magento1Client(multiStoreConfig(config.magento1.api, req)); + throw error; + } - client.addMethods('budsies', (restClient) => { - let module = {}; + result.addresses.splice(addressToDeleteIndex, 1) - module.deleteAddress = function () { - const customerToken = getToken(req); - - return restClient.post(`address/delete?token=${customerToken}`, req.body).then((data) => { - return getResponse(data); + return updateUserAddresses( + customerToken, + userProxy, + result, + result.addresses + ); + }).then(() => { + return req.body.address.id; }); } diff --git a/src/api/user.ts b/src/api/user.ts index 525a02e9..cebf01ef 100755 --- a/src/api/user.ts +++ b/src/api/user.ts @@ -21,6 +21,31 @@ function addUserGroupToken (config, result) { result.groupToken = jwt.encode(data, config.authHashSecret ? config.authHashSecret : config.objHashSecret) } +function validateUserData (data): { + isValid: boolean, + errors: any +} { + const ajv = new Ajv(); + const userProfileSchema = require('../models/userProfileUpdate.schema.json') + let userProfileSchemaExtension = {}; + if (fs.existsSync(path.resolve(__dirname, '../models/userProfileUpdate.schema.extension.json'))) { + userProfileSchemaExtension = require('../models/userProfileUpdate.schema.extension.json'); + } + const validate = ajv.compile(merge(userProfileSchema, userProfileSchemaExtension)) + + if (!validate(data)) { + return { + isValid: false, + errors: validate.errors + } + } + + return { + isValid: true, + errors: undefined + } +} + function validateAddresses (currentAddresses = [], newAddresses = []) { for (let address of newAddresses) { if (!address.customer_id && !address.id) { @@ -34,7 +59,54 @@ function validateAddresses (currentAddresses = [], newAddresses = []) { } } -export default ({config, db}) => { +export function updateUserAddresses ( + customerToken, + userProxy, + customerData, + addresses +) { + const addressesValidation = validateAddresses( + customerData.addresses, + addresses + ); + + if (addressesValidation) { + const error = { + code: 403, + result: addressesValidation + } + throw error; + } + + const data: any = { + customer: { + email: customerData.email, + firstname: customerData.firstname, + lastname: customerData.lastname, + addresses + } + }; + + const validationResult = validateUserData(data); + + if (!validationResult.isValid) { + const error = { + errors: validationResult.errors, + code: 500 + } + + throw error; + } + + data.customer.website_id = customerData.website_id; + + return userProxy.update({ + token: customerToken, + body: data + }); +} + +export default ({ config, db }) => { let userApi = Router(); const _getProxy = (req) => { @@ -83,7 +155,7 @@ export default ({config, db}) => { /** * Second request for more user info */ - apiStatus(res, result, 200, {refreshToken: encryptToken(jwt.encode(req.body, config.authHashSecret ? config.authHashSecret : config.objHashSecret), config.authHashSecret ? config.authHashSecret : config.objHashSecret)}); + apiStatus(res, result, 200, { refreshToken: encryptToken(jwt.encode(req.body, config.authHashSecret ? config.authHashSecret : config.objHashSecret), config.authHashSecret ? config.authHashSecret : config.objHashSecret) }); }).catch(err => { apiError(res, err); }) @@ -106,7 +178,7 @@ export default ({config, db}) => { } userProxy.login(decodedToken).then((result) => { - apiStatus(res, result, 200, {refreshToken: encryptToken(jwt.encode(decodedToken, config.authHashSecret ? config.authHashSecret : config.objHashSecret), config.authHashSecret ? config.authHashSecret : config.objHashSecret)}); + apiStatus(res, result, 200, { refreshToken: encryptToken(jwt.encode(decodedToken, config.authHashSecret ? config.authHashSecret : config.objHashSecret), config.authHashSecret ? config.authHashSecret : config.objHashSecret) }); }).catch(err => { apiError(res, err); }) @@ -186,21 +258,14 @@ export default ({config, db}) => { * POST for updating user */ userApi.post('/me', async (req, res) => { - const ajv = new Ajv(); - const userProfileSchema = require('../models/userProfileUpdate.schema.json') - let userProfileSchemaExtension = {}; - if (fs.existsSync(path.resolve(__dirname, '../models/userProfileUpdate.schema.extension.json'))) { - userProfileSchemaExtension = require('../models/userProfileUpdate.schema.extension.json'); - } - const validate = ajv.compile(merge(userProfileSchema, userProfileSchemaExtension)) - if (req.body.customer && req.body.customer.groupToken) { delete req.body.customer.groupToken } - if (!validate(req.body)) { - console.dir(validate.errors); - apiStatus(res, validate.errors, 500); + const validationResult = validateUserData(req.body); + + if (!validationResult.isValid) { + apiStatus(res, validationResult.errors, 500); return; } @@ -255,7 +320,7 @@ export default ({config, db}) => { userApi.post('/change-password', (req, res) => { const userProxy = _getProxy(req) const token = getToken(req) - userProxy.changePassword({token, body: req.body}).then((result) => { + userProxy.changePassword({ token, body: req.body }).then((result) => { apiStatus(res, result, 200) }).catch(err => { apiStatus(res, err, 500)