Subversion Repositories SmartDukaan

Rev

Rev 33634 | Rev 34017 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
22653 ashik.ali 1
package com.spice.profitmandi.service.scheme;
2
 
24307 amit.gupta 3
import com.spice.profitmandi.common.enumuration.ItemType;
29927 amit.gupta 4
import com.spice.profitmandi.common.enumuration.MessageType;
22653 ashik.ali 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
23019 ashik.ali 7
import com.spice.profitmandi.common.model.SchemeModel;
29927 amit.gupta 8
import com.spice.profitmandi.common.model.SendNotificationModel;
29584 manish 9
import com.spice.profitmandi.common.services.ReporticoService;
27395 amit.gupta 10
import com.spice.profitmandi.common.util.FormattingUtils;
22859 ashik.ali 11
import com.spice.profitmandi.common.util.StringUtils;
30121 amit.gupta 12
import com.spice.profitmandi.common.util.Utils;
31969 amit.gupta 13
import com.spice.profitmandi.dao.entity.catalog.Item;
14
import com.spice.profitmandi.dao.entity.catalog.Scheme;
15
import com.spice.profitmandi.dao.entity.catalog.SchemeRegion;
16
import com.spice.profitmandi.dao.entity.catalog.SchemesImeisModel;
29927 amit.gupta 17
import com.spice.profitmandi.dao.entity.fofo.*;
31903 amit.gupta 18
import com.spice.profitmandi.dao.entity.inventory.PartnerAgeingModel;
26498 amit.gupta 19
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
32060 amit.gupta 20
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
31609 amit.gupta 21
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
23527 ashik.ali 22
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
22653 ashik.ali 23
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
25111 amit.gupta 24
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
27377 amit.gupta 25
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
31903 amit.gupta 26
import com.spice.profitmandi.dao.model.AmountModel;
25503 amit.gupta 27
import com.spice.profitmandi.dao.model.CreateSchemeRequest;
31170 amit.gupta 28
import com.spice.profitmandi.dao.repository.catalog.*;
32309 amit.gupta 29
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
23968 amit.gupta 30
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
29927 amit.gupta 31
import com.spice.profitmandi.dao.repository.fofo.*;
26498 amit.gupta 32
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
31609 amit.gupta 33
import com.spice.profitmandi.dao.repository.transaction.UserWalletHistoryRepository;
32060 amit.gupta 34
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
33087 amit.gupta 35
import com.spice.profitmandi.dao.repository.warehouse.AgeingSummaryModel;
36
import com.spice.profitmandi.dao.repository.warehouse.WarehouseInventoryItemRepository;
29927 amit.gupta 37
import com.spice.profitmandi.service.NotificationService;
23798 amit.gupta 38
import com.spice.profitmandi.service.authentication.RoleManager;
31903 amit.gupta 39
import com.spice.profitmandi.service.inventory.AgeingService;
26722 amit.gupta 40
import com.spice.profitmandi.service.inventory.PurchaseService;
31903 amit.gupta 41
import com.spice.profitmandi.service.pricecircular.CatalogSummaryModel;
31921 amit.gupta 42
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
31903 amit.gupta 43
import com.spice.profitmandi.service.pricecircular.SchemeSummaryModel;
22859 ashik.ali 44
import com.spice.profitmandi.service.wallet.WalletService;
45
import in.shop2020.model.v1.order.WalletReferenceType;
29927 amit.gupta 46
import org.apache.logging.log4j.LogManager;
47
import org.apache.logging.log4j.Logger;
48
import org.hibernate.Session;
49
import org.hibernate.SessionFactory;
50
import org.hibernate.query.Query;
51
import org.springframework.beans.factory.annotation.Autowired;
52
import org.springframework.beans.factory.annotation.Qualifier;
53
import org.springframework.cache.annotation.Cacheable;
54
import org.springframework.stereotype.Component;
22859 ashik.ali 55
 
31170 amit.gupta 56
import javax.persistence.TypedQuery;
29927 amit.gupta 57
import javax.persistence.criteria.CriteriaBuilder;
58
import javax.persistence.criteria.CriteriaQuery;
59
import javax.persistence.criteria.Predicate;
60
import javax.persistence.criteria.Root;
61
import java.text.MessageFormat;
33704 amit.gupta 62
import java.time.*;
29927 amit.gupta 63
import java.util.*;
64
import java.util.stream.Collectors;
65
 
22653 ashik.ali 66
@Component
67
public class SchemeServiceImpl implements SchemeService {
68
 
31410 amit.gupta 69
    private static final Logger LOGGER = LogManager.getLogger(SchemeServiceImpl.class);
31916 amit.gupta 70
    private static final Set<Integer> tagIds = new HashSet<>(Arrays.asList(4));
33176 amit.gupta 71
    private static final List<String> BLOCKED_IMEIS = Arrays.asList("864883056397593", "864883054606656", "864883056567815", "861950056518271", "869175055649511", "861362058924574", "866009066803036", "866009066816699", "866009066816137", "866009066815873", "866009066805536", "866009066803010", "866009066821939", "866009066802756", "866009066820592", "866009066820311", "866009066816491", "866009066816376", "866009066815899", "866009066815774", "866009066817937", "866009066819859", "866009066817655", "866009066820691", "866009066820832", "866009066803291", "866009066820733", "866009066814496", "866009066820451", "866009066820659", "866009066804976", "866009066820717", "866009066816095", "861362054898434", "869599051117852", "869599056695332", "869599056695894", "864883057389656", "862661052418692", "860118051929254", "862888051664998", "862680054625831", "862888051666316", "860118051738895", "868066050447970", "868066052424399", "865084051552576", "865084050755097", "865084050755295", "865084050754819", "864883057487278", "864883057389599", "864883057437455", "864883057388278", "862680058278058", "869599056810139", "862200053994193", "861932057188916", "861175050581774", "863933065909093", "863933065635391", "861362054889177", "864004062055154", "864004062069239", "862661050221676", "862661052416993", "866812058631475", "869599051118173", "869599051504273", "868066052729250", "864883057701397", "864883054123033", "864883054947316", "864883056235694", "868066052727692", "866030052139896", "866030052140175", "860588051522053", "860588051513193", "861932056969779", "869599056171995", "865594061074932", "863935059410491", "866088059072718", "869599055375894", "869599054306916", "863782054006472", "863782054012371", "860588053486992", "868066052726835", "868066052726694", "860688053876430", "860688053869674", "868494054682394", "869599053512357");
31450 amit.gupta 72
    private static final List<SchemeType> ACTIVATION_SCHEME_TYPES = Arrays.asList(SchemeType.ACTIVATION, SchemeType.SPECIAL_SUPPORT, SchemeType.SELLOUT);
33600 ranu 73
 
31410 amit.gupta 74
    @Autowired
75
    StateGstRateRepository stateGstRateRepository;
76
    @Autowired
77
    NotificationService notificationService;
78
    @Autowired
79
    @Qualifier("fofoInventoryItemRepository")
80
    private InventoryItemRepository inventoryItemRepository;
81
    @Autowired
82
    private ActivatedImeiRepository activatedImeiRepository;
83
    @Autowired
84
    private PartnerTypeChangeService partnerTypeChangeService;
85
    @Autowired
86
    private PurchaseService purchaseService;
87
    @Autowired
88
    private ScanRecordRepository scanRecordRepository;
89
    @Autowired
90
    private SessionFactory sessionFactory;
91
    @Autowired
92
    private SchemeRepository schemeRepository;
93
    @Autowired
94
    private PriceDropRepository priceDropRepository;
95
    @Autowired
96
    private RoleManager roleManager;
97
    @Autowired
98
    private RetailerRepository retailerRepository;
99
    @Autowired
100
    private ReporticoService reporticoService;
101
    @Autowired
102
    private TagListingRepository tagListingRepository;
103
    @Autowired
104
    private SchemeInOutRepository schemeInOutRepository;
105
    @Autowired
106
    @Qualifier("catalogItemRepository")
107
    private ItemRepository itemRepository;
108
    @Autowired
109
    private SchemeItemRepository schemeItemRepository;
110
    @Autowired
111
    private SchemeRegionRepository schemeRegionRepository;
112
    @Autowired
113
    private WalletService walletService;
114
    @Autowired
115
    private PurchaseRepository purchaseRepository;
116
    @Autowired
117
    private FofoOrderRepository fofoOrderRepository;
23444 amit.gupta 118
 
31921 amit.gupta 119
    @Autowired
120
    private PriceCircularService priceCircularService;
121
 
33600 ranu 122
    @Autowired
123
    private SamsungExceptionRepository samsungExceptionRepository;
124
 
31410 amit.gupta 125
    @Override
126
    public void saveScheme(int creatorId, CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
23444 amit.gupta 127
 
31410 amit.gupta 128
        this.validateCreateSchemeRequest(createSchemeRequest);
27898 amit.gupta 129
 
31410 amit.gupta 130
        Scheme scheme = this.toScheme(creatorId, createSchemeRequest);
25503 amit.gupta 131
 
31410 amit.gupta 132
        if (scheme.getStartDateTime().isAfter(scheme.getEndDateTime())) {
133
            throw new ProfitMandiBusinessException(
134
                    ProfitMandiConstants.START_DATE + ", " + ProfitMandiConstants.END_DATE,
135
                    scheme.getStartDateTime() + ", " + scheme.getEndDateTime(), "SCHM_VE_1005");
136
        }
26722 amit.gupta 137
 
31410 amit.gupta 138
        // this.validateItemIds(createSchemeRequest);
139
        schemeRepository.persist(scheme);
140
        for (int catalogId : createSchemeRequest.getCatalogIds()) {
141
            SchemeItem schemeItem = new SchemeItem();
142
            schemeItem.setSchemeId(scheme.getId());
143
            schemeItem.setCatalogId(catalogId);
144
            schemeItemRepository.persist(schemeItem);
145
        }
23444 amit.gupta 146
 
31410 amit.gupta 147
        for (int regionId : createSchemeRequest.getRegionIds()) {
148
            SchemeRegion schemeRegion = new SchemeRegion();
149
            schemeRegion.setSchemeId(scheme.getId());
150
            schemeRegion.setRegionId(regionId);
151
            schemeRegionRepository.persist(schemeRegion);
152
        }
26332 amit.gupta 153
 
31410 amit.gupta 154
    }
26722 amit.gupta 155
 
31410 amit.gupta 156
    private void validateCreateSchemeRequest(CreateSchemeRequest createSchemeRequest)
157
            throws ProfitMandiBusinessException {
158
        if (createSchemeRequest.getName() == null || createSchemeRequest.getName().isEmpty()) {
159
            throw new ProfitMandiBusinessException(ProfitMandiConstants.NAME, createSchemeRequest.getName(),
160
                    "SCHM_VE_1000");
161
        }
162
        if (createSchemeRequest.getAmount() <= 0) {
163
            throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
164
                    "SCHM_VE_1001");
165
        }
26684 amit.gupta 166
 
31410 amit.gupta 167
        if (createSchemeRequest.getAmountType().equals(AmountType.PERCENTAGE)
168
                && createSchemeRequest.getAmount() > 100) {
169
            throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
170
                    "SCHM_VE_1002");
171
        }
23444 amit.gupta 172
 
31410 amit.gupta 173
        if (createSchemeRequest.getStartDate() == null) {
174
            throw new ProfitMandiBusinessException(ProfitMandiConstants.START_DATE, createSchemeRequest.getStartDate(),
175
                    "SCHM_VE_1003");
176
        }
177
        if (createSchemeRequest.getEndDate() == null) {
178
            throw new ProfitMandiBusinessException(ProfitMandiConstants.END_DATE, createSchemeRequest.getEndDate(),
179
                    "SCHM_VE_1004");
180
        }
181
    }
23798 amit.gupta 182
 
31410 amit.gupta 183
    private void validateItemIds(CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
184
        if (createSchemeRequest.getCatalogIds() == null || createSchemeRequest.getCatalogIds().isEmpty()) {
185
            throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getCatalogIds(),
186
                    "SCHM_1003");
187
        }
188
        List<Integer> foundItemIds = itemRepository.selectIdsByIdsAndType(createSchemeRequest.getCatalogIds(),
189
                ItemType.SERIALIZED);
190
        if (foundItemIds.size() != createSchemeRequest.getCatalogIds().size()) {
191
            createSchemeRequest.getCatalogIds().removeAll(foundItemIds);
192
            throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getCatalogIds(),
193
                    "SCHM_1004");
194
        }
195
    }
29927 amit.gupta 196
 
31410 amit.gupta 197
    @Override
198
    public Scheme getSchemeById(int schemeId) throws ProfitMandiBusinessException {
199
        Scheme scheme = schemeRepository.selectById(schemeId);
200
        List<Integer> catalogIds = schemeItemRepository.selectCatalogIdsBySchemeId(scheme.getId());
201
        if (catalogIds.size() > 0) {
202
            List<Item> items = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds));
203
            scheme.setCatalogStringMap(this.toCatalogStringMap(items));
204
        }
205
        return scheme;
206
    }
24562 amit.gupta 207
 
31410 amit.gupta 208
    public Map<Integer, String> toCatalogStringMap(List<Item> items) {
209
        Map<Integer, String> catalogMap = new HashMap<>();
210
        for (Item item : items) {
211
            if (!catalogMap.containsKey(item.getCatalogItemId())) {
212
                catalogMap.put(item.getCatalogItemId(), item.getItemDescriptionNoColor());
213
            }
214
        }
215
        return catalogMap;
216
    }
29927 amit.gupta 217
 
31410 amit.gupta 218
    private Set<Integer> schemeItemsToCatalogIds(List<SchemeItem> schemeItems) {
219
        Set<Integer> catalogId = new HashSet<>();
220
        for (SchemeItem schemeItem : schemeItems) {
221
            catalogId.add(schemeItem.getCatalogId());
222
        }
223
        return catalogId;
224
    }
23444 amit.gupta 225
 
31410 amit.gupta 226
    @Override
33248 ranu 227
    public List<SchemeModel> getAllSchemeModels(LocalDateTime startDateTime, LocalDateTime endDateTime) throws ProfitMandiBusinessException {
31410 amit.gupta 228
        List<Scheme> schemes = schemeRepository.selectAllBetweenCreateTimestamp(startDateTime, endDateTime);
229
        Map<Integer, Scheme> schemeIdSchemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
230
        List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(schemeIdSchemeMap.keySet());
231
        Set<Integer> catalogIds = schemeItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
232
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
233
        Map<Integer, String> catalogStringMap = this.toCatalogStringMap(items);
234
        this.addCatalogIdsToSchemes(schemeItems, schemeIdSchemeMap, catalogStringMap);
235
        return this.toSchemeModels(schemeIdSchemeMap);
236
    }
23444 amit.gupta 237
 
31410 amit.gupta 238
    private List<SchemeModel> toSchemeModels(Map<Integer, Scheme> schemeIdSchemeMap) {
239
        List<SchemeModel> schemeModels = new ArrayList<>();
240
        for (Map.Entry<Integer, Scheme> schemeIdSchemeEntry : schemeIdSchemeMap.entrySet()) {
241
            schemeModels.add(this.toSchemeModel(schemeIdSchemeEntry.getValue()));
242
        }
243
        return schemeModels;
244
    }
23444 amit.gupta 245
 
31410 amit.gupta 246
    private SchemeModel toSchemeModel(Scheme scheme) {
247
        SchemeModel schemeModel = new SchemeModel();
248
        schemeModel.setSchemeId(scheme.getId());
249
        schemeModel.setName(scheme.getName());
250
        schemeModel.setDescription(scheme.getDescription());
251
        schemeModel.setSchemeType(scheme.getType().toString());
252
        schemeModel.setAmountType(scheme.getAmountType().toString());
253
        schemeModel.setAmount(scheme.getAmount());
254
        schemeModel.setStartDateTime(StringUtils.toString(scheme.getStartDateTime()));
255
        schemeModel.setEndDateTime(StringUtils.toString(scheme.getEndDateTime()));
256
        schemeModel.setCreateTimestamp(StringUtils.toString(scheme.getCreateTimestamp()));
257
        schemeModel.setActiveTimestamp(StringUtils.toString(scheme.getActiveTimestamp()));
258
        schemeModel.setExpireTimestamp(StringUtils.toString(scheme.getExpireTimestamp()));
259
        schemeModel.setCreatedBy(scheme.getCreatedBy());
260
        schemeModel.setCatalogStringMap(scheme.getCatalogStringMap());
261
        schemeModel.setRetailerIds(scheme.getRetailerIds());
262
        return schemeModel;
263
    }
23444 amit.gupta 264
 
31410 amit.gupta 265
    private void addCatalogIdsToSchemes(List<SchemeItem> schemeItems, Map<Integer, Scheme> schemeIdSchemeMap,
266
                                        Map<Integer, String> catalogStringMap) {
267
        for (SchemeItem schemeItem : schemeItems) {
268
            Scheme scheme = schemeIdSchemeMap.get(schemeItem.getSchemeId());
269
            scheme.getCatalogStringMap().put(schemeItem.getCatalogId(), catalogStringMap.get(schemeItem.getCatalogId()));
270
        }
271
    }
31170 amit.gupta 272
 
31410 amit.gupta 273
    @Override
274
    public void activeSchemeById(int schemeId) throws ProfitMandiBusinessException {
275
        Scheme scheme = schemeRepository.selectById(schemeId);
276
        if (scheme.getActiveTimestamp() != null) {
277
            throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
278
                    "SCHM_1005");
279
        }
280
        if (scheme.getExpireTimestamp() != null) {
281
            throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
282
                    "SCHM_1006");
283
        }
284
        scheme.setActiveTimestamp(LocalDateTime.now());
285
        this.sendSchemeNotification(scheme);
23444 amit.gupta 286
 
287
 
31410 amit.gupta 288
        /*
289
         * if (scheme.getType() == SchemeType.IN) {
290
         * this.processPreviousPurchases(scheme); } else if (scheme.getType() ==
291
         * SchemeType.OUT) { this.processPreviousSales(scheme); }
292
         */
293
    }
23796 amit.gupta 294
 
31410 amit.gupta 295
    private void sendSchemeNotification(Scheme scheme) throws ProfitMandiBusinessException {
296
        if (ACTIVATION_SCHEME_TYPES.contains(scheme.getType())) {
31336 amit.gupta 297
 
31410 amit.gupta 298
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
299
            List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(Collections.singleton(scheme.getId()));
300
            Set<Integer> catalogIds = schemeItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
301
            List<String> itemDescriptions = itemRepository.selectAllByCatalogIds(catalogIds).stream().filter(Utils.distinctByKey(Item::getCatalogItemId))
302
                    .map(x -> x.getItemDescriptionNoColor()).collect(Collectors.toList());
303
            String titleTemplate = "%s of Rs.%s for %s";
304
            String schemeString = "Activation scheme";
305
            if (scheme.getType().equals(SchemeType.SPECIAL_SUPPORT)) {
306
                schemeString = "Special Support";
307
            }
30957 amit.gupta 308
 
31410 amit.gupta 309
            String message = "Duration from - " + FormattingUtils.formatDateMonth(scheme.getStartDateTime()) + " - " + FormattingUtils.formatDateMonth(scheme.getEndDateTime());
310
            sendNotificationModel.setCampaignName("activationscheme");
32602 amit.gupta 311
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
31410 amit.gupta 312
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
313
            sendNotificationModel.setMessage(message);
314
            sendNotificationModel.setTitle(String.format(titleTemplate, schemeString, FormattingUtils.formatDecimal(scheme.getAmount()), org.apache.commons.lang3.StringUtils.abbreviate(String.join(", ", itemDescriptions), 25)));
315
            sendNotificationModel.setType("url");
316
            sendNotificationModel.setMessageType(MessageType.scheme);
317
            notificationService.sendNotificationToAll(sendNotificationModel);
318
        }
319
    }
23444 amit.gupta 320
 
31410 amit.gupta 321
    @Override
322
    public void expireSchemeById(int schemeId, LocalDateTime expiryTime) throws ProfitMandiBusinessException {
323
        Scheme scheme = schemeRepository.selectById(schemeId);
324
        if (scheme == null || scheme.getActiveTimestamp() == null) {
325
            throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
326
                    "SCHM_1007");
327
        }
328
        if (scheme.getExpireTimestamp() != null) {
329
            throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
330
                    "SCHM_1008");
331
        }
332
        scheme.setExpireTimestamp(LocalDateTime.now());
333
        if (expiryTime.isAfter(scheme.getEndDateTime())) {
334
            throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
335
                    "End Date cant be extended during expiry");
336
        }
337
        scheme.setEndDateTime(expiryTime);
338
        schemeRepository.persist(scheme);
339
    }
23444 amit.gupta 340
 
31410 amit.gupta 341
    private Map<Integer, Scheme> toSchemeIdSchemeMap(List<Scheme> schemes) {
342
        Map<Integer, Scheme> schemeIdSchemeMap = new HashMap<>();
343
        for (Scheme scheme : schemes) {
344
            schemeIdSchemeMap.put(scheme.getId(), scheme);
345
        }
346
        return schemeIdSchemeMap;
347
    }
23444 amit.gupta 348
 
31410 amit.gupta 349
    private Map<Integer, Set<Scheme>> toCatalogIdSchemesMap(List<SchemeItem> schemeItems, List<Scheme> schemes) {
350
        Map<Integer, Scheme> schemesMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
351
        Map<Integer, Set<Scheme>> catalogSchemesMap = new HashMap<>();
352
        for (SchemeItem schemeItem : schemeItems) {
353
            if (!catalogSchemesMap.containsKey(schemeItem.getCatalogId())) {
354
                catalogSchemesMap.put(schemeItem.getCatalogId(), new HashSet<>());
355
            }
356
            Set<Scheme> schemesSet = catalogSchemesMap.get(schemeItem.getCatalogId());
357
            schemesSet.add(schemesMap.get(schemeItem.getSchemeId()));
358
        }
359
        return catalogSchemesMap;
360
    }
23444 amit.gupta 361
 
31410 amit.gupta 362
    private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
33248 ranu 363
                                                                      List<InventoryItem> inventoryItems) throws ProfitMandiBusinessException {
31410 amit.gupta 364
        Set<Integer> schemeIds = schemes.stream().map(x -> x.getId()).collect(Collectors.toSet());
365
        Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
366
        Set<Integer> catalogIds = itemRepository.selectByIds(itemIds).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
367
        List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndCatalogIds(schemeIds, catalogIds);
23444 amit.gupta 368
 
31410 amit.gupta 369
        Map<Integer, Set<Scheme>> catalogIdSchemesMap = this.toCatalogIdSchemesMap(schemeItems, schemes);
370
        Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = new HashMap<>();
371
        for (InventoryItem inventoryItem : inventoryItems) {
372
            LOGGER.info("inventoryItem {}", inventoryItem);
373
            LOGGER.info("inventoryItem.getItem() {}", inventoryItem.getItem());
374
            LOGGER.info("catalogIdSchemesMap {}", catalogIdSchemesMap);
375
            if (catalogIdSchemesMap.containsKey(inventoryItem.getItem().getCatalogItemId())) {
376
                inventoryItemSchemesMap.put(inventoryItem, catalogIdSchemesMap.get(inventoryItem.getItem().getCatalogItemId()));
377
            }
378
        }
379
        return inventoryItemSchemesMap;
380
    }
31170 amit.gupta 381
 
31903 amit.gupta 382
    @Autowired
383
    OfferTargetSlabRepository offerTargetSlabRepository;
384
 
31410 amit.gupta 385
    private Scheme toScheme(int creatorId, CreateSchemeRequest createSchemeRequest) {
386
        Scheme scheme = new Scheme();
387
        scheme.setName(createSchemeRequest.getName());
388
        scheme.setDescription(createSchemeRequest.getDescription());
389
        scheme.setType(createSchemeRequest.getType());
390
        scheme.setAmountType(createSchemeRequest.getAmountType());
391
        scheme.setAmount(createSchemeRequest.getAmount());
392
        scheme.setPartnerType(createSchemeRequest.getPartnerType());
393
        scheme.setStartDateTime(createSchemeRequest.getStartDate());
394
        scheme.setEndDateTime(createSchemeRequest.getEndDate());
395
        scheme.setCreatedBy(creatorId);
396
        scheme.setCashback(createSchemeRequest.isCashback());
397
        return scheme;
398
    }
23444 amit.gupta 399
 
31903 amit.gupta 400
    @Autowired
401
    OfferRepository offerRepository;
402
    @Autowired
403
    OfferPayoutRepository offerPayoutRepository;
404
    @Autowired
405
    AgeingService ageingService;
31588 amit.gupta 406
 
31903 amit.gupta 407
    public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
33432 amit.gupta 408
        LOGGER.info("Processing scheme in  for purchaseId - {}", purchaseId);
31903 amit.gupta 409
        Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
410
        PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
411
                YearMonth.from(purchase.getCreateTimestamp()));
412
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
413
        //Remove imeis from blocked imeis list
414
        inventoryItems = inventoryItems.stream().filter(inventoryItem -> !BLOCKED_IMEIS.contains(inventoryItem.getSerialNumber())).collect(Collectors.toList());
415
        if (inventoryItems.size() == 0) return;
23444 amit.gupta 416
 
31903 amit.gupta 417
        Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
418
        Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
419
        inventoryItems.stream().forEach(x -> x.setItem(itemsMap.get(x.getItemId())));
23444 amit.gupta 420
 
421
 
31903 amit.gupta 422
        LocalDateTime billingDate = purchaseService.getBillingDateOfPurchase(purchaseId);
423
        Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
424
                .filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(billingDate)).map(x -> x.getItemId())
425
                .collect(Collectors.toSet());
426
        // Only consider inventory items that were not returned and not eol
427
        inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
428
                .filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD))
429
                .filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
430
 
431
        if (inventoryItems.size() == 0) return;
432
 
433
        Map<Integer, List<InventoryItem>> catalogInventoryItemMap = inventoryItems.stream().collect(Collectors.groupingBy(x -> x.getItem().getCatalogItemId()));
434
        Map<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSchemeSummaryMap = tagListingRepository.getModelSchemesByCatalogIdsAndType(retailerId,
32454 amit.gupta 435
                partnerType, new ArrayList<>(catalogInventoryItemMap.keySet()), billingDate);
31903 amit.gupta 436
 
437
 
438
        int itemsCount = 0;
439
        float totalCashback = 0;
440
        for (Map.Entry<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSummaryModelListEntry : catalogSchemeSummaryMap.entrySet()) {
441
            CatalogSummaryModel catalogSummaryModel = catalogSummaryModelListEntry.getKey();
32058 amit.gupta 442
            List<SchemeSummaryModel> schemeSummaryModels = catalogSummaryModelListEntry.getValue().stream().filter(x -> x != null).collect(Collectors.toList());
443
            schemeSummaryModels.stream().filter(x -> x != null && x.getSchemeType().equals(SchemeType.IN)).forEach(x -> x.setProcess(true));
31903 amit.gupta 444
            if (schemeSummaryModels.stream().filter(x -> x.isProcess()).count() == 0) continue;
445
            List<InventoryItem> modelInventoryItems = catalogInventoryItemMap.get(catalogSummaryModel.getCatalogId());
446
            for (InventoryItem inventoryItem : modelInventoryItems) {
32165 amit.gupta 447
                float inventoryItemCashback = this.createSchemeInOut(schemeSummaryModels, inventoryItem);
31903 amit.gupta 448
                if (inventoryItemCashback > 0) {
449
                    itemsCount++;
450
                    totalCashback += inventoryItemCashback;
31410 amit.gupta 451
                }
452
            }
31903 amit.gupta 453
        }
22653 ashik.ali 454
 
29927 amit.gupta 455
 
31903 amit.gupta 456
        LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
457
        if (itemsCount > 0) {
458
            walletService.addAmountToWallet(
459
                    retailerId, purchaseId, WalletReferenceType.SCHEME_IN, "Added for SCHEME IN against invoice "
460
                            + purchase.getPurchaseReference() + " (total " + itemsCount + " pcs)",
461
                    totalCashback, purchase.getCreateTimestamp());
462
            LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
463
                    purchase.getPurchaseReference(), itemsCount);
464
        }
465
 
466
    }
467
 
468
 
31410 amit.gupta 469
    // We are maintaining price drop after grn
470
    private float getAmount(InventoryItem inventoryItem, Scheme scheme) throws ProfitMandiBusinessException {
471
        if (BLOCKED_IMEIS.contains(inventoryItem.getSerialNumber())) {
472
            return 0;
473
        }
474
        float amount = 0;
475
        float dpForCalc = 0;
476
        float taxableSellingPrice = 0;
29927 amit.gupta 477
 
31410 amit.gupta 478
        //float totalTaxRate = stateGstRateRepository.getTotalTaxRate(inventoryItem.getItemId());
479
        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
480
            if (scheme.getType().equals(SchemeType.IN)) {
481
                dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
482
            } else {
483
                try {
484
                    dpForCalc = Math.min(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount(),
485
                            tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice());
486
                } catch (Exception e) {
487
                    LOGGER.info("Could not find tag Listing entry in {}", inventoryItem.getItemId());
488
                    e.printStackTrace();
489
                }
490
            }
491
            //TODO:Should be calculated on unit price
492
            //taxableSellingPrice = dpForCalc / (1 + totalTaxRate / 100);
493
            //amount = taxableSellingPrice * scheme.getAmount() / 100;
494
            amount = dpForCalc * scheme.getAmount() / 100;
495
            System.out.println(String.format("%d\t%s\t%d\t%d\t%s\t%s\t%s\t%s\t%f\t%f\t%f\t%f", inventoryItem.getId(),
496
                    inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
497
                    scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
498
                    scheme.getAmount(), amount));
499
        } else if (scheme.getType().equals(SchemeType.IN)) {
500
            amount = scheme.getAmount();
501
        }
502
        return amount;
503
    }
23444 amit.gupta 504
 
31903 amit.gupta 505
    //Only in and activation margins are allowed to be rolled out more than twice
32165 amit.gupta 506
    private float createSchemeInOut(List<SchemeSummaryModel> schemeSummaryModels, InventoryItem inventoryItem) throws ProfitMandiBusinessException {
33614 amit.gupta 507
        LOGGER.info("schemeSummaryModels - {}", schemeSummaryModels);
31921 amit.gupta 508
        InventoryPayoutModel inventoryPayoutModel = priceCircularService.getPayouts(inventoryItem);
31903 amit.gupta 509
        //Get all schemes
510
        List<SchemeSummaryModel> inventoryPayoutModelToProcess = schemeSummaryModels.stream().filter(x -> x.isProcess()).collect(Collectors.toList());
511
 
32165 amit.gupta 512
        List<SchemeInOut> paidSios = inventoryPayoutModel.getPaidSios();
513
        List<SchemeInOut> pendingSios = inventoryPayoutModel.getPendingSios();
514
        Map<SchemeType, List<SchemeInOut>> paidSchemeTypesMap = inventoryPayoutModel.getPaidSios().stream().collect(Collectors.groupingBy(x -> x.getScheme().getType()));
515
        Map<Integer, SchemeInOut> paidSchemesMap = paidSios.stream().collect(Collectors.toMap(x -> x.getSchemeId(), x -> x));
516
        Map<Integer, SchemeInOut> pendingSchemesMap = pendingSios.stream().collect(Collectors.toMap(x -> x.getSchemeId(), x -> x));
32155 amit.gupta 517
        Map<SchemeType, Float> schemeTypeCancelledAmountMap = new HashMap<>();
31903 amit.gupta 518
 
519
        double percentageToPay = 0d;
520
        double fixedToPay = 0d;
521
        Map<SchemeSummaryModel, AmountModel> payoutSchemeSummaryModelMap = new HashMap<>();
522
        for (SchemeSummaryModel schemeSummaryModelToProcess : inventoryPayoutModelToProcess) {
32972 amit.gupta 523
            if (paidSchemesMap.containsKey(schemeSummaryModelToProcess.getSchemeId()) || pendingSchemesMap.containsKey(schemeSummaryModelToProcess.getSchemeId()))
524
                continue;
31903 amit.gupta 525
            //If different type but on higher side provide the higher margin
526
            if (Arrays.asList(SchemeType.ACTIVATION, SchemeType.SPECIAL_SUPPORT).contains(schemeSummaryModelToProcess.getSchemeType())) {
32165 amit.gupta 527
                Scheme scheme = schemeRepository.selectById(schemeSummaryModelToProcess.getSchemeId());
528
                //Create only if the activation if the activation date is not known
529
                ActivatedImei activatedImei = activatedImeiRepository.selectBySerialNumber(inventoryItem.getSerialNumber());
32972 amit.gupta 530
                if (activatedImei == null || activatedImei.getActivationTimestamp() == null) {
32165 amit.gupta 531
                    SchemeInOut sio = new SchemeInOut();
532
                    sio.setAmount(0);
533
                    sio.setInventoryItemId(inventoryItem.getId());
534
                    sio.setSchemeId(schemeSummaryModelToProcess.getSchemeId());
535
                    sio.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
536
                    sio.setStatus(SchemePayoutStatus.PENDING);
537
                    schemeInOutRepository.persist(sio);
538
                }
31903 amit.gupta 539
            } else if (!SchemeType.IN.equals(schemeSummaryModelToProcess.getSchemeType())) {
540
                //We have got non repeating scheme type
541
                if (paidSchemeTypesMap.containsKey(schemeSummaryModelToProcess.getSchemeType())) {
542
                    SchemeInOut sio = paidSchemeTypesMap.get(schemeSummaryModelToProcess.getSchemeType()).get(0);
543
                    Scheme paidScheme = sio.getScheme();
544
                    //Don't entertain if amount types do not match for same type
545
                    if (paidScheme.getAmountType().equals(schemeSummaryModelToProcess.getAmountType()) &&
546
                            schemeSummaryModelToProcess.getAmount() > paidScheme.getAmount() + Utils.DOUBLE_EPSILON) {
547
                        sio.setRolledBackTimestamp(LocalDateTime.now());
548
                        sio.setStatus(SchemePayoutStatus.REJECTED);
32155 amit.gupta 549
                        sio.setStatusDescription("Eligible for higher margin for " + schemeSummaryModelToProcess.getSchemeType() + ", new entry added");
550
                        schemeTypeCancelledAmountMap.put(schemeSummaryModelToProcess.getSchemeType(), sio.getAmount());
31903 amit.gupta 551
                        if (paidScheme.getAmountType().equals(AmountType.PERCENTAGE)) {
552
                            percentageToPay += schemeSummaryModelToProcess.getAmount() - paidScheme.getAmount();
553
                        } else {
554
                            fixedToPay += schemeSummaryModelToProcess.getAmount() - paidScheme.getAmount();
555
                        }
556
                        payoutSchemeSummaryModelMap.put(schemeSummaryModelToProcess, new AmountModel(schemeSummaryModelToProcess.getAmount() - paidScheme.getAmount(), schemeSummaryModelToProcess.getAmountType()));
557
                    }
558
                } else {
559
                    if (schemeSummaryModelToProcess.getAmountType().equals(AmountType.PERCENTAGE)) {
560
                        percentageToPay += schemeSummaryModelToProcess.getAmount();
561
                    } else {
562
                        fixedToPay += schemeSummaryModelToProcess.getAmount();
563
                    }
564
                    payoutSchemeSummaryModelMap.put(schemeSummaryModelToProcess, new AmountModel(schemeSummaryModelToProcess.getAmount(), schemeSummaryModelToProcess.getAmountType()));
565
                }
566
            } else {
567
                if (schemeSummaryModelToProcess.getAmountType().equals(AmountType.PERCENTAGE)) {
568
                    percentageToPay += schemeSummaryModelToProcess.getAmount();
569
                } else {
570
                    fixedToPay += schemeSummaryModelToProcess.getAmount();
571
                }
572
                payoutSchemeSummaryModelMap.put(schemeSummaryModelToProcess, new AmountModel(schemeSummaryModelToProcess.getAmount(), schemeSummaryModelToProcess.getAmountType()));
573
            }
574
        }
575
        double walletCredit = 0d;
576
        if (fixedToPay > 0) {
31913 amit.gupta 577
            double fixedRollout = fixedToPay * (100 / (100 + inventoryPayoutModel.getPercentageAmount()));
31903 amit.gupta 578
            for (Map.Entry<SchemeSummaryModel, AmountModel> schemeSummaryModelAmountModelEntry : payoutSchemeSummaryModelMap.entrySet()) {
579
                SchemeSummaryModel schemeSummaryModel = schemeSummaryModelAmountModelEntry.getKey();
580
                AmountModel amountModel = schemeSummaryModelAmountModelEntry.getValue();
581
                if (amountModel.getAmountType().equals(AmountType.FIXED)) {
582
                    SchemeInOut sio = new SchemeInOut();
583
                    sio.setSchemeId(schemeSummaryModel.getSchemeId());
584
                    sio.setInventoryItemId(inventoryItem.getId());
585
                    sio.setStatus(SchemePayoutStatus.CREDITED);
586
                    sio.setCreditTimestamp(LocalDateTime.now());
32155 amit.gupta 587
                    sio.setAmount((float) (fixedRollout * amountModel.getAmount() / fixedToPay) + schemeTypeCancelledAmountMap.getOrDefault(schemeSummaryModel.getSchemeType(), 0f));
31903 amit.gupta 588
                    if (schemeSummaryModel.getSchemeType().equals(SchemeType.IN))
589
                        sio.setStatusDescription("Credited for GRN of IMEI-" + inventoryItem.getSerialNumber());
590
                    else
591
                        sio.setStatusDescription("Credited for Sale of IMEI-" + inventoryItem.getSerialNumber());
592
                    schemeInOutRepository.persist(sio);
593
                }
594
            }
595
            walletCredit += fixedRollout;
596
        }
597
 
598
        if (percentageToPay > 0) {
31987 amit.gupta 599
            LOGGER.info("inventoryPayoutModel.getFixedAmount() ----> {}", inventoryPayoutModel.getFixedAmount());
31914 amit.gupta 600
            double effectiveDP = inventoryPayoutModel.getDp() - (inventoryPayoutModel.getFixedAmount() + fixedToPay);
31903 amit.gupta 601
            double totalPercentage = inventoryPayoutModel.getPercentageAmount() + percentageToPay;
602
            double percentageRollout = effectiveDP * (totalPercentage / (100 + totalPercentage) - (inventoryPayoutModel.getPercentageAmount() / (100 + inventoryPayoutModel.getPercentageAmount())));
603
            for (Map.Entry<SchemeSummaryModel, AmountModel> schemeSummaryModelAmountModelEntry : payoutSchemeSummaryModelMap.entrySet()) {
604
                SchemeSummaryModel schemeSummaryModel = schemeSummaryModelAmountModelEntry.getKey();
605
                AmountModel amountModel = schemeSummaryModelAmountModelEntry.getValue();
606
                if (amountModel.getAmountType().equals(AmountType.PERCENTAGE)) {
607
                    SchemeInOut sio = new SchemeInOut();
608
                    sio.setInventoryItemId(inventoryItem.getId());
609
                    sio.setSchemeId(schemeSummaryModel.getSchemeId());
610
                    sio.setStatus(SchemePayoutStatus.CREDITED);
611
                    sio.setCreditTimestamp(LocalDateTime.now());
32155 amit.gupta 612
                    sio.setAmount((float) (percentageRollout * amountModel.getAmount() / percentageToPay) +
613
                            schemeTypeCancelledAmountMap.getOrDefault(schemeSummaryModel.getSchemeType(), 0f));
31903 amit.gupta 614
                    if (schemeSummaryModel.getSchemeType().equals(SchemeType.IN))
615
                        sio.setStatusDescription("Credited for GRN of IMEI-" + inventoryItem.getSerialNumber());
616
                    else
617
                        sio.setStatusDescription("Credited for Sale of IMEI-" + inventoryItem.getSerialNumber());
618
                    schemeInOutRepository.persist(sio);
619
                }
620
            }
621
            walletCredit += percentageRollout;
622
        }
623
 
624
        return (float) walletCredit;
625
    }
626
 
627
    private Set<Integer> filterImeisByAgeing(Set<Integer> inventoryItemIds, FofoOrder fofoOrder) {
628
        Set<Integer> filteredInventoryIds = new HashSet<>();
629
        List<PartnerAgeingModel> partnerAgeingModels = ageingService.filterAgedInventory(inventoryItemIds);
630
        for (PartnerAgeingModel partnerAgeingModel : partnerAgeingModels) {
631
            LOGGER.info("Serial Number - {}", partnerAgeingModel.getSerialNumber());
632
            if (partnerAgeingModel.getBrand().equalsIgnoreCase("Samsung")) {
633
                ActivatedImei activatedImei = activatedImeiRepository.selectBySerialNumber(partnerAgeingModel.getSerialNumber());
634
                if (activatedImei != null && activatedImei.getActivationTimestamp().toLocalDate()
635
                        .isBefore(partnerAgeingModel.getBillingDate().plusDays(partnerAgeingModel.getMaxAgeingDays()))) {
636
                    //Lets give money if activation is there and is before the ageing limit of that brand.
637
                    filteredInventoryIds.add(partnerAgeingModel.getInventoryItemId());
638
                } else {
639
                    //If billing happens before ageing expiry
640
                    if (fofoOrder.getCreateTimestamp().toLocalDate().isBefore(partnerAgeingModel.getBillingDate().plusDays(partnerAgeingModel.getMaxAgeingDays()))) {
641
                        filteredInventoryIds.add(partnerAgeingModel.getInventoryItemId());
642
                    }
643
                }
644
            } else {
645
                filteredInventoryIds.add(partnerAgeingModel.getInventoryItemId());
646
            }
647
        }
648
        return filteredInventoryIds;
649
    }
650
 
33087 amit.gupta 651
    @Autowired
652
    WarehouseInventoryItemRepository warehouseInventoryItemRepository;
653
 
31410 amit.gupta 654
    @Override
655
    public float processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
656
        float totalCashback = 0;
657
        FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
658
        // Process only if order is not cancelled
659
        if (fofoOrder.getCancelledTimestamp() == null) {
660
            // PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
661
            // fofoOrder.getCreateTimestamp().toLocalDate());
662
            // TODO - SCHEME
663
            PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
664
                    YearMonth.from(fofoOrder.getCreateTimestamp()));
29927 amit.gupta 665
 
31410 amit.gupta 666
            List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
667
            if (scanRecords.size() == 0) return 0;
668
            Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
669
                    .collect(Collectors.toSet());
31903 amit.gupta 670
            //Check for ageing
31912 amit.gupta 671
            //inventoryItemIds = this.filterImeisByAgeing(inventoryItemIds, fofoOrder);
31903 amit.gupta 672
            //ageingService.filterAgedInventory(inventoryItemIds);
31410 amit.gupta 673
            LOGGER.info("fofoOrderId --- {}", fofoOrderId);
674
            LOGGER.info("scanRecords --- {}", scanRecords);
675
            LOGGER.info("inventoryItemIds --- {}", inventoryItemIds);
31903 amit.gupta 676
 
677
            if (inventoryItemIds.size() == 0) return 0;
678
 
31410 amit.gupta 679
            Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
680
                    .filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
681
                    .collect(Collectors.toSet());
682
            inventoryItems = inventoryItems.stream().filter(inventoryItem -> !BLOCKED_IMEIS.contains(inventoryItem.getSerialNumber())).collect(Collectors.toSet());
29927 amit.gupta 683
 
33087 amit.gupta 684
            //Do not consider imei above 90 days for samsung
33432 amit.gupta 685
            List<String> samsungSerialNumbers = inventoryItems.stream().filter(x -> x.getItem().getBrand().equalsIgnoreCase("samsung")).map(x -> x.getSerialNumber()).collect(Collectors.toList());
33600 ranu 686
 
33432 amit.gupta 687
            if (samsungSerialNumbers.size() > 0) {
33087 amit.gupta 688
                List<AgeingSummaryModel> billedImeiModels = warehouseInventoryItemRepository.findStockAgeingByFofoIdSerialNumbers(retailerId, samsungSerialNumbers);
33606 ranu 689
                List<String> agedSerialNumbers = billedImeiModels.stream().filter(x -> x.isAgedAbove(365)).map(x -> x.getSerialNumber()).collect(Collectors.toList());
690
                if (agedSerialNumbers.size() > 0) {
691
                    List<String> samsungExceptionsSerialNumbers = samsungExceptionRepository.selectAllBySerialNumber(agedSerialNumbers).stream().map(x -> x.getSerialNumber()).collect(Collectors.toList());
692
                    agedSerialNumbers.removeAll(samsungExceptionsSerialNumbers);
693
                }
33432 amit.gupta 694
                inventoryItems = inventoryItems.stream().filter(x -> !agedSerialNumbers.contains(x.getSerialNumber())).collect(Collectors.toSet());
33087 amit.gupta 695
            }
696
 
31903 amit.gupta 697
            if (inventoryItems.size() == 0) return 0;
29927 amit.gupta 698
 
31903 amit.gupta 699
            Map<Integer, List<InventoryItem>> catalogInventoryItemMap = inventoryItems.stream().collect(Collectors.groupingBy(x -> x.getItem().getCatalogItemId()));
700
            Map<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSchemeSummaryMap = tagListingRepository.getModelSchemesByCatalogIdsAndType(retailerId,
701
                    partnerType, new ArrayList<>(catalogInventoryItemMap.keySet()), fofoOrder.getCreateTimestamp());
23444 amit.gupta 702
 
31903 amit.gupta 703
 
31410 amit.gupta 704
            int count = 0;
31903 amit.gupta 705
            for (Map.Entry<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSummaryModelListEntry : catalogSchemeSummaryMap.entrySet()) {
706
                CatalogSummaryModel catalogSummaryModel = catalogSummaryModelListEntry.getKey();
32058 amit.gupta 707
                List<SchemeSummaryModel> schemeSummaryModels = catalogSummaryModelListEntry.getValue().stream().filter(x -> x != null).collect(Collectors.toList());
31903 amit.gupta 708
                List<SchemeType> allOutSchemeTypes = new ArrayList<>();
709
                allOutSchemeTypes.addAll(Arrays.asList(SchemeType.ACTIVATION, SchemeType.INVESTMENT, SchemeType.SPECIAL_SUPPORT, SchemeType.SELLOUT));
710
                allOutSchemeTypes.addAll(OUT_SCHEME_TYPES);
711
                schemeSummaryModels.stream().filter(x -> allOutSchemeTypes.contains(x.getSchemeType())).forEach(x -> x.setProcess(true));
712
                if (schemeSummaryModels.stream().filter(x -> x.isProcess()).count() == 0) continue;
23444 amit.gupta 713
 
31903 amit.gupta 714
                List<InventoryItem> modelInventoryItems = catalogInventoryItemMap.get(catalogSummaryModel.getCatalogId());
715
                for (InventoryItem inventoryItem : modelInventoryItems) {
32165 amit.gupta 716
                    float inventoryItemCashback = this.createSchemeInOut(schemeSummaryModels, inventoryItem);
31903 amit.gupta 717
                    if (inventoryItemCashback > 0) {
718
                        count++;
719
                        totalCashback += inventoryItemCashback;
720
                    }
31410 amit.gupta 721
                }
722
            }
31903 amit.gupta 723
 
31410 amit.gupta 724
            if (count > 0) {
725
                walletService.addAmountToWallet(
726
                        retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT, "Sales margin for invoice number "
727
                                + fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
728
                        totalCashback, fofoOrder.getCreateTimestamp());
729
                fofoOrder.setCashback(totalCashback + fofoOrder.getCashback());
730
            }
731
        }
732
        return totalCashback;
733
    }
22653 ashik.ali 734
 
31410 amit.gupta 735
    @Override
736
    //Tax rate has been passed to 0 to ensure no tax deduction
737
    public float getSpecialSupportAmount(float supportAmount, PartnerType partnerType, LocalDate onDate,
738
                                         int catalogId) throws ProfitMandiBusinessException {
739
        //int itemId = itemRepository.selectAllByCatalogItemId(catalogId).stream().findAny().get().getId();
740
        //float totalTaxRate = stateGstRateRepository.getTotalTaxRate(itemId);
741
        return this.getSpecialSupportAmount(supportAmount, partnerType, onDate, catalogId, 0);
742
    }
23444 amit.gupta 743
 
31410 amit.gupta 744
    @Override
745
    public float getSpecialSupportAmount(float supportAmount, PartnerType partnerType, LocalDate onDate,
746
                                         int catalogId, float taxRate) throws ProfitMandiBusinessException {
747
        float totalMargin = this.selectPercentageScheme(partnerType, onDate, catalogId, false, 0, 0).stream().collect(Collectors.summingDouble(x -> x.getAmount())).floatValue();
748
        float amountToCredit = supportAmount * (1 - (totalMargin / (100 + taxRate)));
749
        return amountToCredit;
750
    }
23444 amit.gupta 751
 
31410 amit.gupta 752
    @Override
33614 amit.gupta 753
    public void rollbackSchemes(List<Integer> inventoryItemIds, String rollbackReason)
31410 amit.gupta 754
            throws Exception {
33614 amit.gupta 755
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(inventoryItemIds);
756
        Map<Integer, InventoryItem> inventoryItemMap = inventoryItems.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
757
        Map<Integer, Integer> purchasePartnerMap = inventoryItems.stream().collect(Collectors.toMap(x -> x.getPurchaseId(), x -> x.getFofoId(), (u, v) -> u));
758
 
759
        LOGGER.info("inventoryItemIds - {}", inventoryItemIds);
760
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(inventoryItemIds));
761
        List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).distinct().collect(Collectors.toList());
762
        if(schemeIds.size() == 0) return;
763
        List<Scheme> schemes = schemeRepository.selectBySchemeIds(schemeIds);
764
        Map<Integer, Float> inSchemesMap = new HashMap<>();
765
        Map<Integer, Float> outSchemesMap = new HashMap<>();
766
        Map<Integer, Scheme> schemesMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
767
        for (SchemeInOut schemeInOut : schemeInOuts) {
768
            Map<Integer, Float> schemePayoutMap;
769
            int inventoryItemId = schemeInOut.getInventoryItemId();
31410 amit.gupta 770
            if (schemeInOut.getRolledBackTimestamp() == null) {
771
                schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
772
                if (schemeInOut.getStatus() == null || schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
33614 amit.gupta 773
                    Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
774
                    if (scheme.getType().equals(SchemeType.IN)) {
775
                        schemePayoutMap = inSchemesMap;
776
                    } else {
777
                        schemePayoutMap = outSchemesMap;
778
                    }
779
                    if (!schemePayoutMap.containsKey(inventoryItemId)) {
780
                        schemePayoutMap.put(inventoryItemId, 0f);
781
                    }
33634 amit.gupta 782
                    schemePayoutMap.put(inventoryItemId, inSchemesMap.get(inventoryItemId)==null?0:inSchemesMap.get(inventoryItemId) + schemeInOut.getAmount());
31410 amit.gupta 783
                }
784
                schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
785
                schemeInOut.setStatusDescription(rollbackReason);
786
            }
787
        }
33614 amit.gupta 788
        Map<Integer, Double> purchaseRollbackAmountMap = inSchemesMap.entrySet().stream().collect(Collectors.groupingBy(x -> inventoryItemMap.get(x.getKey()).getPurchaseId(), Collectors.summingDouble(x -> x.getValue())));
789
 
790
        for (Map.Entry<Integer, Double> purchaseRollbackAmountEntry : purchaseRollbackAmountMap.entrySet()) {
791
            int purchaseId = purchaseRollbackAmountEntry.getKey();
792
            Double amountToRollback = purchaseRollbackAmountEntry.getValue();
793
            if (amountToRollback != null && amountToRollback > 0) {
794
                walletService.rollbackAmountFromWallet(purchasePartnerMap.get(purchaseId), amountToRollback.floatValue(), purchaseId,
795
                        WalletReferenceType.SCHEME_IN, rollbackReason, LocalDateTime.now());
796
            }
31410 amit.gupta 797
        }
798
    }
23444 amit.gupta 799
 
31410 amit.gupta 800
    @Override
801
    public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
802
            throws ProfitMandiBusinessException {
803
        Map<String, Object> map = new HashMap<>();
804
        List<Scheme> schemes = null;
805
        long size = 0;
806
        if (roleManager.isAdmin(roleIds)) {
807
            schemes = schemeRepository.selectAll(offset, limit);
808
            size = schemeRepository.selectAllCount();
809
        } else {
810
            schemes = schemeRepository.selectActiveAll(offset, limit);
811
            size = schemeRepository.selectAllActiveCount();
812
        }
813
        map.put("schemes", schemes);
814
        map.put("start", offset + 1);
815
        map.put("size", size);
816
        if (schemes.size() < limit) {
817
            map.put("end", offset + schemes.size());
818
        } else {
819
            map.put("end", offset + limit);
820
        }
821
        return map;
822
    }
26722 amit.gupta 823
 
31410 amit.gupta 824
    @Override
825
    public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
826
            throws ProfitMandiBusinessException {
827
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
828
        List<Scheme> schemes = null;
829
        if (roleManager.isAdmin(roleIds)) {
830
            schemes = schemeRepository.selectAll(offset, limit);
831
        } else {
832
            schemes = schemeRepository.selectActiveAll(offset, limit);
833
        }
834
        return schemes;
835
    }
27898 amit.gupta 836
 
31410 amit.gupta 837
    @Override
838
    // This is being called to reverse schemes while processing price Drop
839
    public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
840
            throws ProfitMandiBusinessException {
841
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
842
        Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
843
                .collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
29927 amit.gupta 844
 
31410 amit.gupta 845
        for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
846
            float amountToCredit = 0;
847
            float amountToDebit = 0;
848
            int purchaseId = purchaseEntry.getKey();
849
            List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
30454 amit.gupta 850
 
31410 amit.gupta 851
            Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
852
                    .collect(Collectors.toMap(x -> x.getId(), x -> x));
29927 amit.gupta 853
 
31410 amit.gupta 854
            List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
855
            LOGGER.info("Scheme InOuts , {}", schemeInOuts);
856
            if (schemeInOuts.size() == 0) {
857
                continue;
858
            }
859
            List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
860
            Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
861
                    .stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
862
            for (SchemeInOut schemeInOut : schemeInOuts) {
863
                InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
864
                Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
865
                if (scheme.getAmountType().equals(AmountType.FIXED)) {
866
                    continue;
867
                }
868
                if (scheme.getType().equals(SchemeType.IN) && schemeInOut.getRolledBackTimestamp() == null) {
33432 amit.gupta 869
                    schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
870
                    schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
871
                    schemeInOut.setStatusDescription("Margin reversed due to price drop");
872
                    // IF not credited then dont consider any credit/debit for that sio entry
873
                    if (schemeInOut.getCreditTimestamp() != null) {
874
                        amountToDebit += schemeInOut.getAmount();
31410 amit.gupta 875
                    }
876
                }
877
            }
878
            int fofoId = inventoryItems.get(0).getFofoId();
879
            if (amountToDebit > 0) {
880
                walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
881
                        MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), -amountToDebit,
882
                        priceDrop.getAffectedOn());
883
            }
884
        }
885
    }
29231 amit.gupta 886
 
31609 amit.gupta 887
    @Autowired
32060 amit.gupta 888
    UserWalletRepository userWalletRepository;
889
    @Autowired
31609 amit.gupta 890
    UserWalletHistoryRepository userWalletHistoryRepository;
891
 
31410 amit.gupta 892
    @Override
893
    // Always being called from cancel order/bad return means no SCHEME IN is considered
894
    public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
895
                               List<SchemeType> schemeTypes) throws ProfitMandiBusinessException {
896
        Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
897
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
898
        LOGGER.info("inventoryItems" + inventoryItems);
23444 amit.gupta 899
 
31410 amit.gupta 900
        Map<SchemeType, SchemeInOut> schemeTypeMap = new HashMap<>();
30454 amit.gupta 901
 
31410 amit.gupta 902
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
32060 amit.gupta 903
        List<SchemeInOut> rolledBacks = schemeInOuts.stream().filter(x -> x.getStatusDescription().equals(reversalReason)).collect(Collectors.toList());
31410 amit.gupta 904
        float amountToRollback = 0;
23444 amit.gupta 905
 
31410 amit.gupta 906
        if (!schemeInOuts.isEmpty()) {
907
            List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
908
            LOGGER.info("schemeIds" + schemeIds);
29231 amit.gupta 909
 
31410 amit.gupta 910
            Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
911
                    .stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
32060 amit.gupta 912
            if (rolledBacks.size() > 0) {
913
                for (SchemeInOut schemeInOut : rolledBacks) {
914
                    Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
915
                    if (schemeTypes.contains(scheme.getType())) {
916
                        schemeTypeMap.put(scheme.getType(), schemeInOut);
917
                        if (schemeInOut.getCreditTimestamp() != null) {
31410 amit.gupta 918
                            amountToRollback += schemeInOut.getAmount();
919
                        }
920
                    }
921
                }
32060 amit.gupta 922
            } else {
923
                for (SchemeInOut schemeInOut : schemeInOuts) {
924
                    Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
925
                    if (schemeTypes.contains(scheme.getType())) {
926
                        if (schemeInOut.getRolledBackTimestamp() == null) {
927
                            schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
928
                            if (schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
929
                                amountToRollback += schemeInOut.getAmount();
930
                            }
931
                            schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
932
                            schemeInOut.setStatusDescription(reversalReason);
933
                        }
934
                    }
935
                }
31410 amit.gupta 936
            }
937
        }
32060 amit.gupta 938
 
31410 amit.gupta 939
        int fofoId = inventoryItems.get(0).getFofoId();
31609 amit.gupta 940
        WalletReferenceType walletReferenceType = schemeTypes.containsAll(SchemeService.OUT_SCHEME_TYPES) ? WalletReferenceType.SCHEME_OUT
941
                : schemeTypes.contains(SchemeType.ACTIVATION) ? WalletReferenceType.ACTIVATION_SCHEME
942
                : schemeTypes.contains(SchemeType.SPECIAL_SUPPORT) ? WalletReferenceType.SPECIAL_SUPPORT
32060 amit.gupta 943
                : schemeTypes.contains(SchemeType.INVESTMENT) ? WalletReferenceType.SCHEME_OUT : null;
944
        List<UserWalletHistory> userWalletHistoryList = null;
32058 amit.gupta 945
        if (amountToRollback > 0 && walletReferenceType != null) {
946
            // Mark appropriate reference of rollback investment margin
32060 amit.gupta 947
            if (schemeTypes.contains(SchemeType.INVESTMENT) && schemeTypeMap.containsKey(SchemeType.INVESTMENT)) {
948
                LocalDateTime creditTime = schemeTypeMap.get(SchemeType.INVESTMENT).getCreditTimestamp();
949
                if (creditTime == null) return;
950
                int investmentReversalReference = Integer.parseInt(FormattingUtils.getYearMonth(creditTime.minusMonths(1)));
951
                UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
952
                userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(userWallet.getUserId(), investmentReversalReference, WalletReferenceType.INVESTMENT_PAYOUT);
953
                if (userWalletHistoryList.size() > 0) {
954
                    walletReferenceType = WalletReferenceType.INVESTMENT_PAYOUT;
955
                } else {
956
                    userWalletHistoryList = null;
32058 amit.gupta 957
                }
32060 amit.gupta 958
            }
959
            if (userWalletHistoryList == null) {
960
                userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reversalReference, walletReferenceType);
961
            }
962
            if (userWalletHistoryList.size() > 0) {
963
                int maxDeductible = userWalletHistoryList.stream().collect(Collectors.summingInt(x -> x.getAmount()));
964
                if (maxDeductible > 0) {
32165 amit.gupta 965
                    LOGGER.info("----------> maxDeductible {}, amountToRollback {}, reversalReference {}, walletReferenceType {} ", maxDeductible, amountToRollback, reversalReference, walletReferenceType);
32060 amit.gupta 966
                    walletService.rollbackAmountFromWallet(fofoId, Math.min(maxDeductible, amountToRollback), reversalReference, walletReferenceType,
967
                            reversalReason, LocalDateTime.now());
968
                }
31609 amit.gupta 969
 
31903 amit.gupta 970
            }
32058 amit.gupta 971
        }
31410 amit.gupta 972
    }
29231 amit.gupta 973
 
32060 amit.gupta 974
 
31410 amit.gupta 975
    @Override
976
    public double getTotalMargin(int itemId, PartnerType partnerType, LocalDateTime dateTime) {
977
        Session session = sessionFactory.getCurrentSession();
978
        CriteriaBuilder cb = session.getCriteriaBuilder();
979
        CriteriaQuery<Double> criteriaQuery = cb.createQuery(Double.class);
980
        Root<SchemeItem> schemeItem = criteriaQuery.from(SchemeItem.class);
981
        Root<Scheme> scheme = criteriaQuery.from(Scheme.class);
982
        Predicate schemePredicate = cb.equal(scheme.get(ProfitMandiConstants.AMOUNT_TYPE), AmountType.PERCENTAGE);
983
        Predicate lessThanPredicate = cb.lessThanOrEqualTo(scheme.get(ProfitMandiConstants.END_DATE_TIME), dateTime);
984
        Predicate greaterThanPredicate = cb.greaterThanOrEqualTo(scheme.get(ProfitMandiConstants.START_DATE_TIME),
985
                dateTime);
986
        Predicate joinPredicate = cb.equal(scheme.get("id"), schemeItem.get("schemeId"));
987
        Predicate schemeItemPredicate = cb.equal(schemeItem.get(ProfitMandiConstants.ITEM_ID), itemId);
988
        criteriaQuery.select(cb.sum(scheme.get(ProfitMandiConstants.AMOUNT))).where(schemePredicate, lessThanPredicate,
989
                greaterThanPredicate, schemeItemPredicate, joinPredicate);
29231 amit.gupta 990
 
31410 amit.gupta 991
        Query<Double> query = session.createQuery(criteriaQuery);
992
        return query.getSingleResult() + ProfitMandiConstants.SCHEME_INVESTMENT_MARGIN;
29231 amit.gupta 993
 
31410 amit.gupta 994
    }
23444 amit.gupta 995
 
32972 amit.gupta 996
 
31410 amit.gupta 997
    @Override
33614 amit.gupta 998
    public Map<Integer, Float> getCatalogSchemeCashBack(int fofoId, List<Integer> catalogIds) throws
999
            ProfitMandiBusinessException {
32972 amit.gupta 1000
        PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
1001
        Map<CatalogSummaryModel, List<SchemeSummaryModel>> catalogModelMap = tagListingRepository.getModelSchemesByCatalogIdsAndType(fofoId, partnerType, catalogIds, LocalDate.now().atStartOfDay());
1002
 
1003
        Map<Integer, Float> catalogCashbackMap = new HashMap<>();
1004
        for (Map.Entry<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSummaryModelListEntry : catalogModelMap.entrySet()) {
1005
            int catalogItemId = catalogSummaryModelListEntry.getKey().getCatalogId();
1006
            List<SchemeSummaryModel> schemeSummaryModels = catalogSummaryModelListEntry.getValue();
1007
 
1008
            float totalCashback = schemeSummaryModels.stream()
1009
                    .filter(x -> Arrays.asList(SchemeType.ACTIVATION, SchemeType.SPECIAL_SUPPORT, SchemeType.SELLOUT).contains(x.getSchemeType())
1010
                            && x.getAmountType().equals(AmountType.FIXED))
1011
                    .collect(Collectors.summingDouble(x -> x.getAmount())).floatValue();
1012
            catalogCashbackMap.put(catalogItemId, totalCashback);
31410 amit.gupta 1013
        }
32972 amit.gupta 1014
        return catalogCashbackMap;
31410 amit.gupta 1015
    }
30572 amit.gupta 1016
 
31410 amit.gupta 1017
    @Override
31903 amit.gupta 1018
    public List<Scheme> selectSchemeByPartnerTypeFofoId(PartnerType partnerType, LocalDate onDate, int catalogId,
1019
                                                        int fofoId, int offset, int limit) throws ProfitMandiBusinessException {
31410 amit.gupta 1020
        Session session = sessionFactory.getCurrentSession();
1021
        final TypedQuery<Scheme> typedQuery = session.createNamedQuery(
1022
                "Scheme.selectSchemeByModelsPartnerTypeFofoId", Scheme.class);
1023
        typedQuery.setParameter("catalogIds", Arrays.asList(catalogId));
1024
        typedQuery.setParameter("fofoIds", Arrays.asList(fofoId, 0));
1025
        typedQuery.setParameter("onDate", onDate.atStartOfDay());
1026
        typedQuery.setParameter("partnerTypes", Arrays.asList(partnerType, partnerType.ALL));
1027
        typedQuery.setFirstResult(offset);
1028
        if (limit != 0) {
1029
            typedQuery.setMaxResults(limit);
1030
        }
1031
        return typedQuery.getResultList();
1032
    }
30463 amit.gupta 1033
 
33432 amit.gupta 1034
    @Override
1035
    public void processSchemeIn(List<InventoryItem> inventoryItems) throws ProfitMandiBusinessException {
1036
        Map<Integer, List<InventoryItem>> purchaseIdInventoryItemsMap = inventoryItems.stream().collect(Collectors.groupingBy(x -> x.getPurchaseId()));
1037
        for (Map.Entry<Integer, List<InventoryItem>> purchaseIdInventoryItemEntry : purchaseIdInventoryItemsMap.entrySet()) {
1038
            int retailerId = purchaseIdInventoryItemEntry.getValue().get(0).getFofoId();
1039
            this.processSchemeIn(purchaseIdInventoryItemEntry.getKey(), retailerId);
1040
        }
1041
    }
1042
 
32309 amit.gupta 1043
    @Autowired
1044
    FofoStoreRepository fofoStoreRepository;
1045
 
1046
 
31410 amit.gupta 1047
    @Override
32309 amit.gupta 1048
    @Cacheable(value = "staticscheme", cacheManager = "oneDayCacheManager")
1049
    public Scheme getStaticScheme(int fofoId) throws ProfitMandiBusinessException {
33165 amit.gupta 1050
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
32504 amit.gupta 1051
        Scheme scheme = null;
1052
        if (fofoStore.getTarget() > 0) {
1053
            scheme = new Scheme();
33704 amit.gupta 1054
            scheme.setName("Super Retailer - Club 3");
1055
            scheme.setStartDateTime(LocalDate.of(2024, 8, 1).atStartOfDay());
1056
            scheme.setEndDateTime(LocalDate.of(2024, 11, 30).atTime(LocalTime.MAX));
32504 amit.gupta 1057
            scheme.setTarget(fofoStore.getTarget());
33548 amit.gupta 1058
 
33704 amit.gupta 1059
            if (scheme.getEndDateTime().plusDays(5).isBefore(LocalDateTime.now())) return null;
32504 amit.gupta 1060
        }
33165 amit.gupta 1061
        return scheme;
32309 amit.gupta 1062
    }
1063
 
1064
    @Override
31410 amit.gupta 1065
    public List<Scheme> selectSchemeByPartnerType(PartnerType partnerType, LocalDate onDate, int catalogId,
1066
                                                  boolean isAdmin, int offset, int limit) throws ProfitMandiBusinessException {
1067
        Session session = sessionFactory.getCurrentSession();
1068
        List<Predicate> andPredicates = new ArrayList<>();
1069
        CriteriaBuilder cb = session.getCriteriaBuilder();
1070
        CriteriaQuery<Scheme> query = cb.createQuery(Scheme.class);
1071
        Root<Scheme> scheme = query.from(Scheme.class);
1072
        if (!partnerType.equals(PartnerType.ALL)) {
1073
            List<PartnerType> pt = new ArrayList<>();
1074
            pt.add(PartnerType.ALL);
1075
            pt.add(partnerType);
1076
            andPredicates.add(cb.in(scheme.get("partnerType")).value(pt));
1077
        }
1078
        cb.desc(cb.isNull(scheme.get("expireTimestamp")));
1079
        if (catalogId > 0) {
30454 amit.gupta 1080
 
31410 amit.gupta 1081
            List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByCatalogId(catalogId);
1082
            LOGGER.info("schemeId" + schemeIds);
1083
            if (schemeIds.isEmpty()) {
1084
                return new ArrayList<>();
1085
            }
1086
            andPredicates.add(cb.in(scheme.get("id")).value(schemeIds));
1087
            if (onDate != null) {
1088
                andPredicates.add(cb.greaterThan(scheme.get("endDateTime"), onDate.atStartOfDay()));
1089
                andPredicates.add(cb.lessThanOrEqualTo(scheme.get("startDateTime"), onDate.atStartOfDay()));
1090
            }
1091
        }
1092
        if (!isAdmin) {
1093
            andPredicates.add(cb.isNotNull(scheme.get("activeTimestamp")));
1094
        }
1095
        query.where(cb.and(andPredicates.toArray(new Predicate[0])));
1096
        query.orderBy(cb.desc(cb.function("isnull", Boolean.class, scheme.get("expireTimestamp"))));
1097
        if (limit == 0) {
1098
            return session.createQuery(query).setFirstResult(offset).getResultList();
1099
        }
1100
        return session.createQuery(query).setFirstResult(offset).setMaxResults(limit).getResultList();
30454 amit.gupta 1101
 
31410 amit.gupta 1102
    }
30454 amit.gupta 1103
 
31410 amit.gupta 1104
    @Override
1105
    public List<Scheme> selectPercentageScheme(PartnerType partnerType, LocalDate onDate, int catalogId,
1106
                                               boolean isAdmin, int offset, int limit) throws ProfitMandiBusinessException {
1107
        List<Scheme> schemes = this.selectSchemeByPartnerType(partnerType, onDate, catalogId, isAdmin, offset, limit);
1108
        return schemes.stream().filter(x -> x.getAmountType().equals(AmountType.PERCENTAGE)).collect(Collectors.toList());
1109
    }
30454 amit.gupta 1110
 
31410 amit.gupta 1111
    @Override
1112
    public void processActivation() throws ProfitMandiBusinessException {
1113
        List<SchemeInOut> pendingPayouts = schemeInOutRepository.selectAllPending();
1114
        List<Integer> schemeIds = new ArrayList<>();
1115
        Set<Integer> inventoryIds = new HashSet<>();
1116
        for (SchemeInOut pendingPayout : pendingPayouts) {
1117
            schemeIds.add(pendingPayout.getSchemeId());
1118
        }
1119
        Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, 0).stream()
1120
                .filter(x -> x.getType().equals(SchemeType.ACTIVATION) || x.getType().equals(SchemeType.SPECIAL_SUPPORT))
1121
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
1122
        pendingPayouts = pendingPayouts.stream().filter(x -> schemesMap.get(x.getSchemeId()) != null)
1123
                .collect(Collectors.toList());
23884 amit.gupta 1124
 
31410 amit.gupta 1125
        for (SchemeInOut pendingPayout : pendingPayouts) {
1126
            inventoryIds.add(pendingPayout.getInventoryItemId());
1127
        }
1128
        Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryIds).stream()
1129
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
1130
        Map<String, InventoryItem> serialNumberMap = inventoryItemMap.values().stream()
1131
                .collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
23796 amit.gupta 1132
 
31410 amit.gupta 1133
        List<ActivatedImei> activatedImeis = activatedImeiRepository
1134
                .selectBySerialNumbers(new ArrayList<>(serialNumberMap.keySet())).stream().collect(Collectors.toList());
23508 amit.gupta 1135
 
31410 amit.gupta 1136
        Map<String, ActivatedImei> activatedImeiMap = activatedImeis.stream()
1137
                .collect(Collectors.toMap(x -> x.getSerialNumber().toLowerCase(), x -> x));
1138
        for (SchemeInOut pendingPayout : pendingPayouts) {
31914 amit.gupta 1139
            Scheme scheme = schemesMap.get(pendingPayout.getSchemeId());
31410 amit.gupta 1140
            InventoryItem ii = inventoryItemMap.get(pendingPayout.getInventoryItemId());
1141
            String serialNumber = ii.getSerialNumber().toLowerCase();
1142
            ActivatedImei activatedImei = activatedImeiMap.get(serialNumber);
1143
            if (activatedImei == null) {
1144
                continue;
1145
            }
1146
            if (scheme.isWithinRange(activatedImei.getActivationTimestamp())) {
1147
                int fofoId = ii.getFofoId();
1148
                // Get latest order Id
1149
                int orderId = scanRecordRepository.selectByInventoryItemId(ii.getId()).stream()
1150
                        .filter(x -> x.getOrderId() > 0)
1151
                        .sorted(Comparator.comparing(ScanRecord::getCreateTimestamp).reversed()).findFirst().get()
1152
                        .getOrderId();
1153
                FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
31916 amit.gupta 1154
 
31921 amit.gupta 1155
                InventoryPayoutModel inventoryPayoutModel = priceCircularService.getPayouts(ii);
31916 amit.gupta 1156
                AmountModel amountModel = new AmountModel();
1157
                amountModel.setAmount(scheme.getAmount());
1158
                amountModel.setAmountType(scheme.getAmountType());
31921 amit.gupta 1159
                double amountToRollout = inventoryPayoutModel.getRolloutAmount(amountModel);
32058 amit.gupta 1160
                pendingPayout.setAmount((float) amountToRollout);
31410 amit.gupta 1161
                if (scheme.getType().equals(SchemeType.ACTIVATION)) {
1162
                    walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.ACTIVATION_SCHEME,
31914 amit.gupta 1163
                            "Activation margin for " + ii.getItem().getItemDescriptionNoColor() + ", Imei - " + serialNumber, (float) amountToRollout,
31410 amit.gupta 1164
                            fofoOrder.getCreateTimestamp());
1165
                    pendingPayout.setStatusDescription("Activation margin credited, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
1166
                } else {
1167
                    walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.SPECIAL_SUPPORT,
31914 amit.gupta 1168
                            "Special Support for " + ii.getItem().getItemDescriptionNoColor() + ", Imei - " + serialNumber, (float) amountToRollout,
31410 amit.gupta 1169
                            fofoOrder.getCreateTimestamp());
1170
                    pendingPayout.setStatusDescription("Special support credited, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
1171
                }
1172
                pendingPayout.setCreditTimestamp(LocalDateTime.now());
1173
                pendingPayout.setStatus(SchemePayoutStatus.CREDITED);
1174
            } else {
1175
                pendingPayout.setStatus(SchemePayoutStatus.REJECTED);
1176
                pendingPayout.setRolledBackTimestamp(LocalDateTime.now());
1177
                ;
1178
                pendingPayout.setStatusDescription(
1179
                        "Rejected, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
1180
            }
1181
        }
1182
    }
24976 amit.gupta 1183
 
31410 amit.gupta 1184
    @Override
1185
    public void processActivatedImeisForSchemes() throws ProfitMandiBusinessException {
1186
        List<SchemesImeisModel> schemesImeisModels = schemeRepository.selectSelectUnpaidSchemes();
1187
        LOGGER.info("Total Size - " + schemesImeisModels.size());
1188
        List<Integer> orderIds = schemesImeisModels.stream().map(x -> x.getOrderId()).collect(Collectors.toList());
1189
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectAllByOrderIds(orderIds);
1190
        Map<Integer, FofoOrder> validOrdersMap = fofoOrders.stream().filter(x -> x.getCancelledTimestamp() == null).collect(Collectors.toMap(x -> x.getId(), x -> x));
1191
        Map<String, List<SchemesImeisModel>> validImeiSchemesModelMap = schemesImeisModels.stream().filter(x -> validOrdersMap.containsKey(x.getOrderId())).collect(Collectors.groupingBy(x -> x.getImei()));
1192
        for (Map.Entry<String, List<SchemesImeisModel>> imeiListEntry : validImeiSchemesModelMap.entrySet()) {
1193
            SchemesImeisModel schemesImeisModel = imeiListEntry.getValue().get(0);
1194
            List<Integer> schemeIds = imeiListEntry.getValue().stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
1195
            LOGGER.info("Serial Number  - {}, Scheme IDs - {}", schemesImeisModel.getImei(), schemeIds);
1196
            InventoryItem inventoryItem = inventoryItemRepository.selectById(schemesImeisModel.getInventoryItemId());
1197
            List<Scheme> schemes = schemeRepository.selectBySchemeIds(schemeIds);
1198
            List<Scheme> supportSchemes = schemes.stream().filter(x -> Arrays.asList(SchemeType.SPECIAL_SUPPORT, SchemeType.ACTIVATION).contains(x.getType())).collect(Collectors.toList());
1199
            if (supportSchemes.size() > 0) {
32165 amit.gupta 1200
                for (Scheme scheme : supportSchemes) {
1201
                    List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(scheme.getId(), inventoryItem.getId());
32972 amit.gupta 1202
                    if (schemeInOuts.stream().filter(x -> Arrays.asList(SchemePayoutStatus.CREDITED, SchemePayoutStatus.PENDING).contains(x.getStatus())).count() > 0) {
32165 amit.gupta 1203
                        continue;
1204
                    }
1205
                    SchemeInOut sio = new SchemeInOut();
1206
                    sio.setAmount(0);
1207
                    sio.setInventoryItemId(inventoryItem.getId());
1208
                    sio.setSchemeId(scheme.getId());
1209
                    sio.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
1210
                    sio.setStatus(SchemePayoutStatus.PENDING);
1211
                    schemeInOutRepository.persist(sio);
1212
                }
31410 amit.gupta 1213
            }
1214
        }
1215
    }
22653 ashik.ali 1216
}