|
1 | 1 | const __MODULE__ = 'Offer'; |
2 | 2 | const { mountedResponse } = require('./utils/response'); |
| 3 | +const brandService = require('./services/brandService'); |
3 | 4 | const offerService = require('./services/offerService'); |
4 | 5 | const locationService = require('./services/locationService'); |
5 | 6 |
|
@@ -51,3 +52,54 @@ module.exports.linkToLocation = async (event) => { |
51 | 52 | const body = { message: 'Offer successfully linked to this Location' }; |
52 | 53 | return mountedResponse(body, 200); |
53 | 54 | }; |
| 55 | + |
| 56 | +module.exports.linkAllBrandsLocationToAnOffer = async (event) => { |
| 57 | + const { offerId, brandId } = event.pathParameters; |
| 58 | + console.log(`${__MODULE__}@linkAllBrandsLocationToAnOffer: Assigning all locations from brand #${brandId} to offer #${offerId}`, event); |
| 59 | + |
| 60 | + const offer = await offerService.getById(offerId); |
| 61 | + const locations = await brandService.getAllLocationsFromBrand(brandId); |
| 62 | + |
| 63 | + console.debug(`${__MODULE__}@linkAllBrandsLocationToAnOffer: Offer found`, offer); |
| 64 | + console.debug(`${__MODULE__}@linkAllBrandsLocationToAnOffer: Locations found`, locations); |
| 65 | + |
| 66 | + if (!offer) { |
| 67 | + const body = { message: 'Offer does not exists!' }; |
| 68 | + |
| 69 | + return mountedResponse(body, 404); |
| 70 | + } |
| 71 | + |
| 72 | + if (locations && locations.length == 0) { |
| 73 | + const body = { message: 'No Locations were found for this brand!' }; |
| 74 | + |
| 75 | + return mountedResponse(body, 404); |
| 76 | + } |
| 77 | + |
| 78 | + if (!locations) { |
| 79 | + const body = { message: 'An error ocurred while fetching all locations' }; |
| 80 | + return mountedResponse(body, 500); |
| 81 | + } |
| 82 | + |
| 83 | + try { |
| 84 | + const results = await Promise.allSettled(locations.forEach((location) => { |
| 85 | + await offerService.linkToLocation(offer, location); |
| 86 | + })); |
| 87 | + |
| 88 | + const hasSomeFailure = results.some(result => result.status == 'rejected'); |
| 89 | + |
| 90 | + if (hasSomeFailure) { |
| 91 | + const body = { message: 'The action was completed, but not entirely successfull, some locations were not linked to this offer. Try again to link all them' }; |
| 92 | + |
| 93 | + return mountedResponse(body, 200); |
| 94 | + } |
| 95 | + |
| 96 | + const body = { message: 'The action was successfully completed!' }; |
| 97 | + |
| 98 | + return mountedResponse(body, 200); |
| 99 | + |
| 100 | + } catch (error) { |
| 101 | + const body = { message: 'Could not perform brands location assignment' }; |
| 102 | + |
| 103 | + return mountedResponse(body, 500); |
| 104 | + } |
| 105 | +}; |
0 commit comments