Subversion Repositories SmartDukaan

Rev

Rev 35458 | 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
 
23
import java.time.LocalDate;
24
import java.time.LocalDateTime;
25
import java.time.LocalTime;
26
import java.util.*;
27
import java.util.function.Function;
28
import java.util.stream.Collectors;
29
 
30
@Service
31
public class ScratchService {
32
    private static final Logger logger = LogManager.getLogger(ScratchService.class);
33
    @Autowired
34
    SeasonalOfferRepository seasonalOfferRepository;
35
    @Autowired
36
    GiftRepository giftRepository;
37
    @Autowired
38
    ScratchOfferRepository scratchOfferRepository;
39
    @Autowired
40
    FofoOrderItemRepository fofoOrderItemRepository;
41
    @Autowired
42
    ItemRepository itemRepository;
43
    @Autowired
44
    FofoOrderRepository fofoOrderRepository;
35095 aman 45
 
46
 
34804 aman.kumar 47
    public void processScratchOffer(int fofoOrderId, Set<CustomPaymentOption> paymentOptions, Set<Integer> fofoOrderItemIds) throws ProfitMandiBusinessException {
35980 amit 48
        List<OfferEntity> activeOffers = seasonalOfferRepository.getOffersByDate(LocalDate.now());
49
        if (activeOffers.isEmpty()) {
50
            return;
51
        }
52
 
34474 aman.kumar 53
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(fofoOrderId);
35980 amit 54
        OfferEntity eligibleOffer = findEligibleOffer(activeOffers, fofoOrder);
55
        if (eligibleOffer == null) {
56
            logger.info("No eligible offer for order {}", fofoOrderId);
57
            return;
58
        }
34474 aman.kumar 59
 
35980 amit 60
        ScratchOffer availedOffer = scratchOfferRepository.getScractchOfferByCustomerIdAndOfferId(fofoOrder.getCustomerId(), eligibleOffer.getId());
61
        if (availedOffer != null) {
62
            logger.info("Customer {} already availed offer {}", fofoOrder.getCustomerId(), eligibleOffer.getId());
35095 aman 63
            return;
34474 aman.kumar 64
        }
65
 
35980 amit 66
        this.processOffer(eligibleOffer, fofoOrder);
34474 aman.kumar 67
    }
68
 
35980 amit 69
    private OfferEntity findEligibleOffer(List<OfferEntity> activeOffers, FofoOrder fofoOrder) {
34804 aman.kumar 70
        int customerFofoId = fofoOrder.getFofoId();
35095 aman 71
 
35980 amit 72
        // Check PartnerWise offers first
34474 aman.kumar 73
        for (OfferEntity activeOffer : activeOffers) {
35980 amit 74
            if (!"PartnerWise".equals(activeOffer.getClassification())) {
75
                continue;
76
            }
77
            List<GiftEntity> gifts = giftRepository.findByOfferId(activeOffer.getId());
78
            for (GiftEntity gift : gifts) {
79
                if (gift.getFofoStore() == null || gift.getFofoStore().trim().isEmpty()) {
35095 aman 80
                    continue;
81
                }
35980 amit 82
                boolean matches = Arrays.stream(gift.getFofoStore().split(","))
83
                        .map(String::trim)
84
                        .filter(s -> !s.isEmpty())
85
                        .anyMatch(store -> {
86
                            try {
87
                                return Integer.parseInt(store) == customerFofoId;
88
                            } catch (NumberFormatException e) {
89
                                return false;
90
                            }
91
                        });
92
                if (matches) {
93
                    return activeOffer;
34474 aman.kumar 94
                }
95
            }
96
        }
35095 aman 97
 
35980 amit 98
        // Fallback to first non-PartnerWise offer
99
        return activeOffers.stream()
34474 aman.kumar 100
                .filter(offer -> !"PartnerWise".equals(offer.getClassification()))
35980 amit 101
                .findFirst()
102
                .orElse(null);
34474 aman.kumar 103
    }
104
 
35095 aman 105
 
35271 aman 106
    private boolean checkGiftAvailability(LocalDate date, int perDayMaxQty, OfferEntity offer) {
35980 amit 107
        GiftEntity defaultGift = giftRepository.getDefaultGift(offer.getId());
108
        if (defaultGift == null) return false;
109
        Integer giftCounts = scratchOfferRepository.countTodaysGiftDistribution(date.atStartOfDay(), date.atTime(LocalTime.MAX), defaultGift.getId());
34474 aman.kumar 110
        return giftCounts < perDayMaxQty;
111
    }
112
 
35221 aman 113
    private boolean isAppleItem(FofoOrder fofoOrder) {
114
        List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
115
        if (fofoOrderItems == null || fofoOrderItems.isEmpty()) {
116
            return false;
117
        }
35980 amit 118
        return fofoOrderItems.stream()
119
                .anyMatch(item -> item != null && "apple".equalsIgnoreCase(item.getBrand()));
35221 aman 120
    }
35980 amit 121
 
122
    private boolean processOffer(OfferEntity offer, FofoOrder fofoOrder) {
123
        logger.info("Processing offer {} for order {}", offer.getId(), fofoOrder.getId());
124
 
35253 aman 125
        List<GiftEntity> allGifts = giftRepository.findNonDefaultGIft(offer.getId());
35980 amit 126
        GiftEntity defaultGift = giftRepository.getDefaultGift(offer.getId());
127
 
128
        if (allGifts.isEmpty()) {
129
            logger.warn("Offer {} has no gifts", offer.getId());
130
            return false;
131
        }
132
 
133
        // Apple items always get the last gift
35221 aman 134
        if (isAppleItem(fofoOrder)) {
135
            GiftEntity lastGift = allGifts.get(allGifts.size() - 1);
136
            if (lastGift.getMaxRedemptions() > 0) {
137
                createScratchOffer(fofoOrder, offer, lastGift);
138
            } else {
139
                createBetterLuckNextTimeScratch(fofoOrder, offer);
140
            }
141
            return true;
142
        }
34474 aman.kumar 143
 
35980 amit 144
        // Check daily limit
145
        if (!checkGiftAvailability(LocalDate.now(), offer.getUserLimit(), offer)) {
146
            createDefaultGiftScratch(fofoOrder, offer, defaultGift);
34474 aman.kumar 147
            return true;
148
        }
35980 amit 149
 
150
        // Find eligible gifts by cart value and category
151
        List<FofoOrderItem> orderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
152
        Set<Integer> itemCategoryIds = new HashSet<>();
153
        for (FofoOrderItem orderItem : orderItems) {
154
            try {
155
                Item item = itemRepository.selectById(orderItem.getItemId());
156
                if (item != null) {
157
                    itemCategoryIds.add(item.getCategoryId());
158
                }
159
            } catch (ProfitMandiBusinessException e) {
160
                logger.warn("Item {} not found", orderItem.getItemId());
161
            }
162
        }
163
 
164
        float totalAmount = fofoOrder.getTotalAmount();
165
        List<GiftEntity> allOfferGifts = giftRepository.findByOfferId(offer.getId());
166
        List<GiftEntity> eligibleGifts = allOfferGifts.stream()
167
                .filter(gift -> gift.getMaxRedemptions() > 0
168
                        && totalAmount >= gift.getMinCartValue()
169
                        && totalAmount <= gift.getMaxCartValue()
170
                        && itemCategoryIds.stream().anyMatch(catId -> isItemCategoryEligible(gift.getProductCategory(), catId)))
171
                .collect(Collectors.toList());
172
 
34474 aman.kumar 173
        if (eligibleGifts.isEmpty()) {
35980 amit 174
            createDefaultGiftScratch(fofoOrder, offer, defaultGift);
34474 aman.kumar 175
            return true;
176
        }
177
 
178
        GiftEntity selectedGift = selectGiftByClassification(offer, eligibleGifts, fofoOrder);
179
        if (selectedGift == null || selectedGift.getMaxRedemptions() <= 0) {
35980 amit 180
            createDefaultGiftScratch(fofoOrder, offer, defaultGift);
34804 aman.kumar 181
            return true;
34474 aman.kumar 182
        }
183
 
184
        createScratchOffer(fofoOrder, offer, selectedGift);
185
        return true;
186
    }
187
 
188
 
189
    private boolean isItemCategoryEligible(String giftCategories, Integer itemCategoryId) {
190
        if (giftCategories == null || giftCategories.trim().isEmpty()) {
191
            return false;
192
        }
193
        return Arrays.stream(giftCategories.split(","))
35980 amit 194
                .map(String::trim)
195
                .filter(s -> !s.isEmpty())
34474 aman.kumar 196
                .map(category -> {
197
                    try {
35980 amit 198
                        return Integer.parseInt(category);
34474 aman.kumar 199
                    } catch (NumberFormatException e) {
35095 aman 200
                        return -1;
34474 aman.kumar 201
                    }
202
                })
203
                .anyMatch(itemCategoryId::equals);
204
    }
205
 
206
    private GiftEntity selectGiftByClassification(OfferEntity offer, List<GiftEntity> eligibleGifts, FofoOrder fofoOrder) {
35980 amit 207
        switch (offer.getClassification()) {
34474 aman.kumar 208
            case "Serial":
35980 amit 209
                return eligibleGifts.get(0);
34474 aman.kumar 210
            case "Random":
35980 amit 211
                List<GiftEntity> shuffled = new ArrayList<>(eligibleGifts);
212
                Collections.shuffle(shuffled);
213
                return shuffled.get(0);
34474 aman.kumar 214
            case "PartnerWise":
35980 amit 215
                int fofoId = fofoOrder.getFofoId();
216
                return eligibleGifts.stream()
217
                        .filter(gift -> gift.getFofoStore() != null
218
                                && Arrays.stream(gift.getFofoStore().split(","))
219
                                .map(String::trim)
220
                                .anyMatch(s -> {
221
                                    try { return Integer.parseInt(s) == fofoId; }
222
                                    catch (NumberFormatException e) { return false; }
223
                                }))
224
                        .findFirst()
225
                        .orElse(null);
34474 aman.kumar 226
            default:
35980 amit 227
                logger.warn("Unknown classification: {}", offer.getClassification());
228
                return null;
34474 aman.kumar 229
        }
230
    }
231
 
35221 aman 232
    public void createBetterLuckNextTimeScratch(FofoOrder order, OfferEntity offer) {
35980 amit 233
        ScratchOffer so = new ScratchOffer();
234
        so.setCustomerId(order.getCustomerId());
235
        so.setOfferId(offer.getId());
236
        so.setGiftId(1);
237
        so.setInvoiceNumber(order.getInvoiceNumber());
238
        so.setCreatedTimestamp(LocalDateTime.now());
239
        so.setOfferName(offer.getName());
240
        scratchOfferRepository.persist(so);
35221 aman 241
    }
242
 
35095 aman 243
    public void createScratchOffer(FofoOrder order, OfferEntity offer, GiftEntity gift) {
35980 amit 244
        int updated = giftRepository.decrementMaxRedemptions(gift.getId());
245
        if (updated == 0) {
246
            logger.warn("Gift {} has no remaining redemptions", gift.getId());
247
            return;
248
        }
34474 aman.kumar 249
 
35980 amit 250
        ScratchOffer so = new ScratchOffer();
251
        so.setCustomerId(order.getCustomerId());
252
        so.setOfferId(offer.getId());
253
        so.setGiftId(gift.getId());
254
        so.setInvoiceNumber(order.getInvoiceNumber());
255
        so.setCreatedTimestamp(LocalDateTime.now());
256
        so.setOfferName(gift.getName());
257
        scratchOfferRepository.persist(so);
258
        logger.info("Created scratch offer for order {} gift {}", order.getId(), gift.getId());
34474 aman.kumar 259
    }
260
 
35253 aman 261
    public void createDefaultGiftScratch(FofoOrder order, OfferEntity offer, GiftEntity gift) {
35980 amit 262
        ScratchOffer so = new ScratchOffer();
263
        so.setCustomerId(order.getCustomerId());
264
        so.setOfferId(offer.getId());
265
        so.setGiftId(gift.getId());
266
        so.setInvoiceNumber(order.getInvoiceNumber());
267
        so.setCreatedTimestamp(LocalDateTime.now());
268
        so.setOfferName(gift.getName());
269
        scratchOfferRepository.persist(so);
35253 aman 270
    }
35095 aman 271
 
35253 aman 272
 
34474 aman.kumar 273
    public boolean createOffer(ScratchRequest request) {
274
        OfferEntity offer = mapToOfferEntity(request);
275
        seasonalOfferRepository.save(offer);
276
        List<GiftEntity> gifts = mapToGiftEntities(request.getGifts(), offer.getId());
277
        gifts.forEach(giftRepository::save);
278
        return offer.getId() > 0 && giftRepository.findByOfferId(offer.getId()).size() == request.getGifts().size();
279
    }
280
 
281
    public boolean updateOffer(Integer offerId, ScratchRequest request) {
282
        OfferEntity existingOffer = seasonalOfferRepository.findById(offerId);
283
        boolean res = false;
284
        if (existingOffer != null) {
285
            updateOfferEntity(existingOffer, request);
286
            updateGifts(existingOffer.getId(), request.getGifts());
287
            res = true;
288
        }
289
        return res;
290
    }
291
 
292
    //update offer
293
    private void updateOfferEntity(OfferEntity existingOffer, ScratchRequest request) {
294
        existingOffer.setName(request.getName());
295
        existingOffer.setDescription(request.getDescription());
296
        existingOffer.setStartDate(request.getStartDate());
297
        existingOffer.setEndDate(request.getEndDate());
298
        existingOffer.setTermsCondition(request.getTermsCondition());
299
        existingOffer.setUserLimit(request.getUserLimit());
300
        existingOffer.setScratchValidity(request.getScratchValidity());
301
        existingOffer.setProductCategory(request.getProductCategory());
302
        existingOffer.setPaymentMethod(request.getPaymentMethod());
303
        existingOffer.setClassification(request.getClassification());
304
    }
305
 
306
    //update gift
307
    private void updateGifts(Integer offerId, List<ScratchRequest.GiftData> giftsData) {
308
        Map<Integer, GiftEntity> existingGifts = giftRepository.findByOfferId(offerId).stream().collect(Collectors.toMap(GiftEntity::getId, Function.identity()));
309
 
310
        for (ScratchRequest.GiftData giftData : giftsData) {
311
            if (giftData.getId() != null && existingGifts.containsKey(giftData.getId())) {
312
                GiftEntity existingGift = existingGifts.get(giftData.getId());
313
                updateGiftEntity(existingGift, giftData);
314
                existingGifts.remove(giftData.getId());
315
            } else {
316
                GiftEntity gift = new GiftEntity();
317
                gift.setName(giftData.getName());
318
                gift.setThumbnailUrl(giftData.getThumbnailUrl());
319
                gift.setMinCartValue(giftData.getMinCartValue());
320
                gift.setMaxRedemptions(giftData.getMaxRedemptions());
321
                gift.setOfferId(offerId);
322
                gift.setMaxCartValue(giftData.getMaxCartValue());
323
                gift.setFofoStore(giftData.getFofoStore());
324
                gift.setProductCategory(giftData.getProductCategory());
35253 aman 325
                gift.setIsDefault(giftData.isDefault());
34474 aman.kumar 326
                giftRepository.save(gift);
327
            }
328
        }
329
    }
330
 
331
    private void updateGiftEntity(GiftEntity gift, ScratchRequest.GiftData data) {
332
        gift.setName(data.getName());
333
        gift.setThumbnailUrl(data.getThumbnailUrl());
334
        gift.setMinCartValue(data.getMinCartValue());
335
        gift.setMaxRedemptions(data.getMaxRedemptions());
336
        gift.setMaxCartValue(data.getMaxCartValue());
337
        gift.setFofoStore(data.getFofoStore());
338
        gift.setProductCategory(data.getProductCategory());
35253 aman 339
        gift.setIsDefault(data.isDefault());
34474 aman.kumar 340
    }
341
 
342
    //offer
343
    private OfferEntity mapToOfferEntity(ScratchRequest request) {
344
        OfferEntity offer = new OfferEntity();
345
        offer.setName(request.getName());
346
        offer.setDescription(request.getDescription());
347
        offer.setOfferImage(request.getOfferImage());
348
        offer.setOfferType(request.getOfferType());
349
        offer.setStartDate(request.getStartDate());
350
        offer.setEndDate(request.getEndDate());
351
        offer.setTermsCondition(request.getTermsCondition());
352
        offer.setUserLimit(request.getUserLimit());
353
        offer.setScratchValidity(request.getScratchValidity());
354
        offer.setProductCategory(request.getProductCategory());
355
        offer.setPaymentMethod(request.getPaymentMethod());
356
        offer.setClassification(request.getClassification());
34804 aman.kumar 357
        logger.info("active flag - " + request.isActive());
34474 aman.kumar 358
        offer.setActive(request.isActive());
359
        return offer;
360
    }
361
 
362
    //gift
363
    private List<GiftEntity> mapToGiftEntities(List<ScratchRequest.GiftData> giftsData, Integer offerId) {
364
        return giftsData.stream().map(giftData -> {
34804 aman.kumar 365
            logger.info("giftData: {}", giftData);
34474 aman.kumar 366
            GiftEntity gift = new GiftEntity();
367
            gift.setName(giftData.getName());
368
            gift.setThumbnailUrl(giftData.getThumbnailUrl());
369
            gift.setMinCartValue(giftData.getMinCartValue());
370
            gift.setMaxRedemptions(giftData.getMaxRedemptions());
371
            gift.setOfferId(offerId);
372
            gift.setMaxCartValue(giftData.getMaxCartValue());
373
            gift.setFofoStore(giftData.getFofoStore());
374
            gift.setProductCategory(giftData.getProductCategory());
35253 aman 375
            gift.setIsDefault(giftData.isDefault());
34474 aman.kumar 376
            return gift;
377
        }).collect(Collectors.toList());
378
    }
379
 
380
}