Subversion Repositories SmartDukaan

Rev

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