Subversion Repositories SmartDukaan

Rev

Rev 34474 | Rev 35095 | 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;
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
import org.springframework.transaction.annotation.Transactional;
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
@Transactional(rollbackFor = Throwable.class)
32
public class ScratchService {
33
    private static final Logger logger = LogManager.getLogger(ScratchService.class);
34
    @Autowired
35
    SeasonalOfferRepository seasonalOfferRepository;
36
    @Autowired
37
    GiftRepository giftRepository;
38
    @Autowired
39
    ScratchOfferRepository scratchOfferRepository;
40
    @Autowired
41
    FofoOrderItemRepository fofoOrderItemRepository;
42
    @Autowired
43
    ItemRepository itemRepository;
44
    @Autowired
45
    FofoOrderRepository fofoOrderRepository;
34804 aman.kumar 46
//    @Transactional(propagation = Propagation.REQUIRES_NEW)
47
    public void processScratchOffer(int fofoOrderId, Set<CustomPaymentOption> paymentOptions, Set<Integer> fofoOrderItemIds) throws ProfitMandiBusinessException {
34474 aman.kumar 48
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderId);
49
        logger.info("Starting scratchOffer for order: {}", fofoOrder);
50
        LocalDate today = LocalDate.now();
34804 aman.kumar 51
        for (Integer orderItemId : fofoOrderItemIds) {
52
            logger.info("Processing order item: {}", orderItemId);
53
            Item item = this.getItemById(orderItemId);
34474 aman.kumar 54
            Integer itemCategoryId = item.getCategoryId();
55
            logger.info("Item category ID: {}", itemCategoryId);
56
            // Find active offer
57
            List<OfferEntity> activeOffers = seasonalOfferRepository.getOffersByDate(today);
34804 aman.kumar 58
            logger.info("Found Active offer: {}", activeOffers);
34474 aman.kumar 59
            OfferEntity eligibleOffer = FindEligibleOffer(activeOffers, fofoOrder);
34804 aman.kumar 60
//            Set<String> allowedPaymentMethods = Arrays.stream(eligibleOffer.getPaymentMethod().split(","))
61
//                    .collect(Collectors.toSet());
62
//
63
//            boolean isOtherPaymentUsed = paymentOptions.stream()
64
//                    .map(option -> String.valueOf(option.getPaymentOptionId())) // Replace with the correct getter
65
//                    .anyMatch(paymentId -> !allowedPaymentMethods.contains(paymentId));
66
//            // proceed with default because user payment method doest not match
67
//            if (isOtherPaymentUsed) {
68
//                logger.info("Customer {} has chosen a different mode of payment.", fofoOrder.getCustomerId());
69
//                return;
70
//            }
34474 aman.kumar 71
            if (eligibleOffer != null) {
72
                logger.info("Found active offer: {}", eligibleOffer.getId());
73
//                 Get the customer's scratch list and check if this offer is already there
74
                Integer activeOfferId = eligibleOffer.getId();
75
                logger.info
76
                        ("Active offer ID: {}, Type: {}", activeOfferId, eligibleOffer.getName());
77
                ScratchOffer availedOffer = scratchOfferRepository.getScractchOfferByCustomerIdAndOfferId(fofoOrder.getCustomerId(), activeOfferId);
78
 
79
                if (availedOffer != null) {
80
                    logger.info("Customer {} has already scratched offer ID {}. No new gift will be allotted.", fofoOrder.getCustomerId(), activeOfferId);
81
                    return; // Customer already has this offer
82
                }
83
 
84
                // Proceed with processing the offer since customer hasn't scratched it yet
85
                if (this.processOffer(eligibleOffer, fofoOrder, itemCategoryId)) {
34804 aman.kumar 86
                    logger.info("Successfully processed offer for item: {}", orderItemId);
34474 aman.kumar 87
                    return; // Successfully processed an offer
88
                } else {
34804 aman.kumar 89
                    logger.info("Failed to process offer for item: {}", orderItemId);
34474 aman.kumar 90
                }
91
            } else {
92
                logger.info("No active offers found for today: {}", today);
93
            }
94
 
95
            logger.info("No eligible gifts found for any items in order: {}", fofoOrder.getId());
96
            return; // No eligible gifts found for any items
97
        }
98
 
99
        logger.info("No eligible gifts found for any items in order: {}", fofoOrder.getId());
100
    }
101
 
102
    private OfferEntity FindEligibleOffer(List<OfferEntity> activeOffers, FofoOrder fofoOrder) {
34804 aman.kumar 103
        int customerFofoId = fofoOrder.getFofoId();
34474 aman.kumar 104
        for (OfferEntity activeOffer : activeOffers) {
105
            if ("PartnerWise".equals(activeOffer.getClassification())) {
106
                List<GiftEntity> gifts = giftRepository.findByOfferId(activeOffer.getId());
107
 
108
                for (GiftEntity gift : gifts) {
109
                    String[] fofoStores = gift.getFofoStore().split(",");
110
                    boolean isEligible = Arrays.stream(fofoStores)
111
                            .map(Integer::parseInt) // Convert string to int
34804 aman.kumar 112
                            .anyMatch(fofoStore -> fofoStore == customerFofoId);
34474 aman.kumar 113
                    if (isEligible) {
114
                        return activeOffer;  // Return the matching PARTNERWISE offer
115
                    }
116
                }
117
            }
118
        }
119
        // If no PARTNERWISE offer matches, return the first non-PARTNERWISE offer (if any)
120
        return activeOffers.stream()
121
                .filter(offer -> !"PartnerWise".equals(offer.getClassification()))
122
                .findFirst()
123
                .orElse(null);
124
    }
125
 
126
    private Item getItemById(Integer itemId) throws ProfitMandiBusinessException {
127
        logger.info("Getting item by ID: {}", itemId);
128
        Item item = itemRepository.selectById(itemId);
129
        if (item == null) {
130
            logger.warn("Item not found with ID: {}", itemId);
131
        }
132
        return item;
133
    }
134
 
135
    private boolean checkGiftAvailability(LocalDate date, int perDayMaxQty) {
136
        Integer giftCounts = scratchOfferRepository.countTodaysGiftDistribution(date.atStartOfDay(), date.atTime(LocalTime.MAX));
137
        return giftCounts < perDayMaxQty;
138
    }
139
 
140
    private boolean processOffer(OfferEntity offer, FofoOrder fofoOrder, Integer itemCategoryId) {
141
        List<GiftEntity> allGifts = giftRepository.findByOfferId(offer.getId());
142
        logger.info("Processing offer {} for order {}", offer.getId(), fofoOrder.getId());
143
        //Is more gift available
144
        int perDayMaxQty = offer.getUserLimit();
145
        LocalDate today = LocalDate.now();
146
        boolean isMoreGiftAvailable = checkGiftAvailability(today, perDayMaxQty);
147
        logger.info("Gift availability result: {}", isMoreGiftAvailable);
148
 
149
        if (!isMoreGiftAvailable) {
150
            logger.info("Daily limit reached - assigning default gift");
151
            createScratchOffer(fofoOrder, offer, allGifts.get(0));
152
            return true;
153
        }
154
        // Get eligible gifts
155
        List<GiftEntity> eligibleGifts = findEligibleGifts(offer, fofoOrder, itemCategoryId);
156
        if (eligibleGifts.isEmpty()) {
157
            logger.info("No eligible gifts found for offer: {}", offer.getId());
158
            createScratchOffer(fofoOrder, offer, allGifts.get(0));
159
            return true;
160
        }
161
 
162
        logger.info("Found {} eligible gifts for offer {}", eligibleGifts.size(), offer.getId());
163
 
164
        // Select gift based on classification
165
        GiftEntity selectedGift = selectGiftByClassification(offer, eligibleGifts, fofoOrder);
166
 
167
        if (selectedGift == null || selectedGift.getMaxRedemptions() <= 0) {
168
            logger.info("No valid gift selected for offer: {}", offer.getId());
169
            createScratchOffer(fofoOrder, offer, allGifts.get(0));
34804 aman.kumar 170
            return true;
34474 aman.kumar 171
        }
172
 
173
        logger.info("Selected gift: {} for order: {}", selectedGift.getId(), fofoOrder.getId());
174
 
175
        // Create scratch offer
176
        createScratchOffer(fofoOrder, offer, selectedGift);
177
        logger.info("Created scratch offer for order: {}", fofoOrder.getId());
178
        return true;
179
    }
180
 
181
 
182
    private List<GiftEntity> findEligibleGifts(OfferEntity offer, FofoOrder fofoOrder, Integer itemCategoryId) {
183
        logger.info("Finding eligible gifts for offer: {} and category: {}", offer.getId(), itemCategoryId);
184
        List<GiftEntity> activeOfferGifts = giftRepository.findByOfferId(offer.getId());
185
        logger.info("Total gifts for offer {}: {}", offer.getId(), activeOfferGifts.size());
186
 
187
        float totalAmount = fofoOrder.getTotalAmount();
188
        logger.info("Order total amount: {}", totalAmount);
189
 
190
        // Filter eligible gifts
191
        List<GiftEntity> eligibleGifts = activeOfferGifts.stream().filter(gift -> isGiftEligible(gift, totalAmount, itemCategoryId)).collect(Collectors.toList());
192
 
193
        logger.info("Filtered to {} eligible gifts", eligibleGifts.size());
194
 
195
        for (GiftEntity gift : activeOfferGifts) {
196
            boolean isEligible = isGiftEligible(gift, totalAmount, itemCategoryId);
197
            logger.info("Gift ID: {}, Name: {}, MinCart: {}, MaxCart: {}, Categories: {}, MaxRedemptions: {}, Eligible: {}",
198
                    gift.getId(), gift.getName(), gift.getMinCartValue(), gift.getMaxCartValue(),
199
                    gift.getProductCategory(), gift.getMaxRedemptions(), isEligible);
200
        }
201
        return eligibleGifts;
202
    }
203
 
204
    private boolean isGiftEligible(GiftEntity gift, float totalAmount, Integer itemCategoryId) {
205
        logger.info("Checking eligibility for gift: {}", gift.getId());
206
        // Check cart value condition
207
        boolean cartValueCondition = totalAmount >= gift.getMinCartValue() && totalAmount <= gift.getMaxCartValue() && gift.getMaxRedemptions() > 0;
208
        logger.info(
209
                "Gift {} cart value condition: {} (order amount: {}, min: {}, max: {}, max redemptions: {})",
210
                gift.getId(), cartValueCondition, totalAmount,
211
                gift.getMinCartValue(), gift.getMaxCartValue(),
212
                gift.getMaxRedemptions());
213
        // Check category condition
214
        boolean categoryCondition = isItemCategoryEligible(gift.getProductCategory(), itemCategoryId);
215
        logger.info
216
                ("Gift {} category condition: {} (item category: {}, gift categories: {})", gift.getId(), categoryCondition, itemCategoryId, gift.getProductCategory());
217
        boolean isEligible = cartValueCondition && categoryCondition;
218
        logger.info
219
                ("Gift {} is eligible: {}", gift.getId(), isEligible);
220
 
221
        return isEligible;
222
    }
223
 
224
    private boolean isItemCategoryEligible(String giftCategories, Integer itemCategoryId) {
225
        logger.info
226
                ("Checking if item category {} is in gift categories: {}", itemCategoryId, giftCategories);
227
 
228
        // Handle null or empty categories
229
        if (giftCategories == null || giftCategories.trim().isEmpty()) {
230
            return false;
231
        }
232
 
233
        return Arrays.stream(giftCategories.split(","))
234
                .filter(category -> !category.trim().isEmpty()) // Filter out empty strings
235
                .map(category -> {
236
                    try {
237
                        return Integer.parseInt(category.trim());
238
                    } catch (NumberFormatException e) {
239
                        logger.warn("Invalid category format in gift categories: {}", category);
240
                        return -1; // Will not match any real category ID
241
                    }
242
                })
243
                .anyMatch(itemCategoryId::equals);
244
    }
245
 
246
    private GiftEntity selectGiftByClassification(OfferEntity offer, List<GiftEntity> eligibleGifts, FofoOrder fofoOrder) {
247
        String classification = offer.getClassification();
248
        logger.info("Selecting gift by classification: {}", classification);
249
 
250
        GiftEntity selectedGift;
251
        switch (classification) {
252
            case "Serial":
253
                logger.info("Using Serial gift selection strategy");
254
                selectedGift = handleSerialGifts(eligibleGifts);
255
                break;
256
            case "Random":
257
                logger.info("Using Random gift selection strategy");
258
                selectedGift = handleRandomGifts(eligibleGifts);
259
                break;
260
            case "PartnerWise":
261
                logger.info("Using PartnerWise gift selection strategy");
262
                selectedGift = handlePartnerWiseGifts(eligibleGifts, fofoOrder);
263
                break;
264
            case "BrandSpecific":
265
                logger.info("Using BrandSpecific gift selection strategy");
266
                selectedGift = handleBrandSpecificGifts(eligibleGifts, fofoOrder);
267
                break;
268
            default:
269
                logger.warn("Unknown classification: {}", classification);
270
                selectedGift = null;
271
        }
272
 
273
        if (selectedGift != null) {
274
            logger.info("Selected gift: {}", selectedGift.getId());
275
        } else {
276
            logger.warn("No gift selected for classification: {}", classification);
277
        }
278
 
279
        return selectedGift;
280
    }
281
 
282
    private GiftEntity handleSerialGifts(List<GiftEntity> gifts) {
283
        logger.info("Handling Serial gifts selection from {} gifts", gifts.size());
284
        return gifts.get(0);
285
    }
286
 
287
    private GiftEntity handleRandomGifts(List<GiftEntity> gifts) {
288
        logger.info("Handling Random gifts selection from {} gifts", gifts.size());
289
        // Create a new list for remaining gifts to avoid modifying the original list
290
        List<GiftEntity> giftPool = new ArrayList<>(gifts.subList(0, gifts.size()));
291
        // Shuffle the gift pool to increase randomness
292
        Collections.shuffle(giftPool);
293
        // Find a valid gift from the shuffled pool
294
        return giftPool.get(0);
295
    }
296
 
297
    private GiftEntity handlePartnerWiseGifts(List<GiftEntity> gifts, FofoOrder order) {
298
        int fofoId = order.getFofoId();
299
        logger.info("Handling PartnerWise gifts selection from {} gifts for fofoId {}", gifts.size(), fofoId);
300
        // Stream approach - consistent with FindEligibleOffer method
301
        return gifts.stream()
302
                .filter(gift -> {
303
                    String[] fofoStores = gift.getFofoStore().split(",");
304
                    return Arrays.stream(fofoStores)
305
                            .map(storeId -> {
306
                                try {
307
                                    return Integer.parseInt(storeId.trim());
308
                                } catch (NumberFormatException e) {
309
                                    logger.warn("Invalid fofoId format in gift {}: {}", gift.getId(), storeId);
310
                                    return -1; // Invalid ID that won't match
311
                                }
312
                            })
313
                            .anyMatch(storeId -> storeId == fofoId);
314
                })
315
                .findFirst()
316
                .orElse(null);
317
    }
318
 
319
    private GiftEntity handleBrandSpecificGifts(List<GiftEntity> gifts, FofoOrder order) {
320
        logger.info("Handling BrandSpecific gifts selection from {} gifts for order {}", gifts.size(), order.getId());
321
        // TODO: Add brand-specific logic
322
        logger.warn("BrandSpecific gift selection not implemented yet");
323
        return null;
324
    }
325
 
326
    private void createScratchOffer(FofoOrder order, OfferEntity offer, GiftEntity gift) {
327
        ScratchOffer so = new ScratchOffer();
328
        so.setCustomerId(order.getCustomerId());
329
        so.setOfferId(offer.getId());
330
        so.setGiftId(gift.getId());
331
        so.setInvoiceNumber(order.getInvoiceNumber());
332
        so.setCreatedTimestamp(LocalDateTime.now());
333
        so.setOfferName(gift.getName());
334
 
335
        gift.setMaxRedemptions(gift.getMaxRedemptions() - 1);
336
        scratchOfferRepository.persist(so);
34804 aman.kumar 337
        logger.info("Created scratch offer: {}", so);
34474 aman.kumar 338
    }
339
 
340
    public boolean createOffer(ScratchRequest request) {
341
        OfferEntity offer = mapToOfferEntity(request);
342
        seasonalOfferRepository.save(offer);
343
        List<GiftEntity> gifts = mapToGiftEntities(request.getGifts(), offer.getId());
344
        gifts.forEach(giftRepository::save);
345
        return offer.getId() > 0 && giftRepository.findByOfferId(offer.getId()).size() == request.getGifts().size();
346
    }
347
 
348
    public boolean updateOffer(Integer offerId, ScratchRequest request) {
349
        OfferEntity existingOffer = seasonalOfferRepository.findById(offerId);
350
        boolean res = false;
351
        if (existingOffer != null) {
352
            updateOfferEntity(existingOffer, request);
353
            updateGifts(existingOffer.getId(), request.getGifts());
354
            res = true;
355
        }
356
        return res;
357
    }
358
 
359
    //update offer
360
    private void updateOfferEntity(OfferEntity existingOffer, ScratchRequest request) {
361
        existingOffer.setName(request.getName());
362
        existingOffer.setDescription(request.getDescription());
363
        existingOffer.setStartDate(request.getStartDate());
364
        existingOffer.setEndDate(request.getEndDate());
365
        existingOffer.setTermsCondition(request.getTermsCondition());
366
        existingOffer.setUserLimit(request.getUserLimit());
367
        existingOffer.setScratchValidity(request.getScratchValidity());
368
        existingOffer.setProductCategory(request.getProductCategory());
369
        existingOffer.setPaymentMethod(request.getPaymentMethod());
370
        existingOffer.setClassification(request.getClassification());
371
    }
372
 
373
    //update gift
374
    private void updateGifts(Integer offerId, List<ScratchRequest.GiftData> giftsData) {
375
        Map<Integer, GiftEntity> existingGifts = giftRepository.findByOfferId(offerId).stream().collect(Collectors.toMap(GiftEntity::getId, Function.identity()));
376
 
377
        for (ScratchRequest.GiftData giftData : giftsData) {
378
            if (giftData.getId() != null && existingGifts.containsKey(giftData.getId())) {
379
                GiftEntity existingGift = existingGifts.get(giftData.getId());
380
                updateGiftEntity(existingGift, giftData);
381
                existingGifts.remove(giftData.getId());
382
            } else {
383
                GiftEntity gift = new GiftEntity();
384
                gift.setName(giftData.getName());
385
                gift.setThumbnailUrl(giftData.getThumbnailUrl());
386
                gift.setMinCartValue(giftData.getMinCartValue());
387
                gift.setMaxRedemptions(giftData.getMaxRedemptions());
388
                gift.setOfferId(offerId);
389
                gift.setMaxCartValue(giftData.getMaxCartValue());
390
                gift.setFofoStore(giftData.getFofoStore());
391
                gift.setProductCategory(giftData.getProductCategory());
392
                giftRepository.save(gift);
393
            }
394
        }
395
    }
396
 
397
    private void updateGiftEntity(GiftEntity gift, ScratchRequest.GiftData data) {
398
        gift.setName(data.getName());
399
        gift.setThumbnailUrl(data.getThumbnailUrl());
400
        gift.setMinCartValue(data.getMinCartValue());
401
        gift.setMaxRedemptions(data.getMaxRedemptions());
402
        gift.setMaxCartValue(data.getMaxCartValue());
403
        gift.setFofoStore(data.getFofoStore());
404
        gift.setProductCategory(data.getProductCategory());
405
    }
406
 
407
    //offer
408
    private OfferEntity mapToOfferEntity(ScratchRequest request) {
409
        OfferEntity offer = new OfferEntity();
410
        offer.setName(request.getName());
411
        offer.setDescription(request.getDescription());
412
        offer.setOfferImage(request.getOfferImage());
413
        offer.setOfferType(request.getOfferType());
414
        offer.setStartDate(request.getStartDate());
415
        offer.setEndDate(request.getEndDate());
416
        offer.setTermsCondition(request.getTermsCondition());
417
        offer.setUserLimit(request.getUserLimit());
418
        offer.setScratchValidity(request.getScratchValidity());
419
        offer.setProductCategory(request.getProductCategory());
420
        offer.setPaymentMethod(request.getPaymentMethod());
421
        offer.setClassification(request.getClassification());
34804 aman.kumar 422
        logger.info("active flag - " + request.isActive());
34474 aman.kumar 423
        offer.setActive(request.isActive());
424
        return offer;
425
    }
426
 
427
    //gift
428
    private List<GiftEntity> mapToGiftEntities(List<ScratchRequest.GiftData> giftsData, Integer offerId) {
429
        return giftsData.stream().map(giftData -> {
34804 aman.kumar 430
            logger.info("giftData: {}", giftData);
34474 aman.kumar 431
            GiftEntity gift = new GiftEntity();
432
            gift.setName(giftData.getName());
433
            gift.setThumbnailUrl(giftData.getThumbnailUrl());
434
            gift.setMinCartValue(giftData.getMinCartValue());
435
            gift.setMaxRedemptions(giftData.getMaxRedemptions());
436
            gift.setOfferId(offerId);
437
            gift.setMaxCartValue(giftData.getMaxCartValue());
438
            gift.setFofoStore(giftData.getFofoStore());
439
            gift.setProductCategory(giftData.getProductCategory());
440
            return gift;
441
        }).collect(Collectors.toList());
442
    }
443
 
444
}