Subversion Repositories SmartDukaan

Rev

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