Subversion Repositories SmartDukaan

Rev

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