@@ -187,10 +187,75 @@ const bmConsumableController = function (BuildingConsumable) {
187187 } ) ;
188188 } ;
189189
190+ const bmUpdateConsumablePurchaseStatus = async function ( req , res ) {
191+ const { purchaseId, status, quantity } = req . body ;
192+
193+ if ( ! purchaseId || ! status || ! [ 'Approved' , 'Rejected' ] . includes ( status ) ) {
194+ return res
195+ . status ( 400 )
196+ . send ( 'Invalid request. purchaseId and a valid status (Approved/Rejected) are required.' ) ;
197+ }
198+
199+ if ( status === 'Approved' && ( quantity == null || quantity <= 0 ) ) {
200+ return res . status ( 400 ) . send ( 'A positive quantity is required when approving a purchase.' ) ;
201+ }
202+
203+ const requestorRole = req . body . requestor && req . body . requestor . role ;
204+ if ( requestorRole !== 'Owner' && requestorRole !== 'Administrator' ) {
205+ return res . status ( 403 ) . send ( 'You are not authorized to approve or reject purchases.' ) ;
206+ }
207+
208+ try {
209+ const consumable = await BuildingConsumable . findOne ( { 'purchaseRecord._id' : purchaseId } ) ;
210+
211+ if ( ! consumable ) {
212+ return res . status ( 404 ) . send ( 'Purchase not found' ) ;
213+ }
214+
215+ const purchaseRecord = consumable . purchaseRecord . find (
216+ ( record ) => record . _id . toString ( ) === purchaseId ,
217+ ) ;
218+
219+ if ( ! purchaseRecord ) {
220+ return res . status ( 404 ) . send ( 'Purchase record not found' ) ;
221+ }
222+
223+ if ( purchaseRecord . status !== 'Pending' ) {
224+ return res
225+ . status ( 400 )
226+ . send (
227+ `Purchase status can only be updated from 'Pending'. Current status is '${ purchaseRecord . status } '.` ,
228+ ) ;
229+ }
230+
231+ const updateObject = {
232+ $set : { 'purchaseRecord.$.status' : status } ,
233+ } ;
234+ if ( status === 'Approved' ) {
235+ updateObject . $inc = { stockBought : quantity } ;
236+ }
237+
238+ const updatedConsumable = await BuildingConsumable . findOneAndUpdate (
239+ { 'purchaseRecord._id' : purchaseId } ,
240+ updateObject ,
241+ { new : true } ,
242+ ) ;
243+
244+ if ( ! updatedConsumable ) {
245+ return res . status ( 500 ) . send ( 'Failed to apply purchase status update to consumable.' ) ;
246+ }
247+
248+ res . status ( 200 ) . send ( `Purchase ${ status . toLowerCase ( ) } successfully` ) ;
249+ } catch ( error ) {
250+ res . status ( 500 ) . send ( error ) ;
251+ }
252+ } ;
253+
190254 return {
191255 fetchBMConsumables,
192256 bmPurchaseConsumables,
193257 bmPostConsumableUpdateRecord,
258+ bmUpdateConsumablePurchaseStatus,
194259 } ;
195260} ;
196261
0 commit comments