Subversion Repositories SmartDukaan

Rev

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