Subversion Repositories SmartDukaan

Rev

Rev 35253 | Rev 35458 | 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
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
    @Autowired
36
    SeasonalOfferRepository seasonalOfferRepository;
37
    @Autowired
38
    GiftRepository giftRepository;
39
    @Autowired
40
    ScratchOfferRepository scratchOfferRepository;
41
    @Autowired
42
    FofoOrderItemRepository fofoOrderItemRepository;
43
    @Autowired
44
    ItemRepository itemRepository;
45
    @Autowired
46
    FofoOrderRepository fofoOrderRepository;
35095 aman 47
 
48
 
34804 aman.kumar 49
    public void processScratchOffer(int fofoOrderId, Set<CustomPaymentOption> paymentOptions, Set<Integer> fofoOrderItemIds) throws ProfitMandiBusinessException {
34474 aman.kumar 50
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderId);
51
        logger.info("Starting scratchOffer for order: {}", fofoOrder);
52
        LocalDate today = LocalDate.now();
34804 aman.kumar 53
        for (Integer orderItemId : fofoOrderItemIds) {
54
            logger.info("Processing order item: {}", orderItemId);
55
            Item item = this.getItemById(orderItemId);
34474 aman.kumar 56
            Integer itemCategoryId = item.getCategoryId();
57
            logger.info("Item category ID: {}", itemCategoryId);
58
            // Find active offer
59
            List<OfferEntity> activeOffers = seasonalOfferRepository.getOffersByDate(today);
34804 aman.kumar 60
            logger.info("Found Active offer: {}", activeOffers);
34474 aman.kumar 61
            OfferEntity eligibleOffer = FindEligibleOffer(activeOffers, fofoOrder);
34804 aman.kumar 62
//            Set<String> allowedPaymentMethods = Arrays.stream(eligibleOffer.getPaymentMethod().split(","))
63
//                    .collect(Collectors.toSet());
64
//
65
//            boolean isOtherPaymentUsed = paymentOptions.stream()
35253 aman 66
//                    .map(option -> String.valueOf(option.getPaymentOptionId()))
34804 aman.kumar 67
//                    .anyMatch(paymentId -> !allowedPaymentMethods.contains(paymentId));
68
//            // proceed with default because user payment method doest not match
69
//            if (isOtherPaymentUsed) {
70
//                logger.info("Customer {} has chosen a different mode of payment.", fofoOrder.getCustomerId());
71
//                return;
72
//            }
34474 aman.kumar 73
            if (eligibleOffer != null) {
74
                logger.info("Found active offer: {}", eligibleOffer.getId());
75
                Integer activeOfferId = eligibleOffer.getId();
76
                logger.info
77
                        ("Active offer ID: {}, Type: {}", activeOfferId, eligibleOffer.getName());
78
                ScratchOffer availedOffer = scratchOfferRepository.getScractchOfferByCustomerIdAndOfferId(fofoOrder.getCustomerId(), activeOfferId);
79
 
80
                if (availedOffer != null) {
81
                    logger.info("Customer {} has already scratched offer ID {}. No new gift will be allotted.", fofoOrder.getCustomerId(), activeOfferId);
35095 aman 82
                    return;
34474 aman.kumar 83
                }
84
 
85
                if (this.processOffer(eligibleOffer, fofoOrder, itemCategoryId)) {
34804 aman.kumar 86
                    logger.info("Successfully processed offer for item: {}", orderItemId);
35095 aman 87
                    break;
34474 aman.kumar 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());
35095 aman 96
            return;
34474 aman.kumar 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();
35095 aman 104
        logger.info("Looking for eligible offer for customer fofoId: {}", customerFofoId);
105
        logger.info("Total active offers to check: {}", activeOffers.size());
106
 
34474 aman.kumar 107
        for (OfferEntity activeOffer : activeOffers) {
35095 aman 108
            logger.info("Checking offer ID: {} with classification: {}", activeOffer.getId(), activeOffer.getClassification());
109
 
34474 aman.kumar 110
            if ("PartnerWise".equals(activeOffer.getClassification())) {
111
                List<GiftEntity> gifts = giftRepository.findByOfferId(activeOffer.getId());
35095 aman 112
                logger.info("Found {} gifts for PartnerWise offer {}", gifts.size(), activeOffer.getId());
34474 aman.kumar 113
 
35095 aman 114
                if (gifts.isEmpty()) {
115
                    logger.warn("No gifts found for PartnerWise offer {}", activeOffer.getId());
116
                    continue;
117
                }
118
 
34474 aman.kumar 119
                for (GiftEntity gift : gifts) {
35095 aman 120
                    logger.info("Checking gift ID: {} with fofoStore: '{}'", gift.getId(), gift.getFofoStore());
121
 
122
                    if (gift.getFofoStore() == null || gift.getFofoStore().trim().isEmpty()) {
123
                        logger.warn("Gift {} has null/empty fofoStore - skipping", gift.getId());
124
                        continue;
125
                    }
126
 
34474 aman.kumar 127
                    String[] fofoStores = gift.getFofoStore().split(",");
35095 aman 128
                    logger.info("Gift {} fofoStores array: {}", gift.getId(), Arrays.toString(fofoStores));
129
 
34474 aman.kumar 130
                    boolean isEligible = Arrays.stream(fofoStores)
35095 aman 131
                            .filter(store -> !store.trim().isEmpty())
132
                            .map(store -> {
133
                                try {
134
                                    int storeId = Integer.parseInt(store.trim());
135
                                    logger.info("Parsed fofoStore: {} (comparing with customer fofoId: {})", storeId, customerFofoId);
136
                                    return storeId;
137
                                } catch (NumberFormatException e) {
138
                                    logger.warn("Invalid fofoId format in gift {}: '{}' - skipping", gift.getId(), store);
139
                                    return -1;
140
                                }
141
                            })
142
                            .anyMatch(fofoStore -> {
143
                                boolean matches = fofoStore == customerFofoId;
144
                                logger.info("FofoStore {} matches customer fofoId {}: {}", fofoStore, customerFofoId, matches);
145
                                return matches;
146
                            });
147
 
148
                    logger.info("Gift {} is eligible for customer fofoId {}: {}", gift.getId(), customerFofoId, isEligible);
149
 
34474 aman.kumar 150
                    if (isEligible) {
35095 aman 151
                        logger.info("Found matching PartnerWise offer: {} for customer fofoId: {}", activeOffer.getId(), customerFofoId);
152
                        return activeOffer;
34474 aman.kumar 153
                    }
154
                }
35095 aman 155
                logger.info("No matching gifts found in PartnerWise offer {} for customer fofoId: {}", activeOffer.getId(), customerFofoId);
156
            } else {
157
                logger.info("Offer {} is not PartnerWise (classification: {})", activeOffer.getId(), activeOffer.getClassification());
34474 aman.kumar 158
            }
159
        }
35095 aman 160
 
161
        logger.info("No PartnerWise offers matched. Looking for non-PartnerWise offers...");
162
 
163
        List<OfferEntity> nonPartnerWiseOffers = activeOffers.stream()
34474 aman.kumar 164
                .filter(offer -> !"PartnerWise".equals(offer.getClassification()))
35095 aman 165
                .collect(Collectors.toList());
166
 
167
        logger.info("Found {} non-PartnerWise offers", nonPartnerWiseOffers.size());
168
 
169
        OfferEntity selectedOffer = nonPartnerWiseOffers.stream().findFirst().orElse(null);
170
 
171
        if (selectedOffer != null) {
172
            logger.info("Selected non-PartnerWise offer: {}", selectedOffer.getId());
173
        } else {
174
            logger.info("No eligible offers found for customer fofoId: {}", customerFofoId);
175
        }
176
 
177
        return selectedOffer;
34474 aman.kumar 178
    }
179
 
35095 aman 180
 
34474 aman.kumar 181
    private Item getItemById(Integer itemId) throws ProfitMandiBusinessException {
182
        logger.info("Getting item by ID: {}", itemId);
183
        Item item = itemRepository.selectById(itemId);
184
        if (item == null) {
185
            logger.warn("Item not found with ID: {}", itemId);
186
        }
187
        return item;
188
    }
189
 
35271 aman 190
    private boolean checkGiftAvailability(LocalDate date, int perDayMaxQty, OfferEntity offer) {
191
        int defaultGiftId = giftRepository.getDefaultGift(offer.getId()).getId();
192
        Integer giftCounts = scratchOfferRepository.countTodaysGiftDistribution(date.atStartOfDay(), date.atTime(LocalTime.MAX), defaultGiftId);
34474 aman.kumar 193
        return giftCounts < perDayMaxQty;
194
    }
195
 
35221 aman 196
    private boolean isAppleItem(FofoOrder fofoOrder) {
197
        List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
198
        if (fofoOrderItems == null || fofoOrderItems.isEmpty()) {
199
            return false;
200
        }
201
        for (FofoOrderItem item : fofoOrderItems) {
202
            if (item != null && item.getBrand() != null && item.getBrand().equalsIgnoreCase("apple")) {
203
                return true;
204
            }
205
        }
206
        return false;
207
    }
34474 aman.kumar 208
    private boolean processOffer(OfferEntity offer, FofoOrder fofoOrder, Integer itemCategoryId) {
35253 aman 209
        List<GiftEntity> allGifts = giftRepository.findNonDefaultGIft(offer.getId());
34474 aman.kumar 210
        logger.info("Processing offer {} for order {}", offer.getId(), fofoOrder.getId());
35221 aman 211
        if (isAppleItem(fofoOrder)) {
212
            GiftEntity lastGift = allGifts.get(allGifts.size() - 1);
213
            if (lastGift.getMaxRedemptions() > 0) {
214
                createScratchOffer(fofoOrder, offer, lastGift);
215
                logger.info("Apple item detected, assigned last gift: {}", lastGift.getName());
216
            } else {
217
                logger.info("Apple last gift exhausted, assigning Better Luck Next Time");
218
                createBetterLuckNextTimeScratch(fofoOrder, offer);
219
            }
220
            return true;
221
        }
34474 aman.kumar 222
        int perDayMaxQty = offer.getUserLimit();
223
        LocalDate today = LocalDate.now();
35271 aman 224
        boolean isMoreGiftAvailable = checkGiftAvailability(today, perDayMaxQty, offer);
34474 aman.kumar 225
        logger.info("Gift availability result: {}", isMoreGiftAvailable);
226
 
35095 aman 227
        if (allGifts.isEmpty()) {
228
            logger.warn("Offer {} has no gifts - cannot process scratch offer", offer.getId());
229
            return false;
230
        }
34474 aman.kumar 231
        if (!isMoreGiftAvailable) {
232
            logger.info("Daily limit reached - assigning default gift");
35253 aman 233
            createDefaultGiftScratch(fofoOrder, offer, giftRepository.getDefaultGift(offer.getId()));
34474 aman.kumar 234
            return true;
235
        }
236
        // Get eligible gifts
237
        List<GiftEntity> eligibleGifts = findEligibleGifts(offer, fofoOrder, itemCategoryId);
238
        if (eligibleGifts.isEmpty()) {
239
            logger.info("No eligible gifts found for offer: {}", offer.getId());
35253 aman 240
            createDefaultGiftScratch(fofoOrder, offer, giftRepository.getDefaultGift(offer.getId()));
34474 aman.kumar 241
            return true;
242
        }
243
 
244
        logger.info("Found {} eligible gifts for offer {}", eligibleGifts.size(), offer.getId());
245
 
246
        // Select gift based on classification
247
        GiftEntity selectedGift = selectGiftByClassification(offer, eligibleGifts, fofoOrder);
248
 
249
        if (selectedGift == null || selectedGift.getMaxRedemptions() <= 0) {
250
            logger.info("No valid gift selected for offer: {}", offer.getId());
251
            createScratchOffer(fofoOrder, offer, allGifts.get(0));
34804 aman.kumar 252
            return true;
34474 aman.kumar 253
        }
254
 
255
        logger.info("Selected gift: {} for order: {}", selectedGift.getId(), fofoOrder.getId());
256
 
257
        // Create scratch offer
258
        createScratchOffer(fofoOrder, offer, selectedGift);
259
        logger.info("Created scratch offer for order: {}", fofoOrder.getId());
260
        return true;
261
    }
262
 
263
 
264
    private List<GiftEntity> findEligibleGifts(OfferEntity offer, FofoOrder fofoOrder, Integer itemCategoryId) {
265
        logger.info("Finding eligible gifts for offer: {} and category: {}", offer.getId(), itemCategoryId);
266
        List<GiftEntity> activeOfferGifts = giftRepository.findByOfferId(offer.getId());
267
        logger.info("Total gifts for offer {}: {}", offer.getId(), activeOfferGifts.size());
268
 
269
        float totalAmount = fofoOrder.getTotalAmount();
270
        logger.info("Order total amount: {}", totalAmount);
271
 
35253 aman 272
 
34474 aman.kumar 273
        List<GiftEntity> eligibleGifts = activeOfferGifts.stream().filter(gift -> isGiftEligible(gift, totalAmount, itemCategoryId)).collect(Collectors.toList());
274
 
275
        logger.info("Filtered to {} eligible gifts", eligibleGifts.size());
276
 
277
        for (GiftEntity gift : activeOfferGifts) {
278
            boolean isEligible = isGiftEligible(gift, totalAmount, itemCategoryId);
279
            logger.info("Gift ID: {}, Name: {}, MinCart: {}, MaxCart: {}, Categories: {}, MaxRedemptions: {}, Eligible: {}",
280
                    gift.getId(), gift.getName(), gift.getMinCartValue(), gift.getMaxCartValue(),
281
                    gift.getProductCategory(), gift.getMaxRedemptions(), isEligible);
282
        }
283
        return eligibleGifts;
284
    }
285
 
286
    private boolean isGiftEligible(GiftEntity gift, float totalAmount, Integer itemCategoryId) {
287
        logger.info("Checking eligibility for gift: {}", gift.getId());
288
        // Check cart value condition
289
        boolean cartValueCondition = totalAmount >= gift.getMinCartValue() && totalAmount <= gift.getMaxCartValue() && gift.getMaxRedemptions() > 0;
290
        logger.info(
291
                "Gift {} cart value condition: {} (order amount: {}, min: {}, max: {}, max redemptions: {})",
292
                gift.getId(), cartValueCondition, totalAmount,
293
                gift.getMinCartValue(), gift.getMaxCartValue(),
294
                gift.getMaxRedemptions());
295
        // Check category condition
296
        boolean categoryCondition = isItemCategoryEligible(gift.getProductCategory(), itemCategoryId);
297
        logger.info
298
                ("Gift {} category condition: {} (item category: {}, gift categories: {})", gift.getId(), categoryCondition, itemCategoryId, gift.getProductCategory());
299
        boolean isEligible = cartValueCondition && categoryCondition;
300
        logger.info
301
                ("Gift {} is eligible: {}", gift.getId(), isEligible);
302
 
303
        return isEligible;
304
    }
305
 
306
    private boolean isItemCategoryEligible(String giftCategories, Integer itemCategoryId) {
307
        logger.info
308
                ("Checking if item category {} is in gift categories: {}", itemCategoryId, giftCategories);
309
 
35095 aman 310
 
34474 aman.kumar 311
        if (giftCategories == null || giftCategories.trim().isEmpty()) {
312
            return false;
313
        }
314
 
315
        return Arrays.stream(giftCategories.split(","))
316
                .filter(category -> !category.trim().isEmpty()) // Filter out empty strings
317
                .map(category -> {
318
                    try {
319
                        return Integer.parseInt(category.trim());
320
                    } catch (NumberFormatException e) {
321
                        logger.warn("Invalid category format in gift categories: {}", category);
35095 aman 322
                        return -1;
34474 aman.kumar 323
                    }
324
                })
325
                .anyMatch(itemCategoryId::equals);
326
    }
327
 
328
    private GiftEntity selectGiftByClassification(OfferEntity offer, List<GiftEntity> eligibleGifts, FofoOrder fofoOrder) {
329
        String classification = offer.getClassification();
330
        logger.info("Selecting gift by classification: {}", classification);
331
 
332
        GiftEntity selectedGift;
333
        switch (classification) {
334
            case "Serial":
335
                logger.info("Using Serial gift selection strategy");
336
                selectedGift = handleSerialGifts(eligibleGifts);
337
                break;
338
            case "Random":
339
                logger.info("Using Random gift selection strategy");
340
                selectedGift = handleRandomGifts(eligibleGifts);
341
                break;
342
            case "PartnerWise":
343
                logger.info("Using PartnerWise gift selection strategy");
344
                selectedGift = handlePartnerWiseGifts(eligibleGifts, fofoOrder);
345
                break;
346
            case "BrandSpecific":
347
                logger.info("Using BrandSpecific gift selection strategy");
348
                selectedGift = handleBrandSpecificGifts(eligibleGifts, fofoOrder);
349
                break;
350
            default:
351
                logger.warn("Unknown classification: {}", classification);
352
                selectedGift = null;
353
        }
354
 
355
        if (selectedGift != null) {
356
            logger.info("Selected gift: {}", selectedGift.getId());
357
        } else {
358
            logger.warn("No gift selected for classification: {}", classification);
359
        }
360
 
361
        return selectedGift;
362
    }
363
 
364
    private GiftEntity handleSerialGifts(List<GiftEntity> gifts) {
365
        logger.info("Handling Serial gifts selection from {} gifts", gifts.size());
366
        return gifts.get(0);
367
    }
368
 
369
    private GiftEntity handleRandomGifts(List<GiftEntity> gifts) {
370
        logger.info("Handling Random gifts selection from {} gifts", gifts.size());
371
        List<GiftEntity> giftPool = new ArrayList<>(gifts.subList(0, gifts.size()));
372
        Collections.shuffle(giftPool);
373
        return giftPool.get(0);
374
    }
375
 
376
    private GiftEntity handlePartnerWiseGifts(List<GiftEntity> gifts, FofoOrder order) {
377
        int fofoId = order.getFofoId();
378
        logger.info("Handling PartnerWise gifts selection from {} gifts for fofoId {}", gifts.size(), fofoId);
379
        return gifts.stream()
380
                .filter(gift -> {
381
                    String[] fofoStores = gift.getFofoStore().split(",");
382
                    return Arrays.stream(fofoStores)
383
                            .map(storeId -> {
384
                                try {
385
                                    return Integer.parseInt(storeId.trim());
386
                                } catch (NumberFormatException e) {
387
                                    logger.warn("Invalid fofoId format in gift {}: {}", gift.getId(), storeId);
35095 aman 388
                                    return -1;
34474 aman.kumar 389
                                }
390
                            })
391
                            .anyMatch(storeId -> storeId == fofoId);
392
                })
393
                .findFirst()
394
                .orElse(null);
395
    }
396
 
397
    private GiftEntity handleBrandSpecificGifts(List<GiftEntity> gifts, FofoOrder order) {
398
        logger.info("Handling BrandSpecific gifts selection from {} gifts for order {}", gifts.size(), order.getId());
399
        // TODO: Add brand-specific logic
400
        logger.warn("BrandSpecific gift selection not implemented yet");
401
        return null;
402
    }
403
 
35221 aman 404
    public void createBetterLuckNextTimeScratch(FofoOrder order, OfferEntity offer) {
405
        try {
406
            ScratchOffer so = new ScratchOffer();
407
            so.setCustomerId(order.getCustomerId());
408
            so.setOfferId(offer.getId());
409
            so.setGiftId(1);
410
            so.setInvoiceNumber(order.getInvoiceNumber());
411
            so.setCreatedTimestamp(LocalDateTime.now());
412
            so.setOfferName(offer.getName());
413
 
414
            scratchOfferRepository.persist(so);
415
            logger.info("Created Better Luck Next Time scratch offer: {}", so);
416
        } catch (Exception e) {
417
            logger.error("Error creating Better Luck Next Time scratch offer: {}", e.getMessage());
418
        }
419
    }
420
 
35095 aman 421
    public void createScratchOffer(FofoOrder order, OfferEntity offer, GiftEntity gift) {
422
        try {
423
            GiftEntity currentGift = giftRepository.findById(gift.getId());
34474 aman.kumar 424
 
35095 aman 425
            if (currentGift == null || currentGift.getMaxRedemptions() <= 0) {
426
                logger.warn("Gift {} has no remaining redemptions", gift.getId());
427
                return;
428
            }
429
 
430
            currentGift.setMaxRedemptions(currentGift.getMaxRedemptions() - 1);
431
            giftRepository.save(currentGift);
432
 
433
            ScratchOffer so = new ScratchOffer();
434
            so.setCustomerId(order.getCustomerId());
435
            so.setOfferId(offer.getId());
436
            so.setGiftId(gift.getId());
437
            so.setInvoiceNumber(order.getInvoiceNumber());
438
            so.setCreatedTimestamp(LocalDateTime.now());
439
            so.setOfferName(gift.getName());
440
 
441
            scratchOfferRepository.persist(so);
442
            logger.info("Created scratch offer: {}", so);
443
 
444
        } catch (Exception e) {
445
            logger.error("Error creating scratch offer: {}", e.getMessage());
446
 
447
        }
34474 aman.kumar 448
    }
449
 
35253 aman 450
    public void createDefaultGiftScratch(FofoOrder order, OfferEntity offer, GiftEntity gift) {
451
        try {
452
            ScratchOffer so = new ScratchOffer();
453
            so.setCustomerId(order.getCustomerId());
454
            so.setOfferId(offer.getId());
455
            so.setGiftId(gift.getId());
456
            so.setInvoiceNumber(order.getInvoiceNumber());
457
            so.setCreatedTimestamp(LocalDateTime.now());
458
            so.setOfferName(gift.getName());
35095 aman 459
 
35253 aman 460
            scratchOfferRepository.persist(so);
461
            logger.info("Created default (unlimited) scratch offer: {}", so);
462
        } catch (Exception e) {
463
            logger.error("Error creating default scratch offer: {}", e.getMessage());
464
        }
465
    }
35095 aman 466
 
35253 aman 467
 
34474 aman.kumar 468
    public boolean createOffer(ScratchRequest request) {
469
        OfferEntity offer = mapToOfferEntity(request);
470
        seasonalOfferRepository.save(offer);
471
        List<GiftEntity> gifts = mapToGiftEntities(request.getGifts(), offer.getId());
472
        gifts.forEach(giftRepository::save);
473
        return offer.getId() > 0 && giftRepository.findByOfferId(offer.getId()).size() == request.getGifts().size();
474
    }
475
 
476
    public boolean updateOffer(Integer offerId, ScratchRequest request) {
477
        OfferEntity existingOffer = seasonalOfferRepository.findById(offerId);
478
        boolean res = false;
479
        if (existingOffer != null) {
480
            updateOfferEntity(existingOffer, request);
481
            updateGifts(existingOffer.getId(), request.getGifts());
482
            res = true;
483
        }
484
        return res;
485
    }
486
 
487
    //update offer
488
    private void updateOfferEntity(OfferEntity existingOffer, ScratchRequest request) {
489
        existingOffer.setName(request.getName());
490
        existingOffer.setDescription(request.getDescription());
491
        existingOffer.setStartDate(request.getStartDate());
492
        existingOffer.setEndDate(request.getEndDate());
493
        existingOffer.setTermsCondition(request.getTermsCondition());
494
        existingOffer.setUserLimit(request.getUserLimit());
495
        existingOffer.setScratchValidity(request.getScratchValidity());
496
        existingOffer.setProductCategory(request.getProductCategory());
497
        existingOffer.setPaymentMethod(request.getPaymentMethod());
498
        existingOffer.setClassification(request.getClassification());
499
    }
500
 
501
    //update gift
502
    private void updateGifts(Integer offerId, List<ScratchRequest.GiftData> giftsData) {
503
        Map<Integer, GiftEntity> existingGifts = giftRepository.findByOfferId(offerId).stream().collect(Collectors.toMap(GiftEntity::getId, Function.identity()));
504
 
505
        for (ScratchRequest.GiftData giftData : giftsData) {
506
            if (giftData.getId() != null && existingGifts.containsKey(giftData.getId())) {
507
                GiftEntity existingGift = existingGifts.get(giftData.getId());
508
                updateGiftEntity(existingGift, giftData);
509
                existingGifts.remove(giftData.getId());
510
            } else {
511
                GiftEntity gift = new GiftEntity();
512
                gift.setName(giftData.getName());
513
                gift.setThumbnailUrl(giftData.getThumbnailUrl());
514
                gift.setMinCartValue(giftData.getMinCartValue());
515
                gift.setMaxRedemptions(giftData.getMaxRedemptions());
516
                gift.setOfferId(offerId);
517
                gift.setMaxCartValue(giftData.getMaxCartValue());
518
                gift.setFofoStore(giftData.getFofoStore());
519
                gift.setProductCategory(giftData.getProductCategory());
35253 aman 520
                gift.setIsDefault(giftData.isDefault());
34474 aman.kumar 521
                giftRepository.save(gift);
522
            }
523
        }
524
    }
525
 
526
    private void updateGiftEntity(GiftEntity gift, ScratchRequest.GiftData data) {
527
        gift.setName(data.getName());
528
        gift.setThumbnailUrl(data.getThumbnailUrl());
529
        gift.setMinCartValue(data.getMinCartValue());
530
        gift.setMaxRedemptions(data.getMaxRedemptions());
531
        gift.setMaxCartValue(data.getMaxCartValue());
532
        gift.setFofoStore(data.getFofoStore());
533
        gift.setProductCategory(data.getProductCategory());
35253 aman 534
        gift.setIsDefault(data.isDefault());
34474 aman.kumar 535
    }
536
 
537
    //offer
538
    private OfferEntity mapToOfferEntity(ScratchRequest request) {
539
        OfferEntity offer = new OfferEntity();
540
        offer.setName(request.getName());
541
        offer.setDescription(request.getDescription());
542
        offer.setOfferImage(request.getOfferImage());
543
        offer.setOfferType(request.getOfferType());
544
        offer.setStartDate(request.getStartDate());
545
        offer.setEndDate(request.getEndDate());
546
        offer.setTermsCondition(request.getTermsCondition());
547
        offer.setUserLimit(request.getUserLimit());
548
        offer.setScratchValidity(request.getScratchValidity());
549
        offer.setProductCategory(request.getProductCategory());
550
        offer.setPaymentMethod(request.getPaymentMethod());
551
        offer.setClassification(request.getClassification());
34804 aman.kumar 552
        logger.info("active flag - " + request.isActive());
34474 aman.kumar 553
        offer.setActive(request.isActive());
554
        return offer;
555
    }
556
 
557
    //gift
558
    private List<GiftEntity> mapToGiftEntities(List<ScratchRequest.GiftData> giftsData, Integer offerId) {
559
        return giftsData.stream().map(giftData -> {
34804 aman.kumar 560
            logger.info("giftData: {}", giftData);
34474 aman.kumar 561
            GiftEntity gift = new GiftEntity();
562
            gift.setName(giftData.getName());
563
            gift.setThumbnailUrl(giftData.getThumbnailUrl());
564
            gift.setMinCartValue(giftData.getMinCartValue());
565
            gift.setMaxRedemptions(giftData.getMaxRedemptions());
566
            gift.setOfferId(offerId);
567
            gift.setMaxCartValue(giftData.getMaxCartValue());
568
            gift.setFofoStore(giftData.getFofoStore());
569
            gift.setProductCategory(giftData.getProductCategory());
35253 aman 570
            gift.setIsDefault(giftData.isDefault());
34474 aman.kumar 571
            return gift;
572
        }).collect(Collectors.toList());
573
    }
574
 
575
}