Subversion Repositories SmartDukaan

Rev

Rev 37015 | Rev 37094 | Go to most recent revision | 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);
152
        if (!auth.isPresent()) return unauthorized();
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);
170
        if (!auth.isPresent()) return unauthorized();
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);
188
        if (!auth.isPresent()) return unauthorized();
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);
215
        if (!auth.isPresent()) return unauthorized();
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);
254
        if (!auth.isPresent()) return unauthorized();
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);
274
        if (!auth.isPresent()) return unauthorized();
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();
369
        BigDecimal tierPrice = BigDecimal.valueOf(resolveCarryBagPrice(fofoId))
370
                .setScale(2, RoundingMode.HALF_UP);
371
        boolean overridden = false;
372
        for (HydratedLine line : cart.getLines()) {
373
            if (line.getProductId() != ProfitMandiConstants.ITEM_CARRY_BAG) continue;
374
            if (line.getPrice() == null) continue;
375
            if (line.getPrice().getSelling() == null
376
                    || line.getPrice().getSelling().compareTo(tierPrice) != 0) {
377
                line.getPrice().setMrp(tierPrice);
378
                line.getPrice().setSelling(tierPrice);
379
                line.getPrice().setSchemeCashback(BigDecimal.ZERO);
380
                overridden = true;
381
            }
382
        }
383
        if (overridden && cart.getPricing() != null) {
384
            // Mirrors CartHydrationServiceImpl.computePricing so grand total
385
            // reflects the overridden carry-bag price.
386
            BigDecimal subtotal = BigDecimal.ZERO;
387
            BigDecimal discounts = BigDecimal.ZERO;
388
            BigDecimal insuranceTotal = BigDecimal.ZERO;
389
            for (HydratedLine line : cart.getLines()) {
390
                if (line.getStatus() != LineStatus.ACTIVE || line.getPrice() == null) continue;
391
                BigDecimal qty = BigDecimal.valueOf(line.getQuantity());
392
                subtotal = subtotal.add(line.getPrice().getMrp().multiply(qty));
393
                BigDecimal cashback = line.getPrice().getSchemeCashback() == null
394
                        ? BigDecimal.ZERO : line.getPrice().getSchemeCashback();
395
                discounts = discounts.add(cashback.multiply(qty));
396
                if (line.getInsurance() != null && line.getInsurance().getPremium() != null) {
397
                    insuranceTotal = insuranceTotal.add(line.getInsurance().getPremium());
398
                }
399
            }
400
            PricingBreakup p = cart.getPricing();
401
            p.setSubtotal(subtotal);
402
            p.setLineDiscounts(discounts);
403
            p.setTaxableBase(subtotal.subtract(discounts));
404
            p.setGrandTotal(p.getTaxableBase().add(insuranceTotal));
405
        }
406
        return result;
407
    }
408
 
37015 ranu 409
    private float resolveCarryBagPrice(int fofoId) {
410
        PartnerType tier = null;
411
        try {
412
            tier = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
413
        } catch (Exception e) {
414
            // fall through to premium price
415
        }
416
        if (tier == PartnerType.SILVER || tier == PartnerType.BRONZE) {
417
            try {
418
                TagListing tl = tagListingRepository.selectByItemId(ProfitMandiConstants.ITEM_CARRY_BAG);
419
                if (tl != null) return tl.getSellingPrice();
420
            } catch (Exception e) {
421
                // fall through to premium price
422
            }
423
        }
424
        return CARRY_BAG_PREMIUM_PRICE;
425
    }
426
 
36376 aman 427
    private List<CartItem> currentLinesAsItems(int cartId) {
428
        List<CartLine> lines = cartLineRepository.selectAllByCart(cartId);
429
        if (lines == null) return new ArrayList<>();
430
        return lines.stream()
431
                .map(l -> {
432
                    CartItem ci = new CartItem(l.getQuantity(), l.getItemId());
433
                    ci.setSellingPrice(l.getActualPrice());
434
                    return ci;
435
                })
436
                .collect(Collectors.toList());
437
    }
438
 
439
    public static class AddCartItemRequest {
440
        public int productId;
441
        public int quantity;
442
    }
443
 
444
    // -----------------------------------------------------------------
445
    // Auth helpers — login is mandatory per product decision (2026-04-21).
446
    // Guest carts are not supported; unauthenticated requests get 401.
447
    //
448
    // Returns the auth context as an Optional rather than throwing, because
449
    // GlobalExceptionHandler's @ExceptionHandler(Exception.class) would
450
    // otherwise wrap any RuntimeException as HTTP 500 regardless of
451
    // @ResponseStatus annotations on the exception class.
452
    // -----------------------------------------------------------------
453
 
454
    private static final class AuthCtx {
455
        final int userId;
456
        final int storeId;
457
        final int cartId;
458
        AuthCtx(int userId, int storeId, int cartId) {
459
            this.userId = userId; this.storeId = storeId; this.cartId = cartId;
460
        }
461
    }
462
 
463
    /**
464
     * Resolves the authenticated partner's PROCUREMENT cart. v2/cart/* is
465
     * procurement-only. Tertiary billing drafts live under /v2/billing/* and
466
     * are resolved per-cartId there.
467
     */
468
    private java.util.Optional<AuthCtx> resolveAuth(HttpServletRequest request) {
469
        Object userIdAttr = request.getAttribute("userId");
470
        if (userIdAttr == null) {
471
            return java.util.Optional.empty();
472
        }
473
        int userId;
474
        try {
475
            userId = (int) userIdAttr;
476
        } catch (ClassCastException e) {
477
            return java.util.Optional.empty();
478
        }
479
        if (userId <= 0) {
480
            return java.util.Optional.empty();
481
        }
482
        Object userInfoAttr = request.getAttribute("userInfo");
483
        int storeId = userInfoAttr instanceof UserInfo ? ((UserInfo) userInfoAttr).getRetailerId() : 0;
484
 
485
        UserCart uc = userAccountRepository.getUserCart(userId);
486
        if (uc == null || uc.getCartId() <= 0) {
487
            return java.util.Optional.empty();
488
        }
489
        return java.util.Optional.of(new AuthCtx(userId, storeId, uc.getCartId()));
490
    }
491
 
492
    private ResponseEntity<?> unauthorized() {
493
        java.util.Map<String, Object> body = new java.util.HashMap<>();
494
        body.put("responseStatus", "FAILURE");
495
        body.put("statusCode", 401);
496
        body.put("statusMessage", "LOGIN_REQUIRED");
497
        body.put("message", "Authentication is required. Send a valid Auth-Token header.");
498
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body);
499
    }
36321 vikas 500
}