Subversion Repositories SmartDukaan

Rev

Rev 37094 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
36321 vikas 1
package com.spice.profitmandi.web.v2.controller;
2
 
36376 aman 3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
4
import com.spice.profitmandi.common.model.ProfitMandiConstants;
5
import com.spice.profitmandi.common.model.UserInfo;
6
import com.spice.profitmandi.dao.cart.CartService;
7
import com.spice.profitmandi.dao.cart.v2.CartValidationService;
8
import com.spice.profitmandi.dao.cart.v2.CheckoutValidationResult;
37084 ranu 9
import com.spice.profitmandi.dao.cart.v2.HydratedCart;
10
import com.spice.profitmandi.dao.cart.v2.HydratedLine;
11
import com.spice.profitmandi.dao.cart.v2.LineStatus;
36376 aman 12
import com.spice.profitmandi.dao.cart.v2.OpenCartValidationResult;
37084 ranu 13
import com.spice.profitmandi.dao.cart.v2.PricingBreakup;
36376 aman 14
import com.spice.profitmandi.dao.cart.v2.SaleType;
15
import com.spice.profitmandi.dao.entity.catalog.Item;
16
import com.spice.profitmandi.dao.entity.catalog.TagListing;
37014 ranu 17
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
36376 aman 18
import com.spice.profitmandi.dao.entity.user.CartLine;
36321 vikas 19
import com.spice.profitmandi.dao.enumuration.catalog.ByPassRequestStatus;
37014 ranu 20
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
36321 vikas 21
import com.spice.profitmandi.dao.model.AddCartRequest;
36376 aman 22
import com.spice.profitmandi.dao.model.CartItem;
23
import com.spice.profitmandi.dao.model.UserCart;
24
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
25
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
26
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
27
import com.spice.profitmandi.dao.repository.user.CartLineRepository;
28
import com.spice.profitmandi.service.scheme.SchemeService;
36321 vikas 29
import com.spice.profitmandi.web.controller.CartController;
30
import com.spice.profitmandi.web.v2.response.ApiResponse;
31
import org.springframework.beans.factory.annotation.Autowired;
36376 aman 32
import org.springframework.http.HttpStatus;
36321 vikas 33
import org.springframework.http.ResponseEntity;
34
import org.springframework.ui.Model;
35
import org.springframework.web.bind.annotation.*;
36
 
37
import javax.servlet.http.HttpServletRequest;
37084 ranu 38
import java.math.BigDecimal;
39
import java.math.RoundingMode;
37014 ranu 40
import java.time.LocalDate;
36376 aman 41
import java.util.ArrayList;
42
import java.util.Arrays;
43
import java.util.HashSet;
44
import java.util.List;
45
import java.util.Map;
46
import java.util.Set;
47
import java.util.stream.Collectors;
36321 vikas 48
 
36376 aman 49
import org.springframework.transaction.annotation.Transactional;
50
 
36321 vikas 51
@RestController
52
@RequestMapping("/v2")
36376 aman 53
@Transactional(rollbackFor = Throwable.class)
36321 vikas 54
public class V2CartController extends V2BaseController {
55
 
56
    @Autowired
57
    private CartController cartController;
58
 
36376 aman 59
    @Autowired
60
    private CartValidationService cartValidationService;
61
 
62
    @Autowired
63
    private UserAccountRepository userAccountRepository;
64
 
65
    @Autowired
66
    private CartService cartService;
67
 
68
    @Autowired
69
    private CartLineRepository cartLineRepository;
70
 
71
    @Autowired
72
    private ItemRepository itemRepository;
73
 
74
    @Autowired
75
    private TagListingRepository tagListingRepository;
76
 
77
    @Autowired
78
    private SchemeService schemeService;
79
 
80
    @Autowired
81
    private com.spice.profitmandi.dao.repository.user.CartRepository cartRepository;
82
 
37014 ranu 83
    @Autowired
84
    private PartnerTypeChangeService partnerTypeChangeService;
85
 
36376 aman 86
    private static final int MRP_TAG_ID = 4;
87
    private static final double CARRY_BAG_THRESHOLD = 12000d;
37014 ranu 88
    // Premium tiers (Platinum/Diamond/Gold/Rising Star) get flat ₹1;
89
    // Silver/Bronze pay MRP from TagListing (matches CartServiceImpl.getCartValidation).
90
    private static final float CARRY_BAG_PREMIUM_PRICE = 1f;
36376 aman 91
 
36321 vikas 92
    @GetMapping("/cart")
93
    public ResponseEntity<ApiResponse<?>> validateCart(HttpServletRequest request,
94
                                                      @RequestParam(value = "pincode", defaultValue = "110001") String pincode,
95
                                                      @RequestParam int bucketId) throws Throwable {
96
        return wrapResponse(cartController.validateCart(request, pincode, bucketId));
97
    }
98
 
99
    @PostMapping("/cart")
100
    public ResponseEntity<ApiResponse<?>> validateCart(HttpServletRequest request,
101
                                                      @RequestBody AddCartRequest addCartRequest,
102
                                                      @RequestParam(value = "pincode", defaultValue = "110001") String pincode) throws Throwable {
103
        return wrapResponse(cartController.validateCart(request, addCartRequest, pincode));
104
    }
105
 
106
    @PostMapping("/cart/changeAddress")
107
    public ResponseEntity<ApiResponse<?>> changeAddress(HttpServletRequest request,
108
                                                        @RequestParam(value = "addressId") long addressId) throws Throwable {
109
        return wrapResponse(cartController.changeAddress(request, addressId));
110
    }
111
 
112
    @GetMapping("/byPassRequests")
113
    public ResponseEntity<ApiResponse<?>> byPassRequests(HttpServletRequest request, Model model) throws Throwable {
114
        return wrapResponse(cartController.byPassRequests(request, model));
115
    }
116
 
117
    @PostMapping("/byPassRequestAction")
118
    public ResponseEntity<ApiResponse<?>> addAmountToWalletRequestRejected(HttpServletRequest request,
119
                                                                           @RequestParam(name = "id", defaultValue = "0") int id,
120
                                                                           @RequestParam ByPassRequestStatus status,
121
                                                                           @RequestParam String reason,
122
                                                                           Model model) throws Throwable {
123
        return wrapResponse(cartController.addAmountToWalletRequestRejected(request, id, status, reason, model));
124
    }
125
 
126
    @GetMapping("/cart/payment")
127
    public ResponseEntity<ApiResponse<?>> validateCartPayment(HttpServletRequest request,
128
                                                              @RequestParam(defaultValue = "0") int paymentId,
129
                                                              Model model) throws Throwable {
130
        return wrapResponse(cartController.validateCartPayment(request, paymentId, model));
131
    }
132
 
133
    @GetMapping("/partner/hidAllocation")
134
    public ResponseEntity<ApiResponse<?>> getItemHidAllocation(HttpServletRequest request) throws Throwable {
135
        return wrapResponse(cartController.getItemHidAllocation(request));
136
    }
36376 aman 137
 
138
    // =================================================================
139
    // Cart v2 redesign — two-step validation (open + checkout)
140
    // All endpoints require authentication. Guests are rejected with 401.
141
    // =================================================================
142
 
143
    /** STEP 1 — soft validation. Never blocks. Surfaces warnings for price drift,
144
     *  qty downgrade, OOS, unavailability. Refreshes last-seen price baseline
145
     *  used by Step 2 drift detection.
146
     *  Pincode is derived from the cart's bound address server-side; clients
147
     *  do not pass it. */
148
    @GetMapping("/cart/open")
149
    public ResponseEntity<?> openCart(HttpServletRequest request)
150
            throws ProfitMandiBusinessException {
151
        java.util.Optional<AuthCtx> auth = resolveAuth(request);
37157 amit 152
        if (!auth.isPresent()) return authFailureResponse(request);
36376 aman 153
        AuthCtx ctx = auth.get();
37084 ranu 154
        OpenCartValidationResult result = validateAndApplyCarryBagPrice(
36376 aman 155
                ctx.cartId, ctx.storeId);
156
        return ResponseEntity.ok(ApiResponse.success(result));
157
    }
158
 
159
    /** STEP 2 — hard validation immediately before payment. Returns
160
     *  {@code valid=false} on any drift; user must hit {@code /cart/open}
161
     *  to re-confirm, then retry this endpoint. On pass, creates a 240s
162
     *  stock reservation and returns a {@code reservationId}.
163
     *  Procurement only — tertiary billing drafts check out via
164
     *  /v2/billing/drafts/{cartId}/commit. */
165
    @PostMapping("/cart/validate")
166
    public ResponseEntity<?> validateForCheckout(HttpServletRequest request,
167
                                                 @RequestParam(value = "addressId") long addressId)
168
            throws ProfitMandiBusinessException {
169
        java.util.Optional<AuthCtx> auth = resolveAuth(request);
37157 amit 170
        if (!auth.isPresent()) return authFailureResponse(request);
36376 aman 171
        AuthCtx ctx = auth.get();
172
        CheckoutValidationResult result = cartValidationService.validateForCheckout(
173
                ctx.cartId, ctx.userId, ctx.storeId, addressId, SaleType.PARTNER_PROCUREMENT);
174
        return ResponseEntity.ok(ApiResponse.success(result));
175
    }
176
 
177
    // -----------------------------------------------------------------
178
    // Cart mutations — productId-only payload. All return the freshly
179
    // hydrated cart (Step 1 result) so the client never keeps stale state.
180
    // -----------------------------------------------------------------
181
 
182
    /** Add a single product to the cart. Increments qty if already present. */
183
    @PostMapping("/cart/items")
184
    public ResponseEntity<?> addItem(HttpServletRequest request,
185
                                     @RequestBody AddCartItemRequest body)
186
            throws ProfitMandiBusinessException {
187
        java.util.Optional<AuthCtx> auth = resolveAuth(request);
37157 amit 188
        if (!auth.isPresent()) return authFailureResponse(request);
36376 aman 189
        AuthCtx ctx = auth.get();
190
        if (body == null || body.productId <= 0 || body.quantity <= 0) {
191
            throw new ProfitMandiBusinessException("body", body, "CART_ITEM_INVALID_PAYLOAD");
192
        }
193
        List<CartItem> desired = currentLinesAsItems(ctx.cartId);
194
        boolean found = false;
195
        for (CartItem existing : desired) {
196
            if (existing.getItemId() == body.productId) {
197
                existing.setQuantity(existing.getQuantity() + body.quantity);
198
                found = true;
199
                break;
200
            }
201
        }
202
        if (!found) {
203
            desired.add(new CartItem(body.quantity, body.productId));
204
        }
205
        return applyAndHydrate(ctx, desired);
206
    }
207
 
208
    /** Set a specific line's quantity. quantity=0 removes the line. */
36479 ranu 209
    @PostMapping("/cart/items/{productId}")
36376 aman 210
    public ResponseEntity<?> updateQuantity(HttpServletRequest request,
211
                                            @PathVariable int productId,
212
                                            @RequestParam int quantity)
213
            throws ProfitMandiBusinessException {
214
        java.util.Optional<AuthCtx> auth = resolveAuth(request);
37157 amit 215
        if (!auth.isPresent()) return authFailureResponse(request);
36376 aman 216
        AuthCtx ctx = auth.get();
217
        if (quantity < 0) {
218
            throw new ProfitMandiBusinessException("quantity", quantity, "CART_ITEM_NEGATIVE_QTY");
219
        }
220
        List<CartItem> desired = currentLinesAsItems(ctx.cartId);
221
        if (quantity == 0) {
222
            desired = desired.stream()
223
                    .filter(ci -> ci.getItemId() != productId)
224
                    .collect(Collectors.toList());
225
        } else {
226
            boolean found = false;
227
            for (CartItem existing : desired) {
228
                if (existing.getItemId() == productId) {
229
                    existing.setQuantity(quantity);
230
                    found = true;
231
                    break;
232
                }
233
            }
234
            if (!found) {
235
                desired.add(new CartItem(quantity, productId));
236
            }
237
        }
36479 ranu 238
        // Skip carry bag rebalance if user explicitly changed carry bag qty
239
        if (productId == ProfitMandiConstants.ITEM_CARRY_BAG) {
240
            enrichPrices(ctx, desired);
241
            cartService.addItemsToCart(ctx.cartId, desired);
242
            return ResponseEntity.ok(ApiResponse.success(
37084 ranu 243
                    validateAndApplyCarryBagPrice(ctx.cartId, ctx.storeId)));
36479 ranu 244
        }
36376 aman 245
        return applyAndHydrate(ctx, desired);
246
    }
247
 
248
    /** Remove a single line by productId. */
249
    @DeleteMapping("/cart/items/{productId}")
250
    public ResponseEntity<?> removeItem(HttpServletRequest request,
251
                                        @PathVariable int productId)
252
            throws ProfitMandiBusinessException {
253
        java.util.Optional<AuthCtx> auth = resolveAuth(request);
37157 amit 254
        if (!auth.isPresent()) return authFailureResponse(request);
36376 aman 255
        AuthCtx ctx = auth.get();
256
        List<CartItem> desired = currentLinesAsItems(ctx.cartId).stream()
257
                .filter(ci -> ci.getItemId() != productId)
258
                .collect(Collectors.toList());
36479 ranu 259
        // Skip carry bag rebalance if user explicitly removed the carry bag
260
        if (productId == ProfitMandiConstants.ITEM_CARRY_BAG) {
261
            enrichPrices(ctx, desired);
262
            cartService.addItemsToCart(ctx.cartId, desired);
263
            return ResponseEntity.ok(ApiResponse.success(
37084 ranu 264
                    validateAndApplyCarryBagPrice(ctx.cartId, ctx.storeId)));
36479 ranu 265
        }
36376 aman 266
        return applyAndHydrate(ctx, desired);
267
    }
268
 
269
    /** Clear the entire cart. */
270
    @DeleteMapping("/cart")
271
    public ResponseEntity<?> clearCart(HttpServletRequest request)
272
            throws ProfitMandiBusinessException {
273
        java.util.Optional<AuthCtx> auth = resolveAuth(request);
37157 amit 274
        if (!auth.isPresent()) return authFailureResponse(request);
36376 aman 275
        AuthCtx ctx = auth.get();
276
        cartService.clearCart(ctx.cartId);
277
        return ResponseEntity.ok(ApiResponse.success(
37084 ranu 278
                validateAndApplyCarryBagPrice(ctx.cartId, ctx.storeId)));
36376 aman 279
    }
280
 
281
    /**
282
     * Enriches each desired CartItem with the live selling price, runs the
283
     * procurement carry-bag rebalance, applies the change, then returns a
284
     * hydrated Step-1 view. /v2/cart/* is procurement-only; tertiary drafts
285
     * have their own controller.
286
     */
287
    private ResponseEntity<?> applyAndHydrate(AuthCtx ctx, List<CartItem> desired)
288
            throws ProfitMandiBusinessException {
289
        enrichPrices(ctx, desired);
37014 ranu 290
        rebalanceCarryBag(desired, ctx.storeId);
36376 aman 291
        cartService.addItemsToCart(ctx.cartId, desired);
292
        return ResponseEntity.ok(ApiResponse.success(
37084 ranu 293
                validateAndApplyCarryBagPrice(ctx.cartId, ctx.storeId)));
36376 aman 294
    }
295
 
296
    /**
297
     * Populates {@link CartItem#setSellingPrice(double)} for each non-carry-bag item
298
     * with the live (MOP - scheme cashback) figure. Preserves the existing value on
299
     * lookup miss so a partial-Solr outage doesn't zero out prices.
300
     */
301
    private void enrichPrices(AuthCtx ctx, List<CartItem> desired) throws ProfitMandiBusinessException {
302
        Set<Integer> itemIds = desired.stream()
303
                .filter(ci -> ci.getItemId() != ProfitMandiConstants.ITEM_CARRY_BAG)
304
                .map(CartItem::getItemId)
305
                .collect(Collectors.toSet());
306
        if (itemIds.isEmpty()) return;
307
 
308
        Map<Integer, TagListing> tagByItem = tagListingRepository
309
                .selectByItemIdsAndTagIds(itemIds, new HashSet<>(Arrays.asList(MRP_TAG_ID)))
310
                .stream()
311
                .collect(Collectors.toMap(TagListing::getItemId, x -> x, (a, b) -> a));
312
        Map<Integer, Item> items = itemRepository.selectByIds(itemIds).stream()
313
                .collect(Collectors.toMap(Item::getId, x -> x, (a, b) -> a));
314
        List<Integer> catalogIds = items.values().stream()
315
                .map(Item::getCatalogItemId).distinct().collect(Collectors.toList());
316
        Map<Integer, Float> cashbackByCatalog = schemeService.getCatalogSchemeCashBack(ctx.storeId, catalogIds);
317
        if (cashbackByCatalog == null) cashbackByCatalog = java.util.Collections.emptyMap();
318
 
319
        for (CartItem ci : desired) {
320
            if (ci.getItemId() == ProfitMandiConstants.ITEM_CARRY_BAG) continue;
321
            TagListing tl = tagByItem.get(ci.getItemId());
322
            Item it = items.get(ci.getItemId());
323
            if (tl == null || it == null) continue;
324
            float cashback = cashbackByCatalog.getOrDefault(it.getCatalogItemId(), 0f);
325
            ci.setSellingPrice(tl.getMop() - cashback);
326
        }
327
    }
328
 
329
    /**
330
     * Server-side port of the legacy Zustand carry-bag rule: any item with
331
     * sellingPrice > ₹12,000 needs one carry bag per unit. Runs BEFORE addItemsToCart
332
     * so the full-sync semantics keep the cart consistent in one round-trip.
37015 ranu 333
     *
334
     * Pricing mirrors {@code CartServiceImpl.getCartValidation} (lines 271-278):
335
     *   PLATINUM / DIAMOND / GOLD / NEW (Rising Star) -> ₹1 flat
336
     *   SILVER / BRONZE                              -> MRP from carry-bag TagListing
36376 aman 337
     */
37015 ranu 338
    private void rebalanceCarryBag(List<CartItem> desired, int fofoId) {
36376 aman 339
        int bagsNeeded = 0;
340
        for (CartItem ci : desired) {
341
            if (ci.getItemId() == ProfitMandiConstants.ITEM_CARRY_BAG) continue;
342
            if (ci.getSellingPrice() > CARRY_BAG_THRESHOLD) {
343
                bagsNeeded += ci.getQuantity();
344
            }
345
        }
346
        desired.removeIf(ci -> ci.getItemId() == ProfitMandiConstants.ITEM_CARRY_BAG);
347
        if (bagsNeeded > 0) {
348
            CartItem bag = new CartItem(bagsNeeded, ProfitMandiConstants.ITEM_CARRY_BAG);
37015 ranu 349
            bag.setSellingPrice(resolveCarryBagPrice(fofoId));
36376 aman 350
            desired.add(bag);
351
        }
352
    }
353
 
37084 ranu 354
    /**
355
     * Wraps {@link CartValidationService#validateForOpen} and overrides the
356
     * carry-bag line's LivePrice + rolls up totals using the tier logic that
357
     * v1's {@code CartServiceImpl.getCartValidation} already applies (lines
358
     * 271-278). Needed because the shared v2 hydrator prices every line from
359
     * {@code TagListing.getMop()} without a tier check, so premium partners
360
     * would otherwise see MRP (₹15) instead of ₹1.
361
     */
362
    private OpenCartValidationResult validateAndApplyCarryBagPrice(int cartId, int fofoId)
363
            throws ProfitMandiBusinessException {
364
        OpenCartValidationResult result = cartValidationService.validateForOpen(cartId, fofoId);
365
        if (result == null || result.getCart() == null || result.getCart().getLines() == null) {
366
            return result;
367
        }
368
        HydratedCart cart = result.getCart();
37094 ranu 369
 
370
        // 1. Overwrite every line's price from TagListing.sellingPrice — this is
371
        //    the same source v1's CartServiceImpl.getCartValidation uses to set
372
        //    cart_line.actual_price, i.e. the price the order will actually be
373
        //    charged at. The v2 hydrator picks tagListing.mop instead, which
374
        //    diverges from sellingPrice on scheme-discounted models (e.g. Moto
375
        //    G67 showed ₹22,999 mop vs ₹19,907 sellingPrice). Sync client
376
        //    display to server-of-truth so the partner sees what they'll pay.
377
        Set<Integer> lineItemIds = cart.getLines().stream()
378
                .filter(l -> l.getProductId() != ProfitMandiConstants.ITEM_CARRY_BAG)
379
                .map(HydratedLine::getProductId)
380
                .collect(Collectors.toSet());
381
        Map<Integer, Float> sellingByItemId = new java.util.HashMap<>();
382
        if (!lineItemIds.isEmpty()) {
383
            List<TagListing> tls = tagListingRepository.selectByItemIdsAndTagIds(
384
                    lineItemIds, new HashSet<>(Arrays.asList(MRP_TAG_ID)));
385
            for (TagListing tl : tls) {
386
                sellingByItemId.putIfAbsent(tl.getItemId(), tl.getSellingPrice());
387
            }
388
        }
389
        boolean overridden = false;
390
        for (HydratedLine line : cart.getLines()) {
391
            if (line.getProductId() == ProfitMandiConstants.ITEM_CARRY_BAG) continue;
392
            if (line.getPrice() == null) continue;
393
            Float livePrice = sellingByItemId.get(line.getProductId());
394
            if (livePrice == null) continue;
395
            BigDecimal newPrice = BigDecimal.valueOf(livePrice)
396
                    .setScale(2, RoundingMode.HALF_UP);
397
            if (line.getPrice().getSelling() == null
398
                    || line.getPrice().getSelling().compareTo(newPrice) != 0) {
399
                line.getPrice().setMrp(newPrice);
400
                line.getPrice().setSelling(newPrice);
401
                line.getPrice().setSchemeCashback(BigDecimal.ZERO);
402
                overridden = true;
403
            }
404
        }
405
 
406
        // 2. Carry-bag tier logic (₹1 for premium, MOP for Silver/Bronze).
37084 ranu 407
        BigDecimal tierPrice = BigDecimal.valueOf(resolveCarryBagPrice(fofoId))
408
                .setScale(2, RoundingMode.HALF_UP);
409
        for (HydratedLine line : cart.getLines()) {
410
            if (line.getProductId() != ProfitMandiConstants.ITEM_CARRY_BAG) continue;
411
            if (line.getPrice() == null) continue;
412
            if (line.getPrice().getSelling() == null
413
                    || line.getPrice().getSelling().compareTo(tierPrice) != 0) {
414
                line.getPrice().setMrp(tierPrice);
415
                line.getPrice().setSelling(tierPrice);
416
                line.getPrice().setSchemeCashback(BigDecimal.ZERO);
417
                overridden = true;
418
            }
419
        }
37094 ranu 420
 
37084 ranu 421
        if (overridden && cart.getPricing() != null) {
37094 ranu 422
            // Mirrors CartHydrationServiceImpl.computePricing so the grand total
423
            // reflects every overridden line price.
37084 ranu 424
            BigDecimal subtotal = BigDecimal.ZERO;
425
            BigDecimal discounts = BigDecimal.ZERO;
426
            BigDecimal insuranceTotal = BigDecimal.ZERO;
427
            for (HydratedLine line : cart.getLines()) {
428
                if (line.getStatus() != LineStatus.ACTIVE || line.getPrice() == null) continue;
429
                BigDecimal qty = BigDecimal.valueOf(line.getQuantity());
430
                subtotal = subtotal.add(line.getPrice().getMrp().multiply(qty));
431
                BigDecimal cashback = line.getPrice().getSchemeCashback() == null
432
                        ? BigDecimal.ZERO : line.getPrice().getSchemeCashback();
433
                discounts = discounts.add(cashback.multiply(qty));
434
                if (line.getInsurance() != null && line.getInsurance().getPremium() != null) {
435
                    insuranceTotal = insuranceTotal.add(line.getInsurance().getPremium());
436
                }
437
            }
438
            PricingBreakup p = cart.getPricing();
439
            p.setSubtotal(subtotal);
440
            p.setLineDiscounts(discounts);
441
            p.setTaxableBase(subtotal.subtract(discounts));
442
            p.setGrandTotal(p.getTaxableBase().add(insuranceTotal));
443
        }
444
        return result;
445
    }
446
 
37015 ranu 447
    private float resolveCarryBagPrice(int fofoId) {
448
        PartnerType tier = null;
449
        try {
450
            tier = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
451
        } catch (Exception e) {
452
            // fall through to premium price
453
        }
454
        if (tier == PartnerType.SILVER || tier == PartnerType.BRONZE) {
455
            try {
456
                TagListing tl = tagListingRepository.selectByItemId(ProfitMandiConstants.ITEM_CARRY_BAG);
457
                if (tl != null) return tl.getSellingPrice();
458
            } catch (Exception e) {
459
                // fall through to premium price
460
            }
461
        }
462
        return CARRY_BAG_PREMIUM_PRICE;
463
    }
464
 
36376 aman 465
    private List<CartItem> currentLinesAsItems(int cartId) {
466
        List<CartLine> lines = cartLineRepository.selectAllByCart(cartId);
467
        if (lines == null) return new ArrayList<>();
468
        return lines.stream()
469
                .map(l -> {
470
                    CartItem ci = new CartItem(l.getQuantity(), l.getItemId());
471
                    ci.setSellingPrice(l.getActualPrice());
472
                    return ci;
473
                })
474
                .collect(Collectors.toList());
475
    }
476
 
477
    public static class AddCartItemRequest {
478
        public int productId;
479
        public int quantity;
480
    }
481
 
482
    // -----------------------------------------------------------------
483
    // Auth helpers — login is mandatory per product decision (2026-04-21).
484
    // Guest carts are not supported; unauthenticated requests get 401.
485
    //
486
    // Returns the auth context as an Optional rather than throwing, because
487
    // GlobalExceptionHandler's @ExceptionHandler(Exception.class) would
488
    // otherwise wrap any RuntimeException as HTTP 500 regardless of
489
    // @ResponseStatus annotations on the exception class.
490
    // -----------------------------------------------------------------
491
 
492
    private static final class AuthCtx {
493
        final int userId;
494
        final int storeId;
495
        final int cartId;
496
        AuthCtx(int userId, int storeId, int cartId) {
497
            this.userId = userId; this.storeId = storeId; this.cartId = cartId;
498
        }
499
    }
500
 
501
    /**
502
     * Resolves the authenticated partner's PROCUREMENT cart. v2/cart/* is
503
     * procurement-only. Tertiary billing drafts live under /v2/billing/* and
504
     * are resolved per-cartId there.
505
     */
506
    private java.util.Optional<AuthCtx> resolveAuth(HttpServletRequest request) {
507
        Object userIdAttr = request.getAttribute("userId");
508
        if (userIdAttr == null) {
509
            return java.util.Optional.empty();
510
        }
511
        int userId;
512
        try {
513
            userId = (int) userIdAttr;
514
        } catch (ClassCastException e) {
515
            return java.util.Optional.empty();
516
        }
517
        if (userId <= 0) {
518
            return java.util.Optional.empty();
519
        }
520
        Object userInfoAttr = request.getAttribute("userInfo");
521
        int storeId = userInfoAttr instanceof UserInfo ? ((UserInfo) userInfoAttr).getRetailerId() : 0;
522
 
523
        UserCart uc = userAccountRepository.getUserCart(userId);
524
        if (uc == null || uc.getCartId() <= 0) {
525
            return java.util.Optional.empty();
526
        }
527
        return java.util.Optional.of(new AuthCtx(userId, storeId, uc.getCartId()));
528
    }
529
 
37157 amit 530
    /**
531
     * Distinguishes a genuinely unauthenticated request from a valid login with
532
     * no procurement cart mapped (missing dtr.user_accounts cartId row). The
533
     * latter used to answer "Authentication is required", which mislabels a data
534
     * gap as an auth failure.
535
     */
536
    private ResponseEntity<?> authFailureResponse(HttpServletRequest request) {
537
        Object userIdAttr = request.getAttribute("userId");
538
        if (userIdAttr instanceof Integer && (int) userIdAttr > 0) {
539
            java.util.Map<String, Object> body = new java.util.HashMap<>();
540
            body.put("responseStatus", "FAILURE");
541
            body.put("statusCode", 404);
542
            body.put("statusMessage", "NO_PROCUREMENT_CART");
543
            body.put("message", "No procurement cart is mapped to this user. Contact support to fix the account linkage.");
544
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
545
        }
546
        return unauthorized();
547
    }
548
 
36376 aman 549
    private ResponseEntity<?> unauthorized() {
550
        java.util.Map<String, Object> body = new java.util.HashMap<>();
551
        body.put("responseStatus", "FAILURE");
552
        body.put("statusCode", 401);
553
        body.put("statusMessage", "LOGIN_REQUIRED");
554
        body.put("message", "Authentication is required. Send a valid Auth-Token header.");
555
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
556
    }
36321 vikas 557
}