Subversion Repositories SmartDukaan

Rev

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