Subversion Repositories SmartDukaan

Rev

Rev 31450 | Rev 31609 | 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;
23339 ashik.ali 13
import com.spice.profitmandi.dao.entity.catalog.Item;
22653 ashik.ali 14
import com.spice.profitmandi.dao.entity.catalog.Scheme;
31170 amit.gupta 15
import com.spice.profitmandi.dao.entity.catalog.SchemeRegion;
30897 amit.gupta 16
import com.spice.profitmandi.dao.entity.catalog.SchemesImeisModel;
29927 amit.gupta 17
import com.spice.profitmandi.dao.entity.fofo.*;
26498 amit.gupta 18
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
23527 ashik.ali 19
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
22653 ashik.ali 20
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
25111 amit.gupta 21
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
27377 amit.gupta 22
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
25503 amit.gupta 23
import com.spice.profitmandi.dao.model.CreateSchemeRequest;
31170 amit.gupta 24
import com.spice.profitmandi.dao.repository.catalog.*;
23968 amit.gupta 25
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
29927 amit.gupta 26
import com.spice.profitmandi.dao.repository.fofo.*;
26498 amit.gupta 27
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
29927 amit.gupta 28
import com.spice.profitmandi.service.NotificationService;
23798 amit.gupta 29
import com.spice.profitmandi.service.authentication.RoleManager;
26722 amit.gupta 30
import com.spice.profitmandi.service.inventory.PurchaseService;
22859 ashik.ali 31
import com.spice.profitmandi.service.wallet.WalletService;
32
import in.shop2020.model.v1.order.WalletReferenceType;
29927 amit.gupta 33
import org.apache.logging.log4j.LogManager;
34
import org.apache.logging.log4j.Logger;
35
import org.hibernate.Session;
36
import org.hibernate.SessionFactory;
37
import org.hibernate.query.Query;
38
import org.springframework.beans.factory.annotation.Autowired;
39
import org.springframework.beans.factory.annotation.Qualifier;
40
import org.springframework.cache.annotation.Cacheable;
41
import org.springframework.stereotype.Component;
22859 ashik.ali 42
 
31170 amit.gupta 43
import javax.persistence.TypedQuery;
29927 amit.gupta 44
import javax.persistence.criteria.CriteriaBuilder;
45
import javax.persistence.criteria.CriteriaQuery;
46
import javax.persistence.criteria.Predicate;
47
import javax.persistence.criteria.Root;
48
import java.text.MessageFormat;
49
import java.time.LocalDate;
50
import java.time.LocalDateTime;
51
import java.time.YearMonth;
52
import java.util.*;
53
import java.util.stream.Collectors;
54
 
22653 ashik.ali 55
@Component
56
public class SchemeServiceImpl implements SchemeService {
57
 
31410 amit.gupta 58
    private static final Logger LOGGER = LogManager.getLogger(SchemeServiceImpl.class);
59
    private static final Set<Integer> tagIds = new HashSet<Integer>(Arrays.asList(4));
60
    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", "868494052222110", "868494054682394", "869599053512357");
31450 amit.gupta 61
    private static final List<SchemeType> ACTIVATION_SCHEME_TYPES = Arrays.asList(SchemeType.ACTIVATION, SchemeType.SPECIAL_SUPPORT, SchemeType.SELLOUT);
31410 amit.gupta 62
    @Autowired
63
    StateGstRateRepository stateGstRateRepository;
64
    @Autowired
65
    NotificationService notificationService;
66
    @Autowired
67
    @Qualifier("fofoInventoryItemRepository")
68
    private InventoryItemRepository inventoryItemRepository;
69
    @Autowired
70
    private ActivatedImeiRepository activatedImeiRepository;
71
    @Autowired
72
    private PartnerTypeChangeService partnerTypeChangeService;
73
    @Autowired
74
    private PurchaseService purchaseService;
75
    @Autowired
76
    private ScanRecordRepository scanRecordRepository;
77
    @Autowired
78
    private SessionFactory sessionFactory;
79
    @Autowired
80
    private SchemeRepository schemeRepository;
81
    @Autowired
82
    private PriceDropRepository priceDropRepository;
83
    @Autowired
84
    private RoleManager roleManager;
85
    @Autowired
86
    private RetailerRepository retailerRepository;
87
    @Autowired
88
    private ReporticoService reporticoService;
89
    @Autowired
90
    private TagListingRepository tagListingRepository;
91
    @Autowired
92
    private SchemeInOutRepository schemeInOutRepository;
93
    @Autowired
94
    @Qualifier("catalogItemRepository")
95
    private ItemRepository itemRepository;
96
    @Autowired
97
    private SchemeItemRepository schemeItemRepository;
98
    @Autowired
99
    private SchemeRegionRepository schemeRegionRepository;
100
    @Autowired
101
    private WalletService walletService;
102
    @Autowired
103
    private PurchaseRepository purchaseRepository;
104
    @Autowired
105
    private FofoOrderRepository fofoOrderRepository;
23444 amit.gupta 106
 
31410 amit.gupta 107
    @Override
108
    public void saveScheme(int creatorId, CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
23444 amit.gupta 109
 
31410 amit.gupta 110
        this.validateCreateSchemeRequest(createSchemeRequest);
27898 amit.gupta 111
 
31410 amit.gupta 112
        Scheme scheme = this.toScheme(creatorId, createSchemeRequest);
25503 amit.gupta 113
 
31410 amit.gupta 114
        if (scheme.getStartDateTime().isAfter(scheme.getEndDateTime())) {
115
            throw new ProfitMandiBusinessException(
116
                    ProfitMandiConstants.START_DATE + ", " + ProfitMandiConstants.END_DATE,
117
                    scheme.getStartDateTime() + ", " + scheme.getEndDateTime(), "SCHM_VE_1005");
118
        }
26722 amit.gupta 119
 
31410 amit.gupta 120
        // this.validateItemIds(createSchemeRequest);
121
        schemeRepository.persist(scheme);
122
        for (int catalogId : createSchemeRequest.getCatalogIds()) {
123
            SchemeItem schemeItem = new SchemeItem();
124
            schemeItem.setSchemeId(scheme.getId());
125
            schemeItem.setCatalogId(catalogId);
126
            schemeItemRepository.persist(schemeItem);
127
        }
23444 amit.gupta 128
 
31410 amit.gupta 129
        for (int regionId : createSchemeRequest.getRegionIds()) {
130
            SchemeRegion schemeRegion = new SchemeRegion();
131
            schemeRegion.setSchemeId(scheme.getId());
132
            schemeRegion.setRegionId(regionId);
133
            schemeRegionRepository.persist(schemeRegion);
134
        }
26332 amit.gupta 135
 
31410 amit.gupta 136
    }
26722 amit.gupta 137
 
31410 amit.gupta 138
    private void validateCreateSchemeRequest(CreateSchemeRequest createSchemeRequest)
139
            throws ProfitMandiBusinessException {
140
        if (createSchemeRequest.getName() == null || createSchemeRequest.getName().isEmpty()) {
141
            throw new ProfitMandiBusinessException(ProfitMandiConstants.NAME, createSchemeRequest.getName(),
142
                    "SCHM_VE_1000");
143
        }
144
        if (createSchemeRequest.getAmount() <= 0) {
145
            throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
146
                    "SCHM_VE_1001");
147
        }
26684 amit.gupta 148
 
31410 amit.gupta 149
        if (createSchemeRequest.getAmountType().equals(AmountType.PERCENTAGE)
150
                && createSchemeRequest.getAmount() > 100) {
151
            throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
152
                    "SCHM_VE_1002");
153
        }
23444 amit.gupta 154
 
31410 amit.gupta 155
        if (createSchemeRequest.getStartDate() == null) {
156
            throw new ProfitMandiBusinessException(ProfitMandiConstants.START_DATE, createSchemeRequest.getStartDate(),
157
                    "SCHM_VE_1003");
158
        }
159
        if (createSchemeRequest.getEndDate() == null) {
160
            throw new ProfitMandiBusinessException(ProfitMandiConstants.END_DATE, createSchemeRequest.getEndDate(),
161
                    "SCHM_VE_1004");
162
        }
163
    }
23798 amit.gupta 164
 
31410 amit.gupta 165
    private void validateItemIds(CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
166
        if (createSchemeRequest.getCatalogIds() == null || createSchemeRequest.getCatalogIds().isEmpty()) {
167
            throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getCatalogIds(),
168
                    "SCHM_1003");
169
        }
170
        List<Integer> foundItemIds = itemRepository.selectIdsByIdsAndType(createSchemeRequest.getCatalogIds(),
171
                ItemType.SERIALIZED);
172
        if (foundItemIds.size() != createSchemeRequest.getCatalogIds().size()) {
173
            createSchemeRequest.getCatalogIds().removeAll(foundItemIds);
174
            throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getCatalogIds(),
175
                    "SCHM_1004");
176
        }
177
    }
29927 amit.gupta 178
 
31410 amit.gupta 179
    @Override
180
    public Scheme getSchemeById(int schemeId) throws ProfitMandiBusinessException {
181
        Scheme scheme = schemeRepository.selectById(schemeId);
182
        List<Integer> catalogIds = schemeItemRepository.selectCatalogIdsBySchemeId(scheme.getId());
183
        if (catalogIds.size() > 0) {
184
            List<Item> items = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds));
185
            scheme.setCatalogStringMap(this.toCatalogStringMap(items));
186
        }
187
        return scheme;
188
    }
24562 amit.gupta 189
 
31410 amit.gupta 190
    public Map<Integer, String> toCatalogStringMap(List<Item> items) {
191
        Map<Integer, String> catalogMap = new HashMap<>();
192
        for (Item item : items) {
193
            if (!catalogMap.containsKey(item.getCatalogItemId())) {
194
                catalogMap.put(item.getCatalogItemId(), item.getItemDescriptionNoColor());
195
            }
196
        }
197
        return catalogMap;
198
    }
29927 amit.gupta 199
 
31410 amit.gupta 200
    private Set<Integer> schemeItemsToCatalogIds(List<SchemeItem> schemeItems) {
201
        Set<Integer> catalogId = new HashSet<>();
202
        for (SchemeItem schemeItem : schemeItems) {
203
            catalogId.add(schemeItem.getCatalogId());
204
        }
205
        return catalogId;
206
    }
23444 amit.gupta 207
 
31410 amit.gupta 208
    @Override
209
    public List<SchemeModel> getAllSchemeModels(LocalDateTime startDateTime, LocalDateTime endDateTime) {
210
        List<Scheme> schemes = schemeRepository.selectAllBetweenCreateTimestamp(startDateTime, endDateTime);
211
        Map<Integer, Scheme> schemeIdSchemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
212
        List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(schemeIdSchemeMap.keySet());
213
        Set<Integer> catalogIds = schemeItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
214
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
215
        Map<Integer, String> catalogStringMap = this.toCatalogStringMap(items);
216
        this.addCatalogIdsToSchemes(schemeItems, schemeIdSchemeMap, catalogStringMap);
217
        return this.toSchemeModels(schemeIdSchemeMap);
218
    }
23444 amit.gupta 219
 
31410 amit.gupta 220
    private List<SchemeModel> toSchemeModels(Map<Integer, Scheme> schemeIdSchemeMap) {
221
        List<SchemeModel> schemeModels = new ArrayList<>();
222
        for (Map.Entry<Integer, Scheme> schemeIdSchemeEntry : schemeIdSchemeMap.entrySet()) {
223
            schemeModels.add(this.toSchemeModel(schemeIdSchemeEntry.getValue()));
224
        }
225
        return schemeModels;
226
    }
23444 amit.gupta 227
 
31410 amit.gupta 228
    private SchemeModel toSchemeModel(Scheme scheme) {
229
        SchemeModel schemeModel = new SchemeModel();
230
        schemeModel.setSchemeId(scheme.getId());
231
        schemeModel.setName(scheme.getName());
232
        schemeModel.setDescription(scheme.getDescription());
233
        schemeModel.setSchemeType(scheme.getType().toString());
234
        schemeModel.setAmountType(scheme.getAmountType().toString());
235
        schemeModel.setAmount(scheme.getAmount());
236
        schemeModel.setStartDateTime(StringUtils.toString(scheme.getStartDateTime()));
237
        schemeModel.setEndDateTime(StringUtils.toString(scheme.getEndDateTime()));
238
        schemeModel.setCreateTimestamp(StringUtils.toString(scheme.getCreateTimestamp()));
239
        schemeModel.setActiveTimestamp(StringUtils.toString(scheme.getActiveTimestamp()));
240
        schemeModel.setExpireTimestamp(StringUtils.toString(scheme.getExpireTimestamp()));
241
        schemeModel.setCreatedBy(scheme.getCreatedBy());
242
        schemeModel.setCatalogStringMap(scheme.getCatalogStringMap());
243
        schemeModel.setRetailerIds(scheme.getRetailerIds());
244
        return schemeModel;
245
    }
23444 amit.gupta 246
 
31410 amit.gupta 247
    private void addCatalogIdsToSchemes(List<SchemeItem> schemeItems, Map<Integer, Scheme> schemeIdSchemeMap,
248
                                        Map<Integer, String> catalogStringMap) {
249
        for (SchemeItem schemeItem : schemeItems) {
250
            Scheme scheme = schemeIdSchemeMap.get(schemeItem.getSchemeId());
251
            scheme.getCatalogStringMap().put(schemeItem.getCatalogId(), catalogStringMap.get(schemeItem.getCatalogId()));
252
        }
253
    }
31170 amit.gupta 254
 
31410 amit.gupta 255
    @Override
256
    public void activeSchemeById(int schemeId) throws ProfitMandiBusinessException {
257
        Scheme scheme = schemeRepository.selectById(schemeId);
258
        if (scheme.getActiveTimestamp() != null) {
259
            throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
260
                    "SCHM_1005");
261
        }
262
        if (scheme.getExpireTimestamp() != null) {
263
            throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
264
                    "SCHM_1006");
265
        }
266
        scheme.setActiveTimestamp(LocalDateTime.now());
267
        this.sendSchemeNotification(scheme);
23444 amit.gupta 268
 
269
 
31410 amit.gupta 270
        /*
271
         * if (scheme.getType() == SchemeType.IN) {
272
         * this.processPreviousPurchases(scheme); } else if (scheme.getType() ==
273
         * SchemeType.OUT) { this.processPreviousSales(scheme); }
274
         */
275
    }
23796 amit.gupta 276
 
31410 amit.gupta 277
    private void sendSchemeNotification(Scheme scheme) throws ProfitMandiBusinessException {
278
        if (ACTIVATION_SCHEME_TYPES.contains(scheme.getType())) {
31336 amit.gupta 279
 
31410 amit.gupta 280
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
281
            List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(Collections.singleton(scheme.getId()));
282
            Set<Integer> catalogIds = schemeItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
283
            List<String> itemDescriptions = itemRepository.selectAllByCatalogIds(catalogIds).stream().filter(Utils.distinctByKey(Item::getCatalogItemId))
284
                    .map(x -> x.getItemDescriptionNoColor()).collect(Collectors.toList());
285
            String titleTemplate = "%s of Rs.%s for %s";
286
            String schemeString = "Activation scheme";
287
            if (scheme.getType().equals(SchemeType.SPECIAL_SUPPORT)) {
288
                schemeString = "Special Support";
289
            }
30957 amit.gupta 290
 
31410 amit.gupta 291
            String message = "Duration from - " + FormattingUtils.formatDateMonth(scheme.getStartDateTime()) + " - " + FormattingUtils.formatDateMonth(scheme.getEndDateTime());
292
            sendNotificationModel.setCampaignName("activationscheme");
293
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/scheme/" + scheme.getId());
294
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
295
            sendNotificationModel.setMessage(message);
296
            sendNotificationModel.setTitle(String.format(titleTemplate, schemeString, FormattingUtils.formatDecimal(scheme.getAmount()), org.apache.commons.lang3.StringUtils.abbreviate(String.join(", ", itemDescriptions), 25)));
297
            sendNotificationModel.setType("url");
298
            sendNotificationModel.setMessageType(MessageType.scheme);
299
            notificationService.sendNotificationToAll(sendNotificationModel);
300
        }
301
    }
23444 amit.gupta 302
 
31410 amit.gupta 303
    @Override
304
    public void expireSchemeById(int schemeId, LocalDateTime expiryTime) throws ProfitMandiBusinessException {
305
        Scheme scheme = schemeRepository.selectById(schemeId);
306
        if (scheme == null || scheme.getActiveTimestamp() == null) {
307
            throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
308
                    "SCHM_1007");
309
        }
310
        if (scheme.getExpireTimestamp() != null) {
311
            throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
312
                    "SCHM_1008");
313
        }
314
        scheme.setExpireTimestamp(LocalDateTime.now());
315
        if (expiryTime.isAfter(scheme.getEndDateTime())) {
316
            throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
317
                    "End Date cant be extended during expiry");
318
        }
319
        scheme.setEndDateTime(expiryTime);
320
        schemeRepository.persist(scheme);
321
    }
23444 amit.gupta 322
 
31410 amit.gupta 323
    private Map<Integer, Scheme> toSchemeIdSchemeMap(List<Scheme> schemes) {
324
        Map<Integer, Scheme> schemeIdSchemeMap = new HashMap<>();
325
        for (Scheme scheme : schemes) {
326
            schemeIdSchemeMap.put(scheme.getId(), scheme);
327
        }
328
        return schemeIdSchemeMap;
329
    }
23444 amit.gupta 330
 
31410 amit.gupta 331
    private Map<Integer, Set<Scheme>> toCatalogIdSchemesMap(List<SchemeItem> schemeItems, List<Scheme> schemes) {
332
        Map<Integer, Scheme> schemesMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
333
        Map<Integer, Set<Scheme>> catalogSchemesMap = new HashMap<>();
334
        for (SchemeItem schemeItem : schemeItems) {
335
            if (!catalogSchemesMap.containsKey(schemeItem.getCatalogId())) {
336
                catalogSchemesMap.put(schemeItem.getCatalogId(), new HashSet<>());
337
            }
338
            Set<Scheme> schemesSet = catalogSchemesMap.get(schemeItem.getCatalogId());
339
            schemesSet.add(schemesMap.get(schemeItem.getSchemeId()));
340
        }
341
        return catalogSchemesMap;
342
    }
23444 amit.gupta 343
 
31410 amit.gupta 344
    private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
345
                                                                      List<InventoryItem> inventoryItems) {
346
        Set<Integer> schemeIds = schemes.stream().map(x -> x.getId()).collect(Collectors.toSet());
347
        Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
348
        Set<Integer> catalogIds = itemRepository.selectByIds(itemIds).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
349
        List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndCatalogIds(schemeIds, catalogIds);
23444 amit.gupta 350
 
31410 amit.gupta 351
        Map<Integer, Set<Scheme>> catalogIdSchemesMap = this.toCatalogIdSchemesMap(schemeItems, schemes);
352
        Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = new HashMap<>();
353
        for (InventoryItem inventoryItem : inventoryItems) {
354
            LOGGER.info("inventoryItem {}", inventoryItem);
355
            LOGGER.info("inventoryItem.getItem() {}", inventoryItem.getItem());
356
            LOGGER.info("catalogIdSchemesMap {}", catalogIdSchemesMap);
357
            if (catalogIdSchemesMap.containsKey(inventoryItem.getItem().getCatalogItemId())) {
358
                inventoryItemSchemesMap.put(inventoryItem, catalogIdSchemesMap.get(inventoryItem.getItem().getCatalogItemId()));
359
            }
360
        }
361
        return inventoryItemSchemesMap;
362
    }
31170 amit.gupta 363
 
31410 amit.gupta 364
    @Override
365
    public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
366
        LOGGER.info("Trying to process SchemeIn with purchaseId [{}] and retailerId [{}]", purchaseId, retailerId);
367
        Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
368
        // TODO - SCHEME
369
        PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
370
                YearMonth.from(purchase.getCreateTimestamp()));
371
        // PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
372
        // purchase.getCreateTimestamp().toLocalDate());
23444 amit.gupta 373
 
31410 amit.gupta 374
        List<Scheme> schemes = schemeRepository.selectActiveAll(Arrays.asList(SchemeType.IN), partnerType,
375
                purchase.getCreateTimestamp().toLocalDate(), false);
376
        List<Integer> validSchemeIds = schemeRepository.selectSchemesByRetailerIdsSchemeIds(retailerId, schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
377
        schemes = schemes.stream().filter(x -> validSchemeIds.contains(x.getId())).collect(Collectors.toList());
378
        float totalCashback = 0;
23444 amit.gupta 379
 
31410 amit.gupta 380
        if (schemes.isEmpty()) {
381
            return;
382
        }
383
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
384
        //Remove imeis from blocked imeis list
385
        inventoryItems = inventoryItems.stream().filter(inventoryItem -> !BLOCKED_IMEIS.contains(inventoryItem.getSerialNumber())).collect(Collectors.toList());
386
        if (inventoryItems.size() == 0) return;
387
        Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
388
        Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
389
        inventoryItems.stream().forEach(x -> x.setItem(itemsMap.get(x.getItemId())));
23444 amit.gupta 390
 
31410 amit.gupta 391
        LocalDateTime billingDate = purchaseService.getBillingDateOfPurchase(purchaseId);
392
        Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
393
                .filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(billingDate)).map(x -> x.getItemId())
394
                .collect(Collectors.toSet());
395
        // Only consider inventory items that were not returned
396
        inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
397
                .filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD))
398
                .filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
399
        LOGGER.info(inventoryItems);
400
        if (inventoryItems.size() == 0)
401
            return;
402
        Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = this.toInventoryItemSchemesMap(schemes,
403
                inventoryItems);
23444 amit.gupta 404
 
31410 amit.gupta 405
        if (inventoryItemSchemesMap.isEmpty()) {
406
            return;
407
        }
408
        Map<InventoryItem, Set<Scheme>> allInventoryItemSchemesMap = new HashMap<>();
23444 amit.gupta 409
 
31410 amit.gupta 410
        for (Map.Entry<InventoryItem, Set<Scheme>> inventoryItemSchemesEntry : inventoryItemSchemesMap.entrySet()) {
411
            Set<Scheme> allSchemes = new HashSet<>();
412
            for (Scheme scheme : inventoryItemSchemesEntry.getValue()) {
413
                allSchemes.add(scheme);
414
            }
415
            allInventoryItemSchemesMap.put(inventoryItemSchemesEntry.getKey(), allSchemes);
416
        }
29927 amit.gupta 417
 
31410 amit.gupta 418
        //
23444 amit.gupta 419
 
31410 amit.gupta 420
        int itemsCount = 0;
421
        for (Map.Entry<InventoryItem, Set<Scheme>> allInventoryItemSchemesEntry : allInventoryItemSchemesMap
422
                .entrySet()) {
423
            float inventoryItemCashback = 0;
424
            for (Scheme scheme : allInventoryItemSchemesEntry.getValue()) {
425
                InventoryItem inventoryItem = allInventoryItemSchemesEntry.getKey();
31588 amit.gupta 426
                float cashback = this.createSchemeInOut(scheme, inventoryItem, partnerType);
31410 amit.gupta 427
                inventoryItemCashback += cashback;
428
            }
429
            if (inventoryItemCashback > 0) {
430
                totalCashback += inventoryItemCashback;
431
                itemsCount++;
432
            }
433
        }
23444 amit.gupta 434
 
31410 amit.gupta 435
        LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
436
        if (itemsCount > 0) {
437
            walletService.addAmountToWallet(
438
                    retailerId, purchaseId, WalletReferenceType.SCHEME_IN, "Added for SCHEME IN against invoice "
439
                            + purchase.getPurchaseReference() + " (total " + itemsCount + " pcs)",
440
                    totalCashback, purchase.getCreateTimestamp());
441
            LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
442
                    purchase.getPurchaseReference(), itemsCount);
443
            purchase.setCashback(purchase.getCashback() + totalCashback);
444
            purchaseRepository.persist(purchase);
445
        }
446
    }
23444 amit.gupta 447
 
31410 amit.gupta 448
    private Scheme toScheme(int creatorId, CreateSchemeRequest createSchemeRequest) {
449
        Scheme scheme = new Scheme();
450
        scheme.setName(createSchemeRequest.getName());
451
        scheme.setDescription(createSchemeRequest.getDescription());
452
        scheme.setType(createSchemeRequest.getType());
453
        scheme.setAmountType(createSchemeRequest.getAmountType());
454
        scheme.setAmount(createSchemeRequest.getAmount());
455
        scheme.setPartnerType(createSchemeRequest.getPartnerType());
456
        scheme.setStartDateTime(createSchemeRequest.getStartDate());
457
        scheme.setEndDateTime(createSchemeRequest.getEndDate());
458
        scheme.setCreatedBy(creatorId);
459
        scheme.setCashback(createSchemeRequest.isCashback());
460
        return scheme;
461
    }
23444 amit.gupta 462
 
31588 amit.gupta 463
 
31410 amit.gupta 464
    //Only in and activation margins are allowed to be rolled out more than twice
31588 amit.gupta 465
    private float createSchemeInOut(Scheme scheme, InventoryItem inventoryItem, PartnerType partnerType) throws ProfitMandiBusinessException {
31410 amit.gupta 466
        LOGGER.info("Scheme === {}", scheme);
467
        if ((scheme.getId() == 411 || scheme.getId() == 612) && inventoryItem.getCreateTimestamp().isAfter(LocalDate.of(2021, 12, 1).atStartOfDay())) {
468
            return 0;
469
        }
470
        List<SchemeInOut> sios = schemeInOutRepository.selectAllByType(scheme.getType(), inventoryItem.getId());
471
        float actualCredit = 0;
472
        if (sios.stream().filter(x -> x.getRolledBackTimestamp() == null && x.getSchemeId() == scheme.getId())
473
                .collect(Collectors.toList()).size() == 0) {
474
            sios = sios.stream().filter(x -> x.getRolledBackTimestamp() == null).collect(Collectors.toList());
475
            //Rejected Scheme for types INVESTMENT and ACTIVATION are considered rolledback only if the item billing is cancelled.
476
            float amountCredited = (float) sios.stream().mapToDouble(e -> e.getAmount()).sum();
23444 amit.gupta 477
 
31410 amit.gupta 478
            LOGGER.info("SIOS ===== {}", sios);
479
            float amountToCredit = this.getAmount(inventoryItem, scheme);
480
            //Activation and in scheme
481
            if (!scheme.getType().equals(SchemeType.IN) && !scheme.getType().equals(SchemeType.ACTIVATION) &&
482
                    !scheme.getType().equals(SchemeType.SPECIAL_SUPPORT) && sios.size() > 0) {
23444 amit.gupta 483
 
31410 amit.gupta 484
                if (sios.size() > 1) {
485
                    LOGGER.info("SAMESCHEMETYPE has already been credited twice for inventoryItem - {}", inventoryItem.getId());
486
                    return 0;
487
                }
488
                if (amountToCredit > amountCredited + 1f) {
489
                    for (SchemeInOut sio : sios) {
490
                        sio.setRolledBackTimestamp(LocalDateTime.now());
491
                        sio.setStatus(SchemePayoutStatus.REJECTED);
492
                        sio.setStatusDescription("Partner Category upgraded to " + scheme.getPartnerType() + ", new entry for margin added");
493
                    }
494
                    actualCredit = amountToCredit - amountCredited;
495
                } else {
496
                    return 0;            //Rejected Scheme for types INVESTMENT and ACTIVATION are considered rolledback only if the item billing is cancelled.
23444 amit.gupta 497
 
31410 amit.gupta 498
                }
499
            } else {
500
                actualCredit = amountToCredit;
501
            }
502
            LOGGER.info("Actual Credit ==== {}", actualCredit);
22653 ashik.ali 503
 
31410 amit.gupta 504
            SchemeInOut schemeInOut = new SchemeInOut();
505
            schemeInOut.setSchemeId(scheme.getId());
506
            schemeInOut.setInventoryItemId(inventoryItem.getId());
507
            schemeInOut.setAmount(amountToCredit);
508
            schemeInOutRepository.persist(schemeInOut);
29927 amit.gupta 509
 
31410 amit.gupta 510
            if (scheme.getType().equals(SchemeType.ACTIVATION)) {
511
                schemeInOut.setStatus(SchemePayoutStatus.PENDING);
512
                schemeInOut.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
513
                return 0;
31588 amit.gupta 514
            } else if (scheme.getType().equals(SchemeType.INVESTMENT) && !PartnerType.BRONZE.equals(partnerType)) {
31410 amit.gupta 515
                schemeInOut.setStatus(SchemePayoutStatus.PENDING);
516
                schemeInOut.setStatusDescription("Subject to investment days maintained");
517
                return 0;
518
            } else {
519
                schemeInOut.setStatus(SchemePayoutStatus.CREDITED);
520
                schemeInOut.setCreditTimestamp(LocalDateTime.now());
521
                if (scheme.getType().equals(SchemeType.IN)) {
522
                    schemeInOut.setStatusDescription("Credited for GRN of IMEI#" + inventoryItem.getSerialNumber());
31588 amit.gupta 523
                } else if (SchemeType.INVESTMENT.equals(scheme.getType()) || SchemeService.OUT_SCHEME_TYPES.contains(scheme.getType())) {
31410 amit.gupta 524
                    schemeInOut.setStatusDescription("Credited for sale of IMEI#" + inventoryItem.getSerialNumber());
525
                }
526
            }
527
        }
528
        return actualCredit;
529
    }
29927 amit.gupta 530
 
31410 amit.gupta 531
    // We are maintaining price drop after grn
532
    private float getAmount(InventoryItem inventoryItem, Scheme scheme) throws ProfitMandiBusinessException {
533
        if (BLOCKED_IMEIS.contains(inventoryItem.getSerialNumber())) {
534
            return 0;
535
        }
536
        float amount = 0;
537
        float dpForCalc = 0;
538
        float taxableSellingPrice = 0;
29927 amit.gupta 539
 
31410 amit.gupta 540
        //float totalTaxRate = stateGstRateRepository.getTotalTaxRate(inventoryItem.getItemId());
541
        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
542
            if (scheme.getType().equals(SchemeType.IN)) {
543
                dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
544
            } else {
545
                try {
546
                    dpForCalc = Math.min(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount(),
547
                            tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice());
548
                } catch (Exception e) {
549
                    LOGGER.info("Could not find tag Listing entry in {}", inventoryItem.getItemId());
550
                    e.printStackTrace();
551
                }
552
            }
553
            //TODO:Should be calculated on unit price
554
            //taxableSellingPrice = dpForCalc / (1 + totalTaxRate / 100);
555
            //amount = taxableSellingPrice * scheme.getAmount() / 100;
556
            amount = dpForCalc * scheme.getAmount() / 100;
557
            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(),
558
                    inventoryItem.getSerialNumber(), inventoryItem.getItemId(), scheme.getId(), scheme.getName(),
559
                    scheme.getType(), scheme.getAmountType(), scheme.getPartnerType(), dpForCalc, taxableSellingPrice,
560
                    scheme.getAmount(), amount));
561
        } else if (scheme.getType().equals(SchemeType.IN)) {
562
            amount = scheme.getAmount();
563
        }
564
        return amount;
565
    }
23444 amit.gupta 566
 
31410 amit.gupta 567
    @Override
568
    public float processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
569
        float totalCashback = 0;
570
        FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
571
        // Process only if order is not cancelled
572
        if (fofoOrder.getCancelledTimestamp() == null) {
573
            // PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
574
            // fofoOrder.getCreateTimestamp().toLocalDate());
575
            // TODO - SCHEME
576
            PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
577
                    YearMonth.from(fofoOrder.getCreateTimestamp()));
29927 amit.gupta 578
 
31410 amit.gupta 579
            List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
580
            if (scanRecords.size() == 0) return 0;
581
            Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
582
                    .collect(Collectors.toSet());
583
            LOGGER.info("fofoOrderId --- {}", fofoOrderId);
584
            LOGGER.info("scanRecords --- {}", scanRecords);
585
            LOGGER.info("inventoryItemIds --- {}", inventoryItemIds);
586
            Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
587
                    .filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
588
                    .collect(Collectors.toSet());
589
            inventoryItems = inventoryItems.stream().filter(inventoryItem -> !BLOCKED_IMEIS.contains(inventoryItem.getSerialNumber())).collect(Collectors.toSet());
590
            if (inventoryItems.size() == 0) {
591
                return 0;
592
            }
593
            Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
29927 amit.gupta 594
 
31410 amit.gupta 595
            // Remove Items that are eol now.
596
            Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
597
                    .filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(fofoOrder.getCreateTimestamp()))
598
                    .map(x -> x.getItemId()).collect(Collectors.toSet());
599
            // Only consider inventory items that were not returned
600
            //ItemCriteria itemCriteria = new ItemCriteria();
601
            //itemCriteria.setItemIds(new ArrayList<>(itemIdsSet));
602
            //List<Integer> catalogIds = itemRepository.getCatalogIds(itemCriteria);
603
            inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
604
                    .collect(Collectors.toSet());
29927 amit.gupta 605
 
31410 amit.gupta 606
            if (inventoryItems.size() == 0) {
607
                return 0;
608
            }
23444 amit.gupta 609
 
31410 amit.gupta 610
            int count = 0;
23444 amit.gupta 611
 
31410 amit.gupta 612
            List<SchemeType> allOutSchemeTypes = new ArrayList<>();
613
            allOutSchemeTypes.addAll(Arrays.asList(SchemeType.ACTIVATION, SchemeType.INVESTMENT, SchemeType.SPECIAL_SUPPORT, SchemeType.SELLOUT));
614
            allOutSchemeTypes.addAll(OUT_SCHEME_TYPES);
615
            List<Scheme> allActiveSchemes = schemeRepository.selectActiveAll(allOutSchemeTypes, partnerType,
616
                    fofoOrder.getCreateTimestamp().toLocalDate(), false);
617
            List<Integer> validSchemeIds = schemeRepository.selectSchemesByRetailerIdsSchemeIds(retailerId, allActiveSchemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
618
            allActiveSchemes = allActiveSchemes.stream().filter(x -> validSchemeIds.contains(x.getId())).collect(Collectors.toList());
619
            for (InventoryItem inventoryItem : inventoryItems) {
620
                float itemCashback = 0;
621
                Set<Integer> schemeIds = new HashSet<>(
622
                        schemeItemRepository.selectSchemeIdByCatalogId(inventoryItem.getItem().getCatalogItemId()));
623
                List<Scheme> itemActiveSchemes = allActiveSchemes.stream().filter(x -> schemeIds.contains(x.getId()))
624
                        .collect(Collectors.toList());
625
                List<Scheme> supportSchemes = itemActiveSchemes.stream().filter(x -> Arrays.asList(SchemeType.SPECIAL_SUPPORT, SchemeType.ACTIVATION, SchemeType.SELLOUT).contains(x.getType())).collect(Collectors.toList());
626
                itemActiveSchemes = itemActiveSchemes.stream().filter(x -> !Arrays.asList(SchemeType.SPECIAL_SUPPORT, SchemeType.ACTIVATION, SchemeType.SELLOUT).contains(x.getType())).collect(Collectors.toList());
627
                for (Scheme scheme : itemActiveSchemes) {
628
                    LOGGER.info("Scheme ==== {}", scheme);
31588 amit.gupta 629
                    itemCashback += this.createSchemeInOut(scheme, inventoryItem, partnerType);
31410 amit.gupta 630
                }
631
                if (supportSchemes.size() > 0) {
632
                    this.processSpecialSupport(fofoOrder, supportSchemes, inventoryItem, partnerType, fofoOrder.getCreateTimestamp());
633
                }
634
                LOGGER.info("itemCashback ==== {}", itemCashback);
635
                if (itemCashback > 0) {
636
                    count++;
637
                    totalCashback += itemCashback;
638
                }
639
            }
640
            if (count > 0) {
641
                walletService.addAmountToWallet(
642
                        retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT, "Sales margin for invoice number "
643
                                + fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
644
                        totalCashback, fofoOrder.getCreateTimestamp());
645
                fofoOrder.setCashback(totalCashback + fofoOrder.getCashback());
646
            }
647
        }
648
        return totalCashback;
649
    }
22653 ashik.ali 650
 
31410 amit.gupta 651
    @Override
652
    //Tax rate has been passed to 0 to ensure no tax deduction
653
    public float getSpecialSupportAmount(float supportAmount, PartnerType partnerType, LocalDate onDate,
654
                                         int catalogId) throws ProfitMandiBusinessException {
655
        //int itemId = itemRepository.selectAllByCatalogItemId(catalogId).stream().findAny().get().getId();
656
        //float totalTaxRate = stateGstRateRepository.getTotalTaxRate(itemId);
657
        return this.getSpecialSupportAmount(supportAmount, partnerType, onDate, catalogId, 0);
658
    }
23444 amit.gupta 659
 
31410 amit.gupta 660
    @Override
661
    public float getSpecialSupportAmount(float supportAmount, PartnerType partnerType, LocalDate onDate,
662
                                         int catalogId, float taxRate) throws ProfitMandiBusinessException {
663
        float totalMargin = this.selectPercentageScheme(partnerType, onDate, catalogId, false, 0, 0).stream().collect(Collectors.summingDouble(x -> x.getAmount())).floatValue();
664
        float amountToCredit = supportAmount * (1 - (totalMargin / (100 + taxRate)));
665
        return amountToCredit;
666
    }
23444 amit.gupta 667
 
31410 amit.gupta 668
    private void processSpecialSupport(FofoOrder fofoOrder, List<Scheme> supportSchemes, InventoryItem
669
            inventoryItem, PartnerType partnerType, LocalDateTime saleDate) throws ProfitMandiBusinessException {
670
        int catalogId = inventoryItem.getItem().getCatalogItemId();
671
        float totalMargin = this.selectPercentageScheme(partnerType, saleDate.toLocalDate(), catalogId, false, 0, 0).stream().collect(Collectors.summingDouble(x -> x.getAmount())).floatValue();
672
        LOGGER.info("total percentage margin - {}", totalMargin);
673
        for (Scheme scheme : supportSchemes) {
674
            float amountToCredit = scheme.getAmount() * (1 - (totalMargin / 100));
675
            List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(scheme.getId(), inventoryItem.getId());
676
            SchemeInOut schemeInOut = schemeInOuts.stream().filter(x -> x.getRolledBackTimestamp() == null).findFirst().orElse(null);
677
            if (schemeInOut == null) {
678
                schemeInOut = new SchemeInOut();
679
                schemeInOut.setSchemeId(scheme.getId());
680
                schemeInOut.setInventoryItemId(inventoryItem.getId());
681
                schemeInOut.setCreateTimestamp(LocalDateTime.now());
682
                if (SchemeType.SELLOUT.equals(scheme.getType())) {
683
                    schemeInOut.setStatus(SchemePayoutStatus.CREDITED);
684
                    schemeInOut.setCreditTimestamp(LocalDateTime.now());
685
                    schemeInOut.setStatusDescription("Modelwise sellout support credited");
686
                    walletService.addAmountToWallet(inventoryItem.getFofoId(), fofoOrder.getId(), WalletReferenceType.SPECIAL_SUPPORT,
687
                            "Modelwise sellout support credited for Imei - " + inventoryItem.getSerialNumber(), amountToCredit,
688
                            fofoOrder.getCreateTimestamp());
689
                } else {
690
                    schemeInOut.setStatusDescription("Special support, Activation pending for IMEI#" + inventoryItem.getSerialNumber());
691
                    schemeInOut.setStatus(SchemePayoutStatus.PENDING);
692
                }
693
                schemeInOut.setAmount(amountToCredit);
694
                schemeInOutRepository.persist(schemeInOut);
29231 amit.gupta 695
 
31410 amit.gupta 696
            } else if (Double.valueOf(schemeInOut.getAmount()).intValue() != Double.valueOf(amountToCredit).intValue()) {
697
                SchemeInOut schemeInOutNew = new SchemeInOut();
698
                schemeInOutNew.setInventoryItemId(inventoryItem.getId());
699
                schemeInOutNew.setSchemeId(scheme.getId());
700
                schemeInOutNew.setCreateTimestamp(LocalDateTime.now());
701
                schemeInOutNew.setAmount(amountToCredit);
702
                if (schemeInOut.getStatus().equals(SchemePayoutStatus.PENDING)) {
703
                    schemeInOutNew.setStatus(SchemePayoutStatus.PENDING);
704
                    schemeInOutNew.setStatusDescription("Special support, Activation pending for IMEI#" + inventoryItem.getSerialNumber());
705
                    schemeInOutRepository.persist(schemeInOutNew);
706
                } else if (schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
707
                    schemeInOutNew.setStatus(SchemePayoutStatus.CREDITED);
708
                    schemeInOutNew.setCreditTimestamp(LocalDateTime.now());
709
                    schemeInOutNew.setStatusDescription("Special support credited");
710
                    schemeInOutRepository.persist(schemeInOutNew);
711
                    walletService.addAmountToWallet(inventoryItem.getFofoId(), fofoOrder.getId(), WalletReferenceType.SPECIAL_SUPPORT,
712
                            "Special support adjusted against overall margin gains for Imei - " + inventoryItem.getSerialNumber(), amountToCredit - schemeInOut.getAmount(),
713
                            fofoOrder.getCreateTimestamp());
31170 amit.gupta 714
 
31410 amit.gupta 715
                }
716
                schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
717
                schemeInOut.setStatusDescription("Failed!!, New Margin Entry added");
718
                schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
719
            }
30191 amit.gupta 720
 
31410 amit.gupta 721
        }
23444 amit.gupta 722
 
31410 amit.gupta 723
    }
23444 amit.gupta 724
 
31410 amit.gupta 725
    @Override
726
    public void rollbackSchemes(List<Integer> inventoryItemIds, int rollbackReference, String rollbackReason)
727
            throws Exception {
728
        Set<Integer> inventoryItemIdSet = new HashSet<>(inventoryItemIds);
729
        float amountToRollback = 0;
730
        List<SchemeInOut> schemes = schemeInOutRepository.selectByInventoryItemIds(inventoryItemIdSet);
731
        for (SchemeInOut schemeInOut : schemes) {
732
            if (schemeInOut.getRolledBackTimestamp() == null) {
733
                schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
734
                if (schemeInOut.getStatus() == null || schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
735
                    amountToRollback += schemeInOut.getAmount();
736
                }
737
                schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
738
                schemeInOut.setStatusDescription(rollbackReason);
739
            }
740
        }
741
        if (amountToRollback > 0) {
742
            int inventoryItemId = inventoryItemIds.get(0);
743
            InventoryItem ii = inventoryItemRepository.selectById(inventoryItemId);
744
            Integer fofoId = ii.getFofoId();
745
            // Purchase p = purchaseRepository.selectById(ii.getPurchaseId());
746
            // TODO//
747
            walletService.rollbackAmountFromWallet(fofoId, amountToRollback, ii.getPurchaseId(),
748
                    WalletReferenceType.SCHEME_IN, rollbackReason, LocalDateTime.now());
749
        }
750
    }
23444 amit.gupta 751
 
31410 amit.gupta 752
    @Override
753
    public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
754
            throws ProfitMandiBusinessException {
755
        Map<String, Object> map = new HashMap<>();
756
        List<Scheme> schemes = null;
757
        long size = 0;
758
        if (roleManager.isAdmin(roleIds)) {
759
            schemes = schemeRepository.selectAll(offset, limit);
760
            size = schemeRepository.selectAllCount();
761
        } else {
762
            schemes = schemeRepository.selectActiveAll(offset, limit);
763
            size = schemeRepository.selectAllActiveCount();
764
        }
765
        map.put("schemes", schemes);
766
        map.put("start", offset + 1);
767
        map.put("size", size);
768
        if (schemes.size() < limit) {
769
            map.put("end", offset + schemes.size());
770
        } else {
771
            map.put("end", offset + limit);
772
        }
773
        return map;
774
    }
26722 amit.gupta 775
 
31410 amit.gupta 776
    @Override
777
    public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
778
            throws ProfitMandiBusinessException {
779
        LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
780
        List<Scheme> schemes = null;
781
        if (roleManager.isAdmin(roleIds)) {
782
            schemes = schemeRepository.selectAll(offset, limit);
783
        } else {
784
            schemes = schemeRepository.selectActiveAll(offset, limit);
785
        }
786
        return schemes;
787
    }
27898 amit.gupta 788
 
31410 amit.gupta 789
    @Override
790
    // This is being called to reverse schemes while processing price Drop
791
    public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
792
            throws ProfitMandiBusinessException {
793
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
794
        Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
795
                .collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
29927 amit.gupta 796
 
31410 amit.gupta 797
        for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
798
            float amountToCredit = 0;
799
            float amountToDebit = 0;
800
            int purchaseId = purchaseEntry.getKey();
801
            List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
30454 amit.gupta 802
 
31410 amit.gupta 803
            Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
804
                    .collect(Collectors.toMap(x -> x.getId(), x -> x));
29927 amit.gupta 805
 
31410 amit.gupta 806
            List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
807
            LOGGER.info("Scheme InOuts , {}", schemeInOuts);
808
            if (schemeInOuts.size() == 0) {
809
                continue;
810
            }
811
            List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
812
            Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
813
                    .stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
814
            for (SchemeInOut schemeInOut : schemeInOuts) {
815
                InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
816
                Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
817
                if (scheme.getAmountType().equals(AmountType.FIXED)) {
818
                    continue;
819
                }
820
                if (scheme.getType().equals(SchemeType.IN) && schemeInOut.getRolledBackTimestamp() == null) {
821
                    float newAmount = getAmount(ii, scheme);
822
                    if (Math.abs(schemeInOut.getAmount() - newAmount) >= 0.01f) {
823
                        schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
29231 amit.gupta 824
 
31410 amit.gupta 825
                        SchemeInOut sioNew = new SchemeInOut();
826
                        sioNew.setAmount(newAmount);
827
                        sioNew.setStatus(schemeInOut.getStatus());
828
                        sioNew.setStatusDescription(schemeInOut.getStatusDescription());
829
                        sioNew.setInventoryItemId(schemeInOut.getInventoryItemId());
830
                        sioNew.setSchemeId(schemeInOut.getSchemeId());
831
                        sioNew.setCreditTimestamp(LocalDateTime.now());
832
                        schemeInOutRepository.persist(sioNew);
30957 amit.gupta 833
 
31410 amit.gupta 834
                        schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
835
                        schemeInOut.setStatusDescription("Change in margins due to price drop");
836
                        // IF not credited then dont consider any credit/debit for that sio entry
837
                        if (schemeInOut.getCreditTimestamp() != null) {
838
                            amountToCredit += sioNew.getAmount();
839
                            amountToDebit += schemeInOut.getAmount();
840
                        }
841
                    }
29927 amit.gupta 842
 
31410 amit.gupta 843
                }
844
            }
845
            int fofoId = inventoryItems.get(0).getFofoId();
846
            if (amountToDebit > 0) {
847
                walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
848
                        MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), -amountToDebit,
849
                        priceDrop.getAffectedOn());
850
            }
851
            if (amountToCredit > 0) {
852
                walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
853
                        MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), amountToCredit,
854
                        priceDrop.getAffectedOn());
855
            }
856
        }
857
    }
29231 amit.gupta 858
 
31410 amit.gupta 859
    @Override
860
    // Always being called from cancel order/bad return means no SCHEME IN is considered
861
    public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
862
                               List<SchemeType> schemeTypes) throws ProfitMandiBusinessException {
863
        Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
864
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
865
        LOGGER.info("inventoryItems" + inventoryItems);
23444 amit.gupta 866
 
31410 amit.gupta 867
        Map<SchemeType, SchemeInOut> schemeTypeMap = new HashMap<>();
30454 amit.gupta 868
 
31410 amit.gupta 869
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
870
        LOGGER.info("schemeInOuts" + schemeInOuts);
871
        float amountToRollback = 0;
23444 amit.gupta 872
 
31410 amit.gupta 873
        if (!schemeInOuts.isEmpty()) {
874
            List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
875
            LOGGER.info("schemeIds" + schemeIds);
29231 amit.gupta 876
 
31410 amit.gupta 877
            Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
878
                    .stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
879
            for (SchemeInOut schemeInOut : schemeInOuts) {
880
                Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
881
                if (schemeTypes.contains(scheme.getType())) {
882
                    schemeTypeMap.put(scheme.getType(), schemeInOut);
883
                    if (schemeInOut.getRolledBackTimestamp() == null) {
884
                        schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
885
                        if (schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
886
                            amountToRollback += schemeInOut.getAmount();
887
                        }
888
                        schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
889
                        schemeInOut.setStatusDescription(reversalReason);
890
                    }
891
                }
892
            }
29231 amit.gupta 893
 
31410 amit.gupta 894
        }
895
        int fofoId = inventoryItems.get(0).getFofoId();
896
        WalletReferenceType walletReferenceType = schemeTypes.containsAll(SchemeService.OUT_SCHEME_TYPES)
897
                ? WalletReferenceType.SCHEME_OUT
898
                : (schemeTypes.contains(SchemeType.ACTIVATION) ? WalletReferenceType.ACTIVATION_SCHEME
899
                : (schemeTypes.contains(SchemeType.SPECIAL_SUPPORT)) ? WalletReferenceType.SPECIAL_SUPPORT : WalletReferenceType.INVESTMENT_PAYOUT);
900
        if (amountToRollback > 0) {
901
            // Mark appropriate reference of rollback investment margin
902
            if (schemeTypes.contains(SchemeType.INVESTMENT)) {
903
                reversalReference = Integer
904
                        .parseInt(FormattingUtils.getYearMonth(schemeTypeMap.get(SchemeType.INVESTMENT).getCreditTimestamp().minusMonths(1)));
905
            }
906
            walletService.rollbackAmountFromWallet(fofoId, amountToRollback, reversalReference, walletReferenceType,
907
                    reversalReason, LocalDateTime.now());
908
        }
909
    }
29231 amit.gupta 910
 
31410 amit.gupta 911
    @Override
912
    public double getTotalMargin(int itemId, PartnerType partnerType, LocalDateTime dateTime) {
913
        Session session = sessionFactory.getCurrentSession();
914
        CriteriaBuilder cb = session.getCriteriaBuilder();
915
        CriteriaQuery<Double> criteriaQuery = cb.createQuery(Double.class);
916
        Root<SchemeItem> schemeItem = criteriaQuery.from(SchemeItem.class);
917
        Root<Scheme> scheme = criteriaQuery.from(Scheme.class);
918
        Predicate schemePredicate = cb.equal(scheme.get(ProfitMandiConstants.AMOUNT_TYPE), AmountType.PERCENTAGE);
919
        Predicate lessThanPredicate = cb.lessThanOrEqualTo(scheme.get(ProfitMandiConstants.END_DATE_TIME), dateTime);
920
        Predicate greaterThanPredicate = cb.greaterThanOrEqualTo(scheme.get(ProfitMandiConstants.START_DATE_TIME),
921
                dateTime);
922
        Predicate joinPredicate = cb.equal(scheme.get("id"), schemeItem.get("schemeId"));
923
        Predicate schemeItemPredicate = cb.equal(schemeItem.get(ProfitMandiConstants.ITEM_ID), itemId);
924
        criteriaQuery.select(cb.sum(scheme.get(ProfitMandiConstants.AMOUNT))).where(schemePredicate, lessThanPredicate,
925
                greaterThanPredicate, schemeItemPredicate, joinPredicate);
29231 amit.gupta 926
 
31410 amit.gupta 927
        Query<Double> query = session.createQuery(criteriaQuery);
928
        return query.getSingleResult() + ProfitMandiConstants.SCHEME_INVESTMENT_MARGIN;
29231 amit.gupta 929
 
31410 amit.gupta 930
    }
23444 amit.gupta 931
 
31410 amit.gupta 932
    @Override
933
    @Cacheable(value = "itemSchemeCashback", cacheManager = "timeoutCacheManager")
934
    public Map<Integer, Float> getCatalogSchemeCashBack() {
935
        Map<Integer, Float> itemCashbackMap = new HashMap<>();
936
        Map<Integer, Scheme> cashbackSchemesMap = schemeRepository
31450 amit.gupta 937
                .selectActiveAll(Arrays.asList(SchemeType.ACTIVATION, SchemeType.SPECIAL_SUPPORT, SchemeType.SELLOUT), PartnerType.ALL, LocalDate.now(), false)
31410 amit.gupta 938
                .stream().filter(x -> x.getAmountType().equals(AmountType.FIXED))
939
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
940
        if (cashbackSchemesMap.size() > 0) {
941
            List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(cashbackSchemesMap.keySet());
942
            schemeItems.stream().forEach(x -> {
943
                float cashbackAmount = cashbackSchemesMap.get(x.getSchemeId()).getAmount();
944
                if (!itemCashbackMap.containsKey(x.getCatalogId())) {
945
                    itemCashbackMap.put(x.getCatalogId(), cashbackAmount);
946
                } else {
947
                    itemCashbackMap.put(x.getCatalogId(), itemCashbackMap.get(x.getCatalogId()) + cashbackAmount);
948
                }
949
            });
950
        }
951
        // A107FD Model needs to removed
952
        itemCashbackMap.remove(30211);
953
        itemCashbackMap.remove(30212);
954
        itemCashbackMap.remove(30213);
955
        itemCashbackMap.remove(30756);
956
        return itemCashbackMap;
957
    }
30572 amit.gupta 958
 
31410 amit.gupta 959
    @Override
960
    public List<Scheme> selectSchemeByPartnerTypeFofoId(PartnerType partnerType, LocalDate onDate, int catalogId, int fofoId, int offset, int limit) throws ProfitMandiBusinessException {
961
        Session session = sessionFactory.getCurrentSession();
962
        final TypedQuery<Scheme> typedQuery = session.createNamedQuery(
963
                "Scheme.selectSchemeByModelsPartnerTypeFofoId", Scheme.class);
964
        typedQuery.setParameter("catalogIds", Arrays.asList(catalogId));
965
        typedQuery.setParameter("fofoIds", Arrays.asList(fofoId, 0));
966
        typedQuery.setParameter("onDate", onDate.atStartOfDay());
967
        typedQuery.setParameter("partnerTypes", Arrays.asList(partnerType, partnerType.ALL));
968
        typedQuery.setFirstResult(offset);
969
        if (limit != 0) {
970
            typedQuery.setMaxResults(limit);
971
        }
972
        return typedQuery.getResultList();
973
    }
30463 amit.gupta 974
 
31410 amit.gupta 975
    @Override
976
    public List<Scheme> selectSchemeByPartnerType(PartnerType partnerType, LocalDate onDate, int catalogId,
977
                                                  boolean isAdmin, int offset, int limit) throws ProfitMandiBusinessException {
978
        Session session = sessionFactory.getCurrentSession();
979
        List<Predicate> andPredicates = new ArrayList<>();
980
        CriteriaBuilder cb = session.getCriteriaBuilder();
981
        CriteriaQuery<Scheme> query = cb.createQuery(Scheme.class);
982
        Root<Scheme> scheme = query.from(Scheme.class);
983
        if (!partnerType.equals(PartnerType.ALL)) {
984
            List<PartnerType> pt = new ArrayList<>();
985
            pt.add(PartnerType.ALL);
986
            pt.add(partnerType);
987
            andPredicates.add(cb.in(scheme.get("partnerType")).value(pt));
988
        }
989
        cb.desc(cb.isNull(scheme.get("expireTimestamp")));
990
        if (catalogId > 0) {
30454 amit.gupta 991
 
31410 amit.gupta 992
            List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByCatalogId(catalogId);
993
            LOGGER.info("schemeId" + schemeIds);
994
            if (schemeIds.isEmpty()) {
995
                return new ArrayList<>();
996
            }
997
            andPredicates.add(cb.in(scheme.get("id")).value(schemeIds));
998
            if (onDate != null) {
999
                andPredicates.add(cb.greaterThan(scheme.get("endDateTime"), onDate.atStartOfDay()));
1000
                andPredicates.add(cb.lessThanOrEqualTo(scheme.get("startDateTime"), onDate.atStartOfDay()));
1001
            }
1002
        }
1003
        if (!isAdmin) {
1004
            andPredicates.add(cb.isNotNull(scheme.get("activeTimestamp")));
1005
        }
1006
        query.where(cb.and(andPredicates.toArray(new Predicate[0])));
1007
        query.orderBy(cb.desc(cb.function("isnull", Boolean.class, scheme.get("expireTimestamp"))));
1008
        if (limit == 0) {
1009
            return session.createQuery(query).setFirstResult(offset).getResultList();
1010
        }
1011
        return session.createQuery(query).setFirstResult(offset).setMaxResults(limit).getResultList();
30454 amit.gupta 1012
 
31410 amit.gupta 1013
    }
30454 amit.gupta 1014
 
31410 amit.gupta 1015
    @Override
1016
    public List<Scheme> selectPercentageScheme(PartnerType partnerType, LocalDate onDate, int catalogId,
1017
                                               boolean isAdmin, int offset, int limit) throws ProfitMandiBusinessException {
1018
        List<Scheme> schemes = this.selectSchemeByPartnerType(partnerType, onDate, catalogId, isAdmin, offset, limit);
1019
        return schemes.stream().filter(x -> x.getAmountType().equals(AmountType.PERCENTAGE)).collect(Collectors.toList());
1020
    }
30454 amit.gupta 1021
 
31410 amit.gupta 1022
    @Override
1023
    public void processActivation() throws ProfitMandiBusinessException {
1024
        List<SchemeInOut> pendingPayouts = schemeInOutRepository.selectAllPending();
1025
        List<Integer> schemeIds = new ArrayList<>();
1026
        Set<Integer> inventoryIds = new HashSet<>();
1027
        for (SchemeInOut pendingPayout : pendingPayouts) {
1028
            schemeIds.add(pendingPayout.getSchemeId());
1029
        }
1030
        Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, 0).stream()
1031
                .filter(x -> x.getType().equals(SchemeType.ACTIVATION) || x.getType().equals(SchemeType.SPECIAL_SUPPORT))
1032
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
1033
        pendingPayouts = pendingPayouts.stream().filter(x -> schemesMap.get(x.getSchemeId()) != null)
1034
                .collect(Collectors.toList());
23884 amit.gupta 1035
 
31410 amit.gupta 1036
        for (SchemeInOut pendingPayout : pendingPayouts) {
1037
            inventoryIds.add(pendingPayout.getInventoryItemId());
1038
        }
1039
        Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryIds).stream()
1040
                .collect(Collectors.toMap(x -> x.getId(), x -> x));
1041
        Map<String, InventoryItem> serialNumberMap = inventoryItemMap.values().stream()
1042
                .collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
23796 amit.gupta 1043
 
31410 amit.gupta 1044
        List<ActivatedImei> activatedImeis = activatedImeiRepository
1045
                .selectBySerialNumbers(new ArrayList<>(serialNumberMap.keySet())).stream().collect(Collectors.toList());
23508 amit.gupta 1046
 
31410 amit.gupta 1047
        Map<String, ActivatedImei> activatedImeiMap = activatedImeis.stream()
1048
                .collect(Collectors.toMap(x -> x.getSerialNumber().toLowerCase(), x -> x));
1049
        for (SchemeInOut pendingPayout : pendingPayouts) {
1050
            InventoryItem ii = inventoryItemMap.get(pendingPayout.getInventoryItemId());
1051
            String serialNumber = ii.getSerialNumber().toLowerCase();
1052
            ActivatedImei activatedImei = activatedImeiMap.get(serialNumber);
1053
            if (activatedImei == null) {
1054
                continue;
1055
            }
1056
            Scheme scheme = schemesMap.get(pendingPayout.getSchemeId());
1057
            if (scheme.isWithinRange(activatedImei.getActivationTimestamp())) {
1058
                int fofoId = ii.getFofoId();
1059
                // Get latest order Id
1060
                int orderId = scanRecordRepository.selectByInventoryItemId(ii.getId()).stream()
1061
                        .filter(x -> x.getOrderId() > 0)
1062
                        .sorted(Comparator.comparing(ScanRecord::getCreateTimestamp).reversed()).findFirst().get()
1063
                        .getOrderId();
1064
                FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
1065
                if (scheme.getType().equals(SchemeType.ACTIVATION)) {
1066
                    walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.ACTIVATION_SCHEME,
1067
                            "Activation margin for " + ii.getItem().getItemDescriptionNoColor() + ", Imei - " + serialNumber, pendingPayout.getAmount(),
1068
                            fofoOrder.getCreateTimestamp());
1069
                    pendingPayout.setStatusDescription("Activation margin credited, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
1070
                } else {
1071
                    walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.SPECIAL_SUPPORT,
1072
                            "Special Support for " + ii.getItem().getItemDescriptionNoColor() + ", Imei - " + serialNumber, pendingPayout.getAmount(),
1073
                            fofoOrder.getCreateTimestamp());
1074
                    pendingPayout.setStatusDescription("Special support credited, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
1075
                }
1076
                pendingPayout.setCreditTimestamp(LocalDateTime.now());
1077
                pendingPayout.setStatus(SchemePayoutStatus.CREDITED);
1078
            } else {
1079
                pendingPayout.setStatus(SchemePayoutStatus.REJECTED);
1080
                pendingPayout.setRolledBackTimestamp(LocalDateTime.now());
1081
                ;
1082
                pendingPayout.setStatusDescription(
1083
                        "Rejected, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
1084
            }
1085
        }
1086
    }
24976 amit.gupta 1087
 
31410 amit.gupta 1088
    @Override
1089
    public void processActivatedImeisForSchemes() throws ProfitMandiBusinessException {
1090
        List<SchemesImeisModel> schemesImeisModels = schemeRepository.selectSelectUnpaidSchemes();
1091
        LOGGER.info("Total Size - " + schemesImeisModels.size());
1092
        List<Integer> orderIds = schemesImeisModels.stream().map(x -> x.getOrderId()).collect(Collectors.toList());
1093
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectAllByOrderIds(orderIds);
1094
        Map<Integer, FofoOrder> validOrdersMap = fofoOrders.stream().filter(x -> x.getCancelledTimestamp() == null).collect(Collectors.toMap(x -> x.getId(), x -> x));
1095
        Map<String, List<SchemesImeisModel>> validImeiSchemesModelMap = schemesImeisModels.stream().filter(x -> validOrdersMap.containsKey(x.getOrderId())).collect(Collectors.groupingBy(x -> x.getImei()));
1096
        for (Map.Entry<String, List<SchemesImeisModel>> imeiListEntry : validImeiSchemesModelMap.entrySet()) {
1097
            SchemesImeisModel schemesImeisModel = imeiListEntry.getValue().get(0);
1098
            List<Integer> schemeIds = imeiListEntry.getValue().stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
1099
            LOGGER.info("Serial Number  - {}, Scheme IDs - {}", schemesImeisModel.getImei(), schemeIds);
1100
            InventoryItem inventoryItem = inventoryItemRepository.selectById(schemesImeisModel.getInventoryItemId());
1101
            List<Scheme> schemes = schemeRepository.selectBySchemeIds(schemeIds);
1102
            List<Scheme> supportSchemes = schemes.stream().filter(x -> Arrays.asList(SchemeType.SPECIAL_SUPPORT, SchemeType.ACTIVATION).contains(x.getType())).collect(Collectors.toList());
1103
            if (supportSchemes.size() > 0) {
1104
                FofoOrder fofoOrder = validOrdersMap.get(schemesImeisModel.getOrderId());
1105
                PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(fofoOrder.getFofoId(),
1106
                        YearMonth.from(fofoOrder.getCreateTimestamp()));
1107
                this.processSpecialSupport(fofoOrder, supportSchemes, inventoryItem, partnerType, fofoOrder.getCreateTimestamp());
1108
            }
24976 amit.gupta 1109
 
31410 amit.gupta 1110
        }
24976 amit.gupta 1111
 
31410 amit.gupta 1112
    }
27898 amit.gupta 1113
 
22653 ashik.ali 1114
}