Subversion Repositories SmartDukaan

Rev

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