Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#32785: Addresses Resources - update for support Magento 2 #104

Merged
merged 4 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 102 additions & 63 deletions src/api/extensions/budsies/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 })

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
});
}

Expand All @@ -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;
});
}

Expand All @@ -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;
});
}

Expand Down
95 changes: 80 additions & 15 deletions src/api/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) => {
Expand Down Expand Up @@ -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);
})
Expand All @@ -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);
})
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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)
Expand Down
Loading