Subversion Repositories SmartDukaan

Rev

Rev 37303 | Rev 37312 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
34474 aman.kumar 1
package com.spice.profitmandi.dao.service;
2
 
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
4
import com.spice.profitmandi.common.model.CustomPaymentOption;
5
import com.spice.profitmandi.dao.entity.catalog.Item;
6
import com.spice.profitmandi.dao.entity.dtr.ScratchOffer;
7
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
35221 aman 8
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
34474 aman.kumar 9
import com.spice.profitmandi.dao.entity.scratch.GiftEntity;
10
import com.spice.profitmandi.dao.entity.scratch.OfferEntity;
11
import com.spice.profitmandi.dao.entity.scratch.ScratchRequest;
12
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
13
import com.spice.profitmandi.dao.repository.dtr.ScratchOfferRepository;
14
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
15
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
16
import com.spice.profitmandi.dao.repository.scratch.GiftRepository;
17
import com.spice.profitmandi.dao.repository.scratch.SeasonalOfferRepository;
18
import org.apache.logging.log4j.LogManager;
19
import org.apache.logging.log4j.Logger;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.stereotype.Service;
22
 
23
import java.time.LocalDate;
24
import java.time.LocalDateTime;
25
import java.time.LocalTime;
26
import java.util.*;
27
import java.util.function.Function;
28
import java.util.stream.Collectors;
29
 
30
@Service
31
public class ScratchService {
32
    private static final Logger logger = LogManager.getLogger(ScratchService.class);
33
    @Autowired
34
    SeasonalOfferRepository seasonalOfferRepository;
35
    @Autowired
36
    GiftRepository giftRepository;
37
    @Autowired
38
    ScratchOfferRepository scratchOfferRepository;
39
    @Autowired
40
    FofoOrderItemRepository fofoOrderItemRepository;
41
    @Autowired
42
    ItemRepository itemRepository;
43
    @Autowired
44
    FofoOrderRepository fofoOrderRepository;
35095 aman 45
 
46
 
34804 aman.kumar 47
    public void processScratchOffer(int fofoOrderId, Set<CustomPaymentOption> paymentOptions, Set<Integer> fofoOrderItemIds) throws ProfitMandiBusinessException {
35980 amit 48
        List<OfferEntity> activeOffers = seasonalOfferRepository.getOffersByDate(LocalDate.now());
49
        if (activeOffers.isEmpty()) {
50
            return;
51
        }
52
 
34474 aman.kumar 53
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderId);
37311 vikas 54
 
55
        // --- V2: offer selection and the per-offer availed check now happen inside processOfferV2 ---
56
        // OfferEntity eligibleOffer = findEligibleOffer(activeOffers, fofoOrder);
57
        // if (eligibleOffer == null) {
58
        //     logger.info("No eligible offer for order {}", fofoOrderId);
59
        //     return;
60
        // }
61
        //
62
        // ScratchOffer availedOffer = scratchOfferRepository.getScractchOfferByCustomerIdAndOfferId(fofoOrder.getCustomerId(), eligibleOffer.getId());
63
        // if (availedOffer != null) {
64
        //     logger.info("Customer {} already availed offer {}", fofoOrder.getCustomerId(), eligibleOffer.getId());
65
        //     return;
66
        // }
67
        //
68
        // this.processOffer(eligibleOffer, fofoOrder);
69
 
70
        this.processOfferV2(activeOffers, fofoOrder);
71
    }
72
 
73
    // ------------------------------------------------------------------------------------------------
74
    // V2 award flow. Order value picks the slab, a random in-stock gift wins, and the offer's default
75
    // gift is the floor. A gift carrying a partner list (fofo_store) is a partner-restricted special and
76
    // is awarded to those partners on bills above SPECIAL_GIFT_MIN_ORDER_VALUE; a gift with no partner
77
    // list belongs to the random pool.
78
    //
79
    // Deliberately bypasses the V1 gating: no per-day user limit, no Apple override, no item-category
80
    // filter, no payment-method filter, no classification switch. The one-gift-per-customer-per-offer
81
    // rule is kept, applied per offer across every active offer.
82
    //
83
    // Nothing below calls a V1 helper, so this whole block can be deleted to roll back.
84
    // ------------------------------------------------------------------------------------------------
85
 
86
    private static final double SPECIAL_GIFT_MIN_ORDER_VALUE = 25000d;
87
 
88
    private void processOfferV2(List<OfferEntity> activeOffers, FofoOrder fofoOrder) {
89
        if (fofoOrder == null) {
90
            logger.error("Order not found, skipping scratch award");
35980 amit 91
            return;
92
        }
34474 aman.kumar 93
 
37311 vikas 94
        List<OfferEntity> eligibleOffers = filterOffersNotAvailed(activeOffers, fofoOrder.getCustomerId());
95
        if (eligibleOffers.isEmpty()) {
96
            logger.info("Customer {} has already availed every active offer", fofoOrder.getCustomerId());
35095 aman 97
            return;
34474 aman.kumar 98
        }
99
 
37311 vikas 100
        Map<Integer, OfferEntity> offerById = new HashMap<>();
101
        List<GiftEntity> pool = new ArrayList<>();
102
        for (OfferEntity offer : eligibleOffers) {
103
            offerById.put(offer.getId(), offer);
104
            List<GiftEntity> gifts = giftRepository.findByOfferId(offer.getId());
105
            if (gifts != null) {
106
                pool.addAll(gifts);
107
            }
108
        }
109
        if (pool.isEmpty()) {
110
            logger.warn("No gifts configured on any active offer, order {} gets no scratch card", fofoOrder.getId());
111
            return;
112
        }
113
 
114
        double amount = fofoOrder.getTotalAmount();
115
 
116
        // 1. Partner-restricted special gift
117
        GiftEntity special = findSpecialPartnerGift(pool, fofoOrder.getFofoId(), amount);
118
        if (special != null && awardWithStock(fofoOrder, offerById.get(special.getOfferId()), special)) {
119
            return;
120
        }
121
 
122
        // 2. Random draw from the order-value slab
123
        List<GiftEntity> candidates = new ArrayList<>(findSlabGifts(pool, amount));
124
        Collections.shuffle(candidates);
125
        for (GiftEntity gift : candidates) {
126
            if (awardWithStock(fofoOrder, offerById.get(gift.getOfferId()), gift)) {
127
                return;
128
            }
129
        }
130
 
131
        // 3. Floor: the offer's default gift, always issued, never Better Luck Next Time
132
        GiftEntity defaultGift = resolveDefaultGift(pool, eligibleOffers);
133
        if (defaultGift == null) {
134
            logger.error("No default gift on any active offer, order {} gets no scratch card", fofoOrder.getId());
135
            return;
136
        }
137
        awardUnconditional(fofoOrder, offerById.get(defaultGift.getOfferId()), defaultGift);
34474 aman.kumar 138
    }
139
 
37311 vikas 140
    /** One gift per customer per offer: drop any offer this customer already holds a card for. */
141
    private List<OfferEntity> filterOffersNotAvailed(List<OfferEntity> offers, int customerId) {
142
        List<OfferEntity> eligible = new ArrayList<>();
143
        for (OfferEntity offer : offers) {
144
            if (scratchOfferRepository.getScractchOfferByCustomerIdAndOfferId(customerId, offer.getId()) == null) {
145
                eligible.add(offer);
146
            } else {
147
                logger.info("Customer {} already availed offer {}", customerId, offer.getId());
148
            }
149
        }
150
        return eligible;
151
    }
152
 
153
    private GiftEntity findSpecialPartnerGift(List<GiftEntity> pool, int fofoId, double amount) {
154
        if (amount <= SPECIAL_GIFT_MIN_ORDER_VALUE) {
155
            return null;
156
        }
157
        GiftEntity match = null;
158
        for (GiftEntity gift : pool) {
159
            if (!hasPartnerList(gift) || !hasStock(gift) || !csvContainsId(gift.getFofoStore(), fofoId)) {
160
                continue;
161
            }
162
            // deterministic when a partner is listed on more than one special gift
163
            if (match == null || gift.getId() < match.getId()) {
164
                match = gift;
165
            }
166
        }
167
        if (match != null) {
168
            logger.info("Special partner gift {} matched partner {} on amount {}", match.getId(), fofoId, amount);
169
        }
170
        return match;
171
    }
172
 
173
    /** Random-pool gifts whose cart-value band contains the order amount. Excludes specials and the default. */
174
    private List<GiftEntity> findSlabGifts(List<GiftEntity> pool, double amount) {
175
        List<GiftEntity> slab = new ArrayList<>();
176
        for (GiftEntity gift : pool) {
177
            if (hasPartnerList(gift) || isDefaultGift(gift) || !hasStock(gift)) {
178
                continue;
179
            }
180
            if (gift.getMinCartValue() == null && gift.getMaxCartValue() == null) {
181
                logger.warn("Gift {} has no cart-value bounds, excluding it from the slab pool", gift.getId());
182
                continue;
183
            }
184
            double min = gift.getMinCartValue() == null ? 0d : gift.getMinCartValue();
185
            double max = gift.getMaxCartValue() == null ? Double.MAX_VALUE : gift.getMaxCartValue();
186
            if (amount >= min && amount <= max) {
187
                slab.add(gift);
188
            }
189
        }
190
        return slab;
191
    }
192
 
193
    /**
194
     * The default gift of the first eligible offer that has one. Resolved from the already-fetched pool
195
     * rather than via getDefaultGift, whose getSingleResult throws when an offer has two defaults.
196
     */
197
    private GiftEntity resolveDefaultGift(List<GiftEntity> pool, List<OfferEntity> offers) {
198
        for (OfferEntity offer : offers) {
199
            GiftEntity best = null;
200
            for (GiftEntity gift : pool) {
201
                if (gift.getOfferId() == null || gift.getOfferId() != offer.getId() || !isDefaultGift(gift)) {
202
                    continue;
203
                }
204
                if (best == null || gift.getId() < best.getId()) {
205
                    best = gift;
206
                }
207
            }
208
            if (best != null) {
209
                return best;
210
            }
211
        }
212
        return null;
213
    }
214
 
215
    /** Award only if the atomic decrement wins; false lets the caller try the next candidate. */
216
    private boolean awardWithStock(FofoOrder order, OfferEntity offer, GiftEntity gift) {
217
        if (offer == null || gift == null) {
218
            return false;
219
        }
220
        if (giftRepository.decrementMaxRedemptions(gift.getId()) == 0) {
221
            logger.warn("Gift {} exhausted by a concurrent order, trying the next candidate", gift.getId());
222
            return false;
223
        }
224
        persistScratchV2(order, offer, gift);
225
        return true;
226
    }
227
 
228
    /** Floor award: attempt the decrement for accounting, but issue the card either way. */
229
    private void awardUnconditional(FofoOrder order, OfferEntity offer, GiftEntity gift) {
230
        if (offer == null || gift == null) {
231
            logger.error("Cannot resolve the floor gift for order {}", order.getId());
232
            return;
233
        }
234
        if (giftRepository.decrementMaxRedemptions(gift.getId()) == 0) {
235
            logger.warn("Default gift {} is out of stock but is still being issued for order {}", gift.getId(), order.getId());
236
        }
237
        persistScratchV2(order, offer, gift);
238
    }
239
 
240
    private void persistScratchV2(FofoOrder order, OfferEntity offer, GiftEntity gift) {
241
        if (order.getInvoiceNumber() == null) {
242
            logger.warn("Order {} has no invoice number, persisting the scratch card anyway", order.getId());
243
        }
244
        ScratchOffer so = new ScratchOffer();
245
        so.setCustomerId(order.getCustomerId());
246
        so.setOfferId(offer.getId());
247
        so.setGiftId(gift.getId());
248
        so.setInvoiceNumber(order.getInvoiceNumber());
249
        so.setCreatedTimestamp(LocalDateTime.now());
250
        so.setOfferName(gift.getName());
251
        scratchOfferRepository.persist(so);
252
        logger.info("Scratch card created for order {} customer {} offer {} gift {} ({})",
253
                order.getId(), order.getCustomerId(), offer.getId(), gift.getId(), gift.getName());
254
    }
255
 
256
    /** A gift with a partner list is partner-restricted; one without belongs to the random pool. */
257
    private static boolean hasPartnerList(GiftEntity gift) {
258
        return gift.getFofoStore() != null && !gift.getFofoStore().trim().isEmpty();
259
    }
260
 
261
    private static boolean hasStock(GiftEntity gift) {
262
        return gift.getMaxRedemptions() != null && gift.getMaxRedemptions() > 0;
263
    }
264
 
265
    private static boolean isDefaultGift(GiftEntity gift) {
266
        return Boolean.TRUE.equals(gift.isDefault());
267
    }
268
 
269
    private static boolean csvContainsId(String csv, int id) {
270
        if (csv == null || csv.trim().isEmpty()) {
271
            return false;
272
        }
273
        for (String token : csv.split(",")) {
274
            String trimmed = token.trim();
275
            if (trimmed.isEmpty()) {
276
                continue;
277
            }
278
            try {
279
                if (Integer.parseInt(trimmed) == id) {
280
                    return true;
281
                }
282
            } catch (NumberFormatException e) {
283
                // malformed entry, skip it
284
            }
285
        }
286
        return false;
287
    }
288
 
289
    // ------------------------------------------------------------------------------ end of V2 block
290
 
35980 amit 291
    private OfferEntity findEligibleOffer(List<OfferEntity> activeOffers, FofoOrder fofoOrder) {
34804 aman.kumar 292
        int customerFofoId = fofoOrder.getFofoId();
35095 aman 293
 
35980 amit 294
        // Check PartnerWise offers first
34474 aman.kumar 295
        for (OfferEntity activeOffer : activeOffers) {
35980 amit 296
            if (!"PartnerWise".equals(activeOffer.getClassification())) {
297
                continue;
298
            }
299
            List<GiftEntity> gifts = giftRepository.findByOfferId(activeOffer.getId());
300
            for (GiftEntity gift : gifts) {
301
                if (gift.getFofoStore() == null || gift.getFofoStore().trim().isEmpty()) {
35095 aman 302
                    continue;
303
                }
35980 amit 304
                boolean matches = Arrays.stream(gift.getFofoStore().split(","))
305
                        .map(String::trim)
306
                        .filter(s -> !s.isEmpty())
307
                        .anyMatch(store -> {
308
                            try {
309
                                return Integer.parseInt(store) == customerFofoId;
310
                            } catch (NumberFormatException e) {
311
                                return false;
312
                            }
313
                        });
314
                if (matches) {
315
                    return activeOffer;
34474 aman.kumar 316
                }
317
            }
318
        }
35095 aman 319
 
35980 amit 320
        // Fallback to first non-PartnerWise offer
321
        return activeOffers.stream()
34474 aman.kumar 322
                .filter(offer -> !"PartnerWise".equals(offer.getClassification()))
35980 amit 323
                .findFirst()
324
                .orElse(null);
34474 aman.kumar 325
    }
326
 
35095 aman 327
 
35271 aman 328
    private boolean checkGiftAvailability(LocalDate date, int perDayMaxQty, OfferEntity offer) {
35980 amit 329
        GiftEntity defaultGift = giftRepository.getDefaultGift(offer.getId());
37299 ranu 330
        // No default gift configured -> no default-gift daily cap to enforce.
331
        // Return true so the caller skips the fallback and proceeds to the picker.
332
        if (defaultGift == null) return true;
35980 amit 333
        Integer giftCounts = scratchOfferRepository.countTodaysGiftDistribution(date.atStartOfDay(), date.atTime(LocalTime.MAX), defaultGift.getId());
34474 aman.kumar 334
        return giftCounts < perDayMaxQty;
335
    }
336
 
35221 aman 337
    private boolean isAppleItem(FofoOrder fofoOrder) {
338
        List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
339
        if (fofoOrderItems == null || fofoOrderItems.isEmpty()) {
340
            return false;
341
        }
35980 amit 342
        return fofoOrderItems.stream()
343
                .anyMatch(item -> item != null && "apple".equalsIgnoreCase(item.getBrand()));
35221 aman 344
    }
35980 amit 345
 
346
    private boolean processOffer(OfferEntity offer, FofoOrder fofoOrder) {
347
        logger.info("Processing offer {} for order {}", offer.getId(), fofoOrder.getId());
348
 
35253 aman 349
        List<GiftEntity> allGifts = giftRepository.findNonDefaultGIft(offer.getId());
35980 amit 350
        GiftEntity defaultGift = giftRepository.getDefaultGift(offer.getId());
351
 
352
        if (allGifts.isEmpty()) {
353
            logger.warn("Offer {} has no gifts", offer.getId());
354
            return false;
355
        }
356
 
37299 ranu 357
        // Compute cart amount + item categories up-front so both the fast-paths (Apple,
358
        // daily-limit) and the main picker can consult them when deciding fallbacks.
359
        List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
360
        Set<Integer> itemCategoryIds = new HashSet<>();
361
        for (FofoOrderItem orderItem : orderItems) {
362
            try {
363
                Item item = itemRepository.selectById(orderItem.getItemId());
364
                if (item != null) {
365
                    itemCategoryIds.add(item.getCategoryId());
366
                }
367
            } catch (ProfitMandiBusinessException e) {
368
                logger.warn("Item {} not found", orderItem.getItemId());
369
            }
370
        }
371
        float totalAmount = fofoOrder.getTotalAmount();
372
 
35980 amit 373
        // Apple items always get the last gift
35221 aman 374
        if (isAppleItem(fofoOrder)) {
375
            GiftEntity lastGift = allGifts.get(allGifts.size() - 1);
376
            if (lastGift.getMaxRedemptions() > 0) {
377
                createScratchOffer(fofoOrder, offer, lastGift);
378
            } else {
379
                createBetterLuckNextTimeScratch(fofoOrder, offer);
380
            }
381
            return true;
382
        }
34474 aman.kumar 383
 
37299 ranu 384
        // Check daily limit — if the default-gift daily cap is hit, we still need to
385
        // honour the default gift's own slab bounds (management rule: default EW must
386
        // not be awarded above its own max_cart_value, e.g. above 20K).
35980 amit 387
        if (!checkGiftAvailability(LocalDate.now(), offer.getUserLimit(), offer)) {
37299 ranu 388
            awardDefaultOrBlnt(fofoOrder, offer, defaultGift, totalAmount, itemCategoryIds,
389
                    "daily-limit-reached");
34474 aman.kumar 390
            return true;
391
        }
35980 amit 392
 
393
        // Find eligible gifts by cart value and category
394
        List<GiftEntity> allOfferGifts = giftRepository.findByOfferId(offer.getId());
395
        List<GiftEntity> eligibleGifts = allOfferGifts.stream()
396
                .filter(gift -> gift.getMaxRedemptions() > 0
397
                        && totalAmount >= gift.getMinCartValue()
398
                        && totalAmount <= gift.getMaxCartValue()
399
                        && itemCategoryIds.stream().anyMatch(catId -> isItemCategoryEligible(gift.getProductCategory(), catId)))
400
                .collect(Collectors.toList());
401
 
34474 aman.kumar 402
        if (eligibleGifts.isEmpty()) {
37299 ranu 403
            awardDefaultOrBlnt(fofoOrder, offer, defaultGift, totalAmount, itemCategoryIds,
404
                    "no-eligible-gifts");
34474 aman.kumar 405
            return true;
406
        }
407
 
408
        GiftEntity selectedGift = selectGiftByClassification(offer, eligibleGifts, fofoOrder);
409
        if (selectedGift == null || selectedGift.getMaxRedemptions() <= 0) {
37299 ranu 410
            awardDefaultOrBlnt(fofoOrder, offer, defaultGift, totalAmount, itemCategoryIds,
411
                    "picker-returned-null-or-exhausted");
34804 aman.kumar 412
            return true;
34474 aman.kumar 413
        }
414
 
415
        createScratchOffer(fofoOrder, offer, selectedGift);
416
        return true;
417
    }
418
 
37299 ranu 419
    /**
420
     * Fallback awarder that respects the default gift's own slab bounds and category.
421
     * If the default gift is genuinely eligible for this cart (cart within its
422
     * min/max, category matches, stock left), award it. Otherwise award Better Luck
423
     * Next Time — this prevents the "EW awarded above 20K" management rule violation
424
     * that could happen when a slab gap or exhausted pool caused the picker to fall
425
     * through with no eligible gift.
426
     */
427
    private void awardDefaultOrBlnt(FofoOrder order, OfferEntity offer, GiftEntity defaultGift,
428
                                    float totalAmount, Set<Integer> itemCategoryIds, String reason) {
429
        // 1) Default gift — only if truly eligible for this cart (respects its slab).
430
        boolean defaultEligible = defaultGift != null
431
                && defaultGift.getMaxRedemptions() != null
432
                && defaultGift.getMaxRedemptions() > 0
433
                && defaultGift.getMinCartValue() != null
434
                && defaultGift.getMaxCartValue() != null
435
                && totalAmount >= defaultGift.getMinCartValue()
436
                && totalAmount <= defaultGift.getMaxCartValue()
437
                && itemCategoryIds.stream().anyMatch(catId ->
438
                isItemCategoryEligible(defaultGift.getProductCategory(), catId));
439
        if (defaultEligible) {
440
            logger.info("Fallback fired for order {} ({}) — default gift {} eligible, awarding it",
441
                    order.getId(), reason, defaultGift.getId());
442
            createDefaultGiftScratch(order, offer, defaultGift);
443
            return;
444
        }
34474 aman.kumar 445
 
37299 ranu 446
        // 2) Neckband safety net — management rule: when EW isn't allowed for this cart
37301 ranu 447
        //    (i.e. default fell through), award a Neckband from this offer's config.
448
        //    Prefer a Neckband whose OWN slab covers this cart amount (so stock
449
        //    decrements from the correct slab, matching per-slab quota intent).
450
        //    Only if no slab-matching Neckband exists do we cross-slab pick.
37299 ranu 451
        List<GiftEntity> allGifts = giftRepository.findByOfferId(offer.getId());
37301 ranu 452
        List<GiftEntity> neckbandCandidates = allGifts.stream()
37299 ranu 453
                .filter(g -> g.getName() != null && "neckband".equalsIgnoreCase(g.getName().trim()))
454
                .filter(g -> g.getMaxRedemptions() != null && g.getMaxRedemptions() > 0)
455
                .filter(g -> itemCategoryIds.stream().anyMatch(catId ->
456
                        isItemCategoryEligible(g.getProductCategory(), catId)))
37301 ranu 457
                .collect(Collectors.toList());
458
 
459
        // First pass — slab-matching Neckband (this cart's own slab).
460
        GiftEntity neckband = neckbandCandidates.stream()
461
                .filter(g -> g.getMinCartValue() != null && g.getMaxCartValue() != null
462
                        && totalAmount >= g.getMinCartValue()
463
                        && totalAmount <= g.getMaxCartValue())
37299 ranu 464
                .findFirst()
465
                .orElse(null);
37301 ranu 466
 
467
        // Second pass — cross-slab pick only if the correct slab has no Neckband left.
468
        if (neckband == null && !neckbandCandidates.isEmpty()) {
469
            neckband = neckbandCandidates.get(0);
470
            logger.info("Fallback for order {} ({}) — no slab-matching Neckband for cart={}; cross-slab picking row {}",
471
                    order.getId(), reason, totalAmount, neckband.getId());
472
        }
473
 
37299 ranu 474
        if (neckband != null) {
37301 ranu 475
            logger.info("Fallback fired for order {} ({}) — awarding Neckband row {} (slab {}-{}) for cart={}",
476
                    order.getId(), reason, neckband.getId(),
477
                    neckband.getMinCartValue(), neckband.getMaxCartValue(), totalAmount);
37299 ranu 478
            createScratchOffer(order, offer, neckband);
479
            return;
480
        }
481
 
482
        // 3) Absolute last resort — no default, no Neckband available anywhere.
483
        logger.warn("Fallback fired for order {} ({}) — no default gift AND no Neckband in stock; awarding Better Luck Next Time",
484
                order.getId(), reason);
485
        createBetterLuckNextTimeScratch(order, offer);
486
    }
487
 
488
 
34474 aman.kumar 489
    private boolean isItemCategoryEligible(String giftCategories, Integer itemCategoryId) {
490
        if (giftCategories == null || giftCategories.trim().isEmpty()) {
491
            return false;
492
        }
493
        return Arrays.stream(giftCategories.split(","))
35980 amit 494
                .map(String::trim)
495
                .filter(s -> !s.isEmpty())
34474 aman.kumar 496
                .map(category -> {
497
                    try {
35980 amit 498
                        return Integer.parseInt(category);
34474 aman.kumar 499
                    } catch (NumberFormatException e) {
35095 aman 500
                        return -1;
34474 aman.kumar 501
                    }
502
                })
503
                .anyMatch(itemCategoryId::equals);
504
    }
505
 
506
    private GiftEntity selectGiftByClassification(OfferEntity offer, List<GiftEntity> eligibleGifts, FofoOrder fofoOrder) {
35980 amit 507
        switch (offer.getClassification()) {
34474 aman.kumar 508
            case "Serial":
35980 amit 509
                return eligibleGifts.get(0);
34474 aman.kumar 510
            case "Random":
35980 amit 511
                List<GiftEntity> shuffled = new ArrayList<>(eligibleGifts);
512
                Collections.shuffle(shuffled);
513
                return shuffled.get(0);
34474 aman.kumar 514
            case "PartnerWise":
35980 amit 515
                int fofoId = fofoOrder.getFofoId();
516
                return eligibleGifts.stream()
517
                        .filter(gift -> gift.getFofoStore() != null
518
                                && Arrays.stream(gift.getFofoStore().split(","))
519
                                .map(String::trim)
520
                                .anyMatch(s -> {
521
                                    try { return Integer.parseInt(s) == fofoId; }
522
                                    catch (NumberFormatException e) { return false; }
523
                                }))
524
                        .findFirst()
525
                        .orElse(null);
34474 aman.kumar 526
            default:
35980 amit 527
                logger.warn("Unknown classification: {}", offer.getClassification());
528
                return null;
34474 aman.kumar 529
        }
530
    }
531
 
35221 aman 532
    public void createBetterLuckNextTimeScratch(FofoOrder order, OfferEntity offer) {
35980 amit 533
        ScratchOffer so = new ScratchOffer();
534
        so.setCustomerId(order.getCustomerId());
535
        so.setOfferId(offer.getId());
536
        so.setGiftId(1);
537
        so.setInvoiceNumber(order.getInvoiceNumber());
538
        so.setCreatedTimestamp(LocalDateTime.now());
539
        so.setOfferName(offer.getName());
540
        scratchOfferRepository.persist(so);
35221 aman 541
    }
542
 
35095 aman 543
    public void createScratchOffer(FofoOrder order, OfferEntity offer, GiftEntity gift) {
35980 amit 544
        int updated = giftRepository.decrementMaxRedemptions(gift.getId());
545
        if (updated == 0) {
37303 ranu 546
            // Race: another concurrent scratch drained this gift's stock to 0 between
547
            // our eligibility read and our atomic decrement. We MUST still give the
548
            // customer a scratch record — either via the Neckband safety-net path or
549
            // (worst case) BLNT. Silent return here caused the "no scratch created"
550
            // bug that silently ate ~12+ orders on 2026-08-13.
551
            logger.warn("Gift {} decrement raced (stock hit 0); falling back to Neckband safety-net for order {}",
552
                    gift.getId(), order.getId());
553
            try {
554
                GiftEntity defaultGift = giftRepository.getDefaultGift(offer.getId());
555
                float totalAmount = order.getTotalAmount();
556
                Set<Integer> itemCategoryIds = new HashSet<>();
557
                List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(order.getId());
558
                for (FofoOrderItem oi : orderItems) {
559
                    try {
560
                        Item it = itemRepository.selectById(oi.getItemId());
561
                        if (it != null) itemCategoryIds.add(it.getCategoryId());
562
                    } catch (Exception ignore) {
563
                    }
564
                }
565
                awardDefaultOrBlnt(order, offer, defaultGift, totalAmount, itemCategoryIds,
566
                        "createScratchOffer-decrement-race");
567
            } catch (Exception e) {
568
                logger.error("Fallback after decrement race also failed for order {} — awarding BLNT",
569
                        order.getId(), e);
570
                createBetterLuckNextTimeScratch(order, offer);
571
            }
35980 amit 572
            return;
573
        }
34474 aman.kumar 574
 
35980 amit 575
        ScratchOffer so = new ScratchOffer();
576
        so.setCustomerId(order.getCustomerId());
577
        so.setOfferId(offer.getId());
578
        so.setGiftId(gift.getId());
579
        so.setInvoiceNumber(order.getInvoiceNumber());
580
        so.setCreatedTimestamp(LocalDateTime.now());
581
        so.setOfferName(gift.getName());
582
        scratchOfferRepository.persist(so);
583
        logger.info("Created scratch offer for order {} gift {}", order.getId(), gift.getId());
34474 aman.kumar 584
    }
585
 
35253 aman 586
    public void createDefaultGiftScratch(FofoOrder order, OfferEntity offer, GiftEntity gift) {
35980 amit 587
        ScratchOffer so = new ScratchOffer();
588
        so.setCustomerId(order.getCustomerId());
589
        so.setOfferId(offer.getId());
590
        so.setGiftId(gift.getId());
591
        so.setInvoiceNumber(order.getInvoiceNumber());
592
        so.setCreatedTimestamp(LocalDateTime.now());
593
        so.setOfferName(gift.getName());
594
        scratchOfferRepository.persist(so);
35253 aman 595
    }
35095 aman 596
 
35253 aman 597
 
34474 aman.kumar 598
    public boolean createOffer(ScratchRequest request) {
599
        OfferEntity offer = mapToOfferEntity(request);
600
        seasonalOfferRepository.save(offer);
601
        List<GiftEntity> gifts = mapToGiftEntities(request.getGifts(), offer.getId());
602
        gifts.forEach(giftRepository::save);
603
        return offer.getId() > 0 && giftRepository.findByOfferId(offer.getId()).size() == request.getGifts().size();
604
    }
605
 
606
    public boolean updateOffer(Integer offerId, ScratchRequest request) {
607
        OfferEntity existingOffer = seasonalOfferRepository.findById(offerId);
608
        boolean res = false;
609
        if (existingOffer != null) {
610
            updateOfferEntity(existingOffer, request);
611
            updateGifts(existingOffer.getId(), request.getGifts());
612
            res = true;
613
        }
614
        return res;
615
    }
616
 
617
    //update offer
618
    private void updateOfferEntity(OfferEntity existingOffer, ScratchRequest request) {
619
        existingOffer.setName(request.getName());
620
        existingOffer.setDescription(request.getDescription());
621
        existingOffer.setStartDate(request.getStartDate());
622
        existingOffer.setEndDate(request.getEndDate());
623
        existingOffer.setTermsCondition(request.getTermsCondition());
624
        existingOffer.setUserLimit(request.getUserLimit());
625
        existingOffer.setScratchValidity(request.getScratchValidity());
626
        existingOffer.setProductCategory(request.getProductCategory());
627
        existingOffer.setPaymentMethod(request.getPaymentMethod());
628
        existingOffer.setClassification(request.getClassification());
629
    }
630
 
631
    //update gift
632
    private void updateGifts(Integer offerId, List<ScratchRequest.GiftData> giftsData) {
633
        Map<Integer, GiftEntity> existingGifts = giftRepository.findByOfferId(offerId).stream().collect(Collectors.toMap(GiftEntity::getId, Function.identity()));
634
 
635
        for (ScratchRequest.GiftData giftData : giftsData) {
636
            if (giftData.getId() != null && existingGifts.containsKey(giftData.getId())) {
637
                GiftEntity existingGift = existingGifts.get(giftData.getId());
638
                updateGiftEntity(existingGift, giftData);
639
                existingGifts.remove(giftData.getId());
640
            } else {
641
                GiftEntity gift = new GiftEntity();
642
                gift.setName(giftData.getName());
643
                gift.setThumbnailUrl(giftData.getThumbnailUrl());
644
                gift.setMinCartValue(giftData.getMinCartValue());
645
                gift.setMaxRedemptions(giftData.getMaxRedemptions());
646
                gift.setOfferId(offerId);
647
                gift.setMaxCartValue(giftData.getMaxCartValue());
648
                gift.setFofoStore(giftData.getFofoStore());
649
                gift.setProductCategory(giftData.getProductCategory());
35253 aman 650
                gift.setIsDefault(giftData.isDefault());
34474 aman.kumar 651
                giftRepository.save(gift);
652
            }
653
        }
654
    }
655
 
656
    private void updateGiftEntity(GiftEntity gift, ScratchRequest.GiftData data) {
657
        gift.setName(data.getName());
658
        gift.setThumbnailUrl(data.getThumbnailUrl());
659
        gift.setMinCartValue(data.getMinCartValue());
660
        gift.setMaxRedemptions(data.getMaxRedemptions());
661
        gift.setMaxCartValue(data.getMaxCartValue());
662
        gift.setFofoStore(data.getFofoStore());
663
        gift.setProductCategory(data.getProductCategory());
35253 aman 664
        gift.setIsDefault(data.isDefault());
34474 aman.kumar 665
    }
666
 
667
    //offer
668
    private OfferEntity mapToOfferEntity(ScratchRequest request) {
669
        OfferEntity offer = new OfferEntity();
670
        offer.setName(request.getName());
671
        offer.setDescription(request.getDescription());
672
        offer.setOfferImage(request.getOfferImage());
673
        offer.setOfferType(request.getOfferType());
674
        offer.setStartDate(request.getStartDate());
675
        offer.setEndDate(request.getEndDate());
676
        offer.setTermsCondition(request.getTermsCondition());
677
        offer.setUserLimit(request.getUserLimit());
678
        offer.setScratchValidity(request.getScratchValidity());
679
        offer.setProductCategory(request.getProductCategory());
680
        offer.setPaymentMethod(request.getPaymentMethod());
681
        offer.setClassification(request.getClassification());
34804 aman.kumar 682
        logger.info("active flag - " + request.isActive());
34474 aman.kumar 683
        offer.setActive(request.isActive());
684
        return offer;
685
    }
686
 
687
    //gift
688
    private List<GiftEntity> mapToGiftEntities(List<ScratchRequest.GiftData> giftsData, Integer offerId) {
689
        return giftsData.stream().map(giftData -> {
34804 aman.kumar 690
            logger.info("giftData: {}", giftData);
34474 aman.kumar 691
            GiftEntity gift = new GiftEntity();
692
            gift.setName(giftData.getName());
693
            gift.setThumbnailUrl(giftData.getThumbnailUrl());
694
            gift.setMinCartValue(giftData.getMinCartValue());
695
            gift.setMaxRedemptions(giftData.getMaxRedemptions());
696
            gift.setOfferId(offerId);
697
            gift.setMaxCartValue(giftData.getMaxCartValue());
698
            gift.setFofoStore(giftData.getFofoStore());
699
            gift.setProductCategory(giftData.getProductCategory());
35253 aman 700
            gift.setIsDefault(giftData.isDefault());
34474 aman.kumar 701
            return gift;
702
        }).collect(Collectors.toList());
703
    }
704
 
705
}