| 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;
|
| 34221 |
tejus.loha |
13 |
import com.spice.profitmandi.dao.entity.catalog.*;
|
| 29927 |
amit.gupta |
14 |
import com.spice.profitmandi.dao.entity.fofo.*;
|
| 31903 |
amit.gupta |
15 |
import com.spice.profitmandi.dao.entity.inventory.PartnerAgeingModel;
|
| 34709 |
amit.gupta |
16 |
import com.spice.profitmandi.dao.entity.transaction.Loan;
|
| 26498 |
amit.gupta |
17 |
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
|
| 32060 |
amit.gupta |
18 |
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
|
| 31609 |
amit.gupta |
19 |
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
|
| 23527 |
ashik.ali |
20 |
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
|
| 22653 |
ashik.ali |
21 |
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
|
| 34317 |
amit.gupta |
22 |
import com.spice.profitmandi.dao.enumuration.catalog.StockTransactionType;
|
| 34504 |
amit.gupta |
23 |
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
|
| 27377 |
amit.gupta |
24 |
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
|
| 31903 |
amit.gupta |
25 |
import com.spice.profitmandi.dao.model.AmountModel;
|
| 25503 |
amit.gupta |
26 |
import com.spice.profitmandi.dao.model.CreateSchemeRequest;
|
| 31170 |
amit.gupta |
27 |
import com.spice.profitmandi.dao.repository.catalog.*;
|
| 32309 |
amit.gupta |
28 |
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
|
| 23968 |
amit.gupta |
29 |
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
|
| 29927 |
amit.gupta |
30 |
import com.spice.profitmandi.dao.repository.fofo.*;
|
| 34709 |
amit.gupta |
31 |
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
|
| 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;
|
| 34504 |
amit.gupta |
35 |
import com.spice.profitmandi.dao.repository.warehouse.AgeingSummaryModel;
|
| 33087 |
amit.gupta |
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;
|
| 34504 |
amit.gupta |
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));
|
| 34709 |
amit.gupta |
74 |
private static final List<SchemeType> FULL_DAYS_CD_SCHEME_TYPES = Arrays.asList(SchemeType.CASH_DISCOUNT, SchemeType.CASH_DISCOUNT1);
|
|
|
75 |
private static final List<SchemeType> HALF_DAYS_CD_REJECT_SCHEME_TYPES = Arrays.asList(SchemeType.CASH_DISCOUNT1);
|
| 34017 |
amit.gupta |
76 |
|
| 34709 |
amit.gupta |
77 |
|
| 34317 |
amit.gupta |
78 |
private static final List<SchemeType> ACTIVATION_SCHEME_TYPES = Arrays.asList(SchemeType.SPECIAL_SUPPORT, SchemeType.SELLOUT);
|
| 35060 |
amit |
79 |
private static final List<SchemeType> NOFITY_SCHEME_TYPES = Arrays.asList(SchemeType.SPECIAL_SUPPORT, SchemeType.SELLOUT, SchemeType.SELLIN);
|
| 33600 |
ranu |
80 |
|
| 31410 |
amit.gupta |
81 |
@Autowired
|
| 34221 |
tejus.loha |
82 |
SchemeBlockedImeiRepository schemeBlockedImeiRepository;
|
|
|
83 |
@Autowired
|
| 31410 |
amit.gupta |
84 |
StateGstRateRepository stateGstRateRepository;
|
|
|
85 |
@Autowired
|
|
|
86 |
NotificationService notificationService;
|
|
|
87 |
@Autowired
|
|
|
88 |
@Qualifier("fofoInventoryItemRepository")
|
|
|
89 |
private InventoryItemRepository inventoryItemRepository;
|
|
|
90 |
@Autowired
|
|
|
91 |
private ActivatedImeiRepository activatedImeiRepository;
|
|
|
92 |
@Autowired
|
|
|
93 |
private PartnerTypeChangeService partnerTypeChangeService;
|
|
|
94 |
@Autowired
|
|
|
95 |
private PurchaseService purchaseService;
|
|
|
96 |
@Autowired
|
|
|
97 |
private ScanRecordRepository scanRecordRepository;
|
|
|
98 |
@Autowired
|
|
|
99 |
private SessionFactory sessionFactory;
|
|
|
100 |
@Autowired
|
|
|
101 |
private SchemeRepository schemeRepository;
|
|
|
102 |
@Autowired
|
|
|
103 |
private PriceDropRepository priceDropRepository;
|
|
|
104 |
@Autowired
|
|
|
105 |
private RoleManager roleManager;
|
|
|
106 |
@Autowired
|
|
|
107 |
private RetailerRepository retailerRepository;
|
|
|
108 |
@Autowired
|
|
|
109 |
private ReporticoService reporticoService;
|
|
|
110 |
@Autowired
|
|
|
111 |
private TagListingRepository tagListingRepository;
|
|
|
112 |
@Autowired
|
|
|
113 |
private SchemeInOutRepository schemeInOutRepository;
|
|
|
114 |
@Autowired
|
|
|
115 |
@Qualifier("catalogItemRepository")
|
|
|
116 |
private ItemRepository itemRepository;
|
|
|
117 |
@Autowired
|
|
|
118 |
private SchemeItemRepository schemeItemRepository;
|
|
|
119 |
@Autowired
|
|
|
120 |
private SchemeRegionRepository schemeRegionRepository;
|
|
|
121 |
@Autowired
|
|
|
122 |
private WalletService walletService;
|
|
|
123 |
@Autowired
|
|
|
124 |
private PurchaseRepository purchaseRepository;
|
|
|
125 |
@Autowired
|
|
|
126 |
private FofoOrderRepository fofoOrderRepository;
|
| 31921 |
amit.gupta |
127 |
@Autowired
|
|
|
128 |
private PriceCircularService priceCircularService;
|
| 33600 |
ranu |
129 |
@Autowired
|
|
|
130 |
private SamsungExceptionRepository samsungExceptionRepository;
|
|
|
131 |
|
| 31410 |
amit.gupta |
132 |
@Override
|
| 34221 |
tejus.loha |
133 |
public List<String> getBlockedImeis() {
|
| 34254 |
tejus.loha |
134 |
List<SchemeBlockedImei> schemeBlockedImeis = schemeBlockedImeiRepository.selectAll();
|
| 34221 |
tejus.loha |
135 |
return schemeBlockedImeis.stream().filter(x -> x.isBlocked()).map(x -> x.getImei()).collect(Collectors.toList());
|
|
|
136 |
}
|
|
|
137 |
|
|
|
138 |
@Override
|
| 31410 |
amit.gupta |
139 |
public void saveScheme(int creatorId, CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
|
| 23444 |
amit.gupta |
140 |
|
| 31410 |
amit.gupta |
141 |
this.validateCreateSchemeRequest(createSchemeRequest);
|
| 27898 |
amit.gupta |
142 |
|
| 31410 |
amit.gupta |
143 |
Scheme scheme = this.toScheme(creatorId, createSchemeRequest);
|
| 25503 |
amit.gupta |
144 |
|
| 31410 |
amit.gupta |
145 |
if (scheme.getStartDateTime().isAfter(scheme.getEndDateTime())) {
|
|
|
146 |
throw new ProfitMandiBusinessException(
|
|
|
147 |
ProfitMandiConstants.START_DATE + ", " + ProfitMandiConstants.END_DATE,
|
|
|
148 |
scheme.getStartDateTime() + ", " + scheme.getEndDateTime(), "SCHM_VE_1005");
|
|
|
149 |
}
|
| 26722 |
amit.gupta |
150 |
|
| 31410 |
amit.gupta |
151 |
// this.validateItemIds(createSchemeRequest);
|
|
|
152 |
schemeRepository.persist(scheme);
|
|
|
153 |
for (int catalogId : createSchemeRequest.getCatalogIds()) {
|
|
|
154 |
SchemeItem schemeItem = new SchemeItem();
|
|
|
155 |
schemeItem.setSchemeId(scheme.getId());
|
|
|
156 |
schemeItem.setCatalogId(catalogId);
|
| 34317 |
amit.gupta |
157 |
schemeItem.setStartDate(createSchemeRequest.getStartDate());
|
|
|
158 |
schemeItem.setEndDate(createSchemeRequest.getEndDate());
|
| 31410 |
amit.gupta |
159 |
schemeItemRepository.persist(schemeItem);
|
|
|
160 |
}
|
| 23444 |
amit.gupta |
161 |
|
| 31410 |
amit.gupta |
162 |
for (int regionId : createSchemeRequest.getRegionIds()) {
|
|
|
163 |
SchemeRegion schemeRegion = new SchemeRegion();
|
|
|
164 |
schemeRegion.setSchemeId(scheme.getId());
|
|
|
165 |
schemeRegion.setRegionId(regionId);
|
|
|
166 |
schemeRegionRepository.persist(schemeRegion);
|
|
|
167 |
}
|
| 26332 |
amit.gupta |
168 |
|
| 31410 |
amit.gupta |
169 |
}
|
| 26722 |
amit.gupta |
170 |
|
| 31410 |
amit.gupta |
171 |
private void validateCreateSchemeRequest(CreateSchemeRequest createSchemeRequest)
|
|
|
172 |
throws ProfitMandiBusinessException {
|
|
|
173 |
if (createSchemeRequest.getName() == null || createSchemeRequest.getName().isEmpty()) {
|
|
|
174 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.NAME, createSchemeRequest.getName(),
|
|
|
175 |
"SCHM_VE_1000");
|
|
|
176 |
}
|
|
|
177 |
if (createSchemeRequest.getAmount() <= 0) {
|
|
|
178 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
|
|
|
179 |
"SCHM_VE_1001");
|
|
|
180 |
}
|
| 26684 |
amit.gupta |
181 |
|
| 31410 |
amit.gupta |
182 |
if (createSchemeRequest.getAmountType().equals(AmountType.PERCENTAGE)
|
|
|
183 |
&& createSchemeRequest.getAmount() > 100) {
|
|
|
184 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.AMOUNT, createSchemeRequest.getAmount(),
|
|
|
185 |
"SCHM_VE_1002");
|
|
|
186 |
}
|
| 23444 |
amit.gupta |
187 |
|
| 31410 |
amit.gupta |
188 |
if (createSchemeRequest.getStartDate() == null) {
|
|
|
189 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.START_DATE, createSchemeRequest.getStartDate(),
|
|
|
190 |
"SCHM_VE_1003");
|
|
|
191 |
}
|
|
|
192 |
if (createSchemeRequest.getEndDate() == null) {
|
|
|
193 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.END_DATE, createSchemeRequest.getEndDate(),
|
|
|
194 |
"SCHM_VE_1004");
|
|
|
195 |
}
|
|
|
196 |
}
|
| 23798 |
amit.gupta |
197 |
|
| 31410 |
amit.gupta |
198 |
private void validateItemIds(CreateSchemeRequest createSchemeRequest) throws ProfitMandiBusinessException {
|
|
|
199 |
if (createSchemeRequest.getCatalogIds() == null || createSchemeRequest.getCatalogIds().isEmpty()) {
|
|
|
200 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getCatalogIds(),
|
|
|
201 |
"SCHM_1003");
|
|
|
202 |
}
|
|
|
203 |
List<Integer> foundItemIds = itemRepository.selectIdsByIdsAndType(createSchemeRequest.getCatalogIds(),
|
|
|
204 |
ItemType.SERIALIZED);
|
|
|
205 |
if (foundItemIds.size() != createSchemeRequest.getCatalogIds().size()) {
|
|
|
206 |
createSchemeRequest.getCatalogIds().removeAll(foundItemIds);
|
|
|
207 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.ITEM_ID, createSchemeRequest.getCatalogIds(),
|
|
|
208 |
"SCHM_1004");
|
|
|
209 |
}
|
|
|
210 |
}
|
| 29927 |
amit.gupta |
211 |
|
| 31410 |
amit.gupta |
212 |
@Override
|
|
|
213 |
public Scheme getSchemeById(int schemeId) throws ProfitMandiBusinessException {
|
|
|
214 |
Scheme scheme = schemeRepository.selectById(schemeId);
|
|
|
215 |
List<Integer> catalogIds = schemeItemRepository.selectCatalogIdsBySchemeId(scheme.getId());
|
|
|
216 |
if (catalogIds.size() > 0) {
|
|
|
217 |
List<Item> items = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds));
|
|
|
218 |
scheme.setCatalogStringMap(this.toCatalogStringMap(items));
|
|
|
219 |
}
|
|
|
220 |
return scheme;
|
|
|
221 |
}
|
| 24562 |
amit.gupta |
222 |
|
| 31410 |
amit.gupta |
223 |
public Map<Integer, String> toCatalogStringMap(List<Item> items) {
|
|
|
224 |
Map<Integer, String> catalogMap = new HashMap<>();
|
|
|
225 |
for (Item item : items) {
|
|
|
226 |
if (!catalogMap.containsKey(item.getCatalogItemId())) {
|
|
|
227 |
catalogMap.put(item.getCatalogItemId(), item.getItemDescriptionNoColor());
|
|
|
228 |
}
|
|
|
229 |
}
|
|
|
230 |
return catalogMap;
|
|
|
231 |
}
|
| 29927 |
amit.gupta |
232 |
|
| 31410 |
amit.gupta |
233 |
private Set<Integer> schemeItemsToCatalogIds(List<SchemeItem> schemeItems) {
|
|
|
234 |
Set<Integer> catalogId = new HashSet<>();
|
|
|
235 |
for (SchemeItem schemeItem : schemeItems) {
|
|
|
236 |
catalogId.add(schemeItem.getCatalogId());
|
|
|
237 |
}
|
|
|
238 |
return catalogId;
|
|
|
239 |
}
|
| 23444 |
amit.gupta |
240 |
|
| 31410 |
amit.gupta |
241 |
@Override
|
| 33248 |
ranu |
242 |
public List<SchemeModel> getAllSchemeModels(LocalDateTime startDateTime, LocalDateTime endDateTime) throws ProfitMandiBusinessException {
|
| 31410 |
amit.gupta |
243 |
List<Scheme> schemes = schemeRepository.selectAllBetweenCreateTimestamp(startDateTime, endDateTime);
|
|
|
244 |
Map<Integer, Scheme> schemeIdSchemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
245 |
List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(schemeIdSchemeMap.keySet());
|
|
|
246 |
Set<Integer> catalogIds = schemeItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
|
|
|
247 |
List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
|
|
|
248 |
Map<Integer, String> catalogStringMap = this.toCatalogStringMap(items);
|
|
|
249 |
this.addCatalogIdsToSchemes(schemeItems, schemeIdSchemeMap, catalogStringMap);
|
|
|
250 |
return this.toSchemeModels(schemeIdSchemeMap);
|
|
|
251 |
}
|
| 23444 |
amit.gupta |
252 |
|
| 31410 |
amit.gupta |
253 |
private List<SchemeModel> toSchemeModels(Map<Integer, Scheme> schemeIdSchemeMap) {
|
|
|
254 |
List<SchemeModel> schemeModels = new ArrayList<>();
|
|
|
255 |
for (Map.Entry<Integer, Scheme> schemeIdSchemeEntry : schemeIdSchemeMap.entrySet()) {
|
|
|
256 |
schemeModels.add(this.toSchemeModel(schemeIdSchemeEntry.getValue()));
|
|
|
257 |
}
|
|
|
258 |
return schemeModels;
|
|
|
259 |
}
|
| 23444 |
amit.gupta |
260 |
|
| 31410 |
amit.gupta |
261 |
private SchemeModel toSchemeModel(Scheme scheme) {
|
|
|
262 |
SchemeModel schemeModel = new SchemeModel();
|
|
|
263 |
schemeModel.setSchemeId(scheme.getId());
|
|
|
264 |
schemeModel.setName(scheme.getName());
|
|
|
265 |
schemeModel.setDescription(scheme.getDescription());
|
|
|
266 |
schemeModel.setSchemeType(scheme.getType().toString());
|
|
|
267 |
schemeModel.setAmountType(scheme.getAmountType().toString());
|
|
|
268 |
schemeModel.setAmount(scheme.getAmount());
|
|
|
269 |
schemeModel.setStartDateTime(StringUtils.toString(scheme.getStartDateTime()));
|
|
|
270 |
schemeModel.setEndDateTime(StringUtils.toString(scheme.getEndDateTime()));
|
|
|
271 |
schemeModel.setCreateTimestamp(StringUtils.toString(scheme.getCreateTimestamp()));
|
|
|
272 |
schemeModel.setActiveTimestamp(StringUtils.toString(scheme.getActiveTimestamp()));
|
|
|
273 |
schemeModel.setExpireTimestamp(StringUtils.toString(scheme.getExpireTimestamp()));
|
|
|
274 |
schemeModel.setCreatedBy(scheme.getCreatedBy());
|
|
|
275 |
schemeModel.setCatalogStringMap(scheme.getCatalogStringMap());
|
|
|
276 |
schemeModel.setRetailerIds(scheme.getRetailerIds());
|
|
|
277 |
return schemeModel;
|
|
|
278 |
}
|
| 23444 |
amit.gupta |
279 |
|
| 31410 |
amit.gupta |
280 |
private void addCatalogIdsToSchemes(List<SchemeItem> schemeItems, Map<Integer, Scheme> schemeIdSchemeMap,
|
|
|
281 |
Map<Integer, String> catalogStringMap) {
|
|
|
282 |
for (SchemeItem schemeItem : schemeItems) {
|
|
|
283 |
Scheme scheme = schemeIdSchemeMap.get(schemeItem.getSchemeId());
|
|
|
284 |
scheme.getCatalogStringMap().put(schemeItem.getCatalogId(), catalogStringMap.get(schemeItem.getCatalogId()));
|
|
|
285 |
}
|
|
|
286 |
}
|
| 31170 |
amit.gupta |
287 |
|
| 31410 |
amit.gupta |
288 |
@Override
|
|
|
289 |
public void activeSchemeById(int schemeId) throws ProfitMandiBusinessException {
|
|
|
290 |
Scheme scheme = schemeRepository.selectById(schemeId);
|
|
|
291 |
if (scheme.getActiveTimestamp() != null) {
|
|
|
292 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
|
|
|
293 |
"SCHM_1005");
|
|
|
294 |
}
|
|
|
295 |
if (scheme.getExpireTimestamp() != null) {
|
|
|
296 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
|
|
|
297 |
"SCHM_1006");
|
|
|
298 |
}
|
|
|
299 |
scheme.setActiveTimestamp(LocalDateTime.now());
|
|
|
300 |
this.sendSchemeNotification(scheme);
|
| 23444 |
amit.gupta |
301 |
|
|
|
302 |
|
| 31410 |
amit.gupta |
303 |
/*
|
|
|
304 |
* if (scheme.getType() == SchemeType.IN) {
|
|
|
305 |
* this.processPreviousPurchases(scheme); } else if (scheme.getType() ==
|
|
|
306 |
* SchemeType.OUT) { this.processPreviousSales(scheme); }
|
|
|
307 |
*/
|
|
|
308 |
}
|
| 23796 |
amit.gupta |
309 |
|
| 34568 |
vikas.jang |
310 |
@Override
|
|
|
311 |
public void activeSchemeByIds(List<Scheme> schemes) throws ProfitMandiBusinessException {
|
|
|
312 |
if (schemes.size() > 0) {
|
|
|
313 |
for (Scheme scheme : schemes) {
|
|
|
314 |
if (scheme.getActiveTimestamp() != null || scheme.getExpireTimestamp() != null) {
|
|
|
315 |
continue;
|
|
|
316 |
}
|
|
|
317 |
scheme.setActiveTimestamp(LocalDateTime.now());
|
|
|
318 |
}
|
|
|
319 |
this.sendCombinedSchemesNotification(schemes);
|
|
|
320 |
}
|
|
|
321 |
}
|
|
|
322 |
|
| 35252 |
aman |
323 |
@Override
|
|
|
324 |
public void expireSchemeByIds(List<Scheme> schemes) throws ProfitMandiBusinessException {
|
|
|
325 |
if (schemes.size() > 0) {
|
|
|
326 |
for (Scheme scheme : schemes) {
|
|
|
327 |
if (scheme.getExpireTimestamp() != null) {
|
|
|
328 |
continue;
|
|
|
329 |
}
|
|
|
330 |
scheme.setExpireTimestamp(scheme.getEndDateTime());
|
|
|
331 |
}
|
| 35334 |
amit |
332 |
//this.sendCombinedSchemesNotification(schemes);
|
| 35252 |
aman |
333 |
}
|
|
|
334 |
}
|
|
|
335 |
|
| 31410 |
amit.gupta |
336 |
private void sendSchemeNotification(Scheme scheme) throws ProfitMandiBusinessException {
|
| 35060 |
amit |
337 |
if (NOFITY_SCHEME_TYPES.contains(scheme.getType())) {
|
| 31336 |
amit.gupta |
338 |
|
| 31410 |
amit.gupta |
339 |
SendNotificationModel sendNotificationModel = new SendNotificationModel();
|
|
|
340 |
List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIds(Collections.singleton(scheme.getId()));
|
|
|
341 |
Set<Integer> catalogIds = schemeItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
|
|
|
342 |
List<String> itemDescriptions = itemRepository.selectAllByCatalogIds(catalogIds).stream().filter(Utils.distinctByKey(Item::getCatalogItemId))
|
|
|
343 |
.map(x -> x.getItemDescriptionNoColor()).collect(Collectors.toList());
|
| 35210 |
vikas |
344 |
String titleTemplate = "Important Notice!\n\n %s of Rs.%s for %s";
|
| 31410 |
amit.gupta |
345 |
String schemeString = "Activation scheme";
|
|
|
346 |
if (scheme.getType().equals(SchemeType.SPECIAL_SUPPORT)) {
|
|
|
347 |
schemeString = "Special Support";
|
|
|
348 |
}
|
| 30957 |
amit.gupta |
349 |
|
| 31410 |
amit.gupta |
350 |
String message = "Duration from - " + FormattingUtils.formatDateMonth(scheme.getStartDateTime()) + " - " + FormattingUtils.formatDateMonth(scheme.getEndDateTime());
|
|
|
351 |
sendNotificationModel.setCampaignName("activationscheme");
|
| 34902 |
vikas |
352 |
sendNotificationModel.setUrl("https://smartdukaan.com/pages/home/notifications");
|
| 31410 |
amit.gupta |
353 |
sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
|
|
|
354 |
sendNotificationModel.setMessage(message);
|
|
|
355 |
sendNotificationModel.setTitle(String.format(titleTemplate, schemeString, FormattingUtils.formatDecimal(scheme.getAmount()), org.apache.commons.lang3.StringUtils.abbreviate(String.join(", ", itemDescriptions), 25)));
|
|
|
356 |
sendNotificationModel.setType("url");
|
|
|
357 |
sendNotificationModel.setMessageType(MessageType.scheme);
|
| 35060 |
amit |
358 |
List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(Arrays.asList(scheme.getId()));
|
|
|
359 |
sendNotificationModel.setRegionIds(schemeRegionList.stream().map(x->x.getRegionId()).collect(Collectors.toList()));
|
| 35236 |
amit |
360 |
notificationService.sendNotification(sendNotificationModel);
|
| 31410 |
amit.gupta |
361 |
}
|
|
|
362 |
}
|
| 23444 |
amit.gupta |
363 |
|
| 34709 |
amit.gupta |
364 |
@Autowired
|
|
|
365 |
LoanRepository loanRepository;
|
| 34708 |
ranu |
366 |
|
| 31410 |
amit.gupta |
367 |
@Override
|
|
|
368 |
public void expireSchemeById(int schemeId, LocalDateTime expiryTime) throws ProfitMandiBusinessException {
|
|
|
369 |
Scheme scheme = schemeRepository.selectById(schemeId);
|
|
|
370 |
if (scheme == null || scheme.getActiveTimestamp() == null) {
|
|
|
371 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.ACTIVE_TIMESTAMP, scheme.getActiveTimestamp(),
|
|
|
372 |
"SCHM_1007");
|
|
|
373 |
}
|
|
|
374 |
if (scheme.getExpireTimestamp() != null) {
|
|
|
375 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
|
|
|
376 |
"SCHM_1008");
|
|
|
377 |
}
|
|
|
378 |
scheme.setExpireTimestamp(LocalDateTime.now());
|
|
|
379 |
if (expiryTime.isAfter(scheme.getEndDateTime())) {
|
|
|
380 |
throw new ProfitMandiBusinessException(ProfitMandiConstants.EXPIRE_TIMESTAMP, scheme.getExpireTimestamp(),
|
|
|
381 |
"End Date cant be extended during expiry");
|
|
|
382 |
}
|
|
|
383 |
scheme.setEndDateTime(expiryTime);
|
|
|
384 |
schemeRepository.persist(scheme);
|
|
|
385 |
}
|
| 23444 |
amit.gupta |
386 |
|
| 31410 |
amit.gupta |
387 |
private Map<Integer, Scheme> toSchemeIdSchemeMap(List<Scheme> schemes) {
|
|
|
388 |
Map<Integer, Scheme> schemeIdSchemeMap = new HashMap<>();
|
|
|
389 |
for (Scheme scheme : schemes) {
|
|
|
390 |
schemeIdSchemeMap.put(scheme.getId(), scheme);
|
|
|
391 |
}
|
|
|
392 |
return schemeIdSchemeMap;
|
|
|
393 |
}
|
| 23444 |
amit.gupta |
394 |
|
| 31410 |
amit.gupta |
395 |
private Map<Integer, Set<Scheme>> toCatalogIdSchemesMap(List<SchemeItem> schemeItems, List<Scheme> schemes) {
|
|
|
396 |
Map<Integer, Scheme> schemesMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
397 |
Map<Integer, Set<Scheme>> catalogSchemesMap = new HashMap<>();
|
|
|
398 |
for (SchemeItem schemeItem : schemeItems) {
|
|
|
399 |
if (!catalogSchemesMap.containsKey(schemeItem.getCatalogId())) {
|
|
|
400 |
catalogSchemesMap.put(schemeItem.getCatalogId(), new HashSet<>());
|
|
|
401 |
}
|
|
|
402 |
Set<Scheme> schemesSet = catalogSchemesMap.get(schemeItem.getCatalogId());
|
|
|
403 |
schemesSet.add(schemesMap.get(schemeItem.getSchemeId()));
|
|
|
404 |
}
|
|
|
405 |
return catalogSchemesMap;
|
|
|
406 |
}
|
| 23444 |
amit.gupta |
407 |
|
| 31410 |
amit.gupta |
408 |
private Map<InventoryItem, Set<Scheme>> toInventoryItemSchemesMap(List<Scheme> schemes,
|
| 33248 |
ranu |
409 |
List<InventoryItem> inventoryItems) throws ProfitMandiBusinessException {
|
| 31410 |
amit.gupta |
410 |
Set<Integer> schemeIds = schemes.stream().map(x -> x.getId()).collect(Collectors.toSet());
|
|
|
411 |
Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
|
|
|
412 |
Set<Integer> catalogIds = itemRepository.selectByIds(itemIds).stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
|
|
|
413 |
List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeIdsAndCatalogIds(schemeIds, catalogIds);
|
| 23444 |
amit.gupta |
414 |
|
| 31410 |
amit.gupta |
415 |
Map<Integer, Set<Scheme>> catalogIdSchemesMap = this.toCatalogIdSchemesMap(schemeItems, schemes);
|
|
|
416 |
Map<InventoryItem, Set<Scheme>> inventoryItemSchemesMap = new HashMap<>();
|
|
|
417 |
for (InventoryItem inventoryItem : inventoryItems) {
|
|
|
418 |
LOGGER.info("inventoryItem {}", inventoryItem);
|
|
|
419 |
LOGGER.info("inventoryItem.getItem() {}", inventoryItem.getItem());
|
|
|
420 |
LOGGER.info("catalogIdSchemesMap {}", catalogIdSchemesMap);
|
|
|
421 |
if (catalogIdSchemesMap.containsKey(inventoryItem.getItem().getCatalogItemId())) {
|
|
|
422 |
inventoryItemSchemesMap.put(inventoryItem, catalogIdSchemesMap.get(inventoryItem.getItem().getCatalogItemId()));
|
|
|
423 |
}
|
|
|
424 |
}
|
|
|
425 |
return inventoryItemSchemesMap;
|
|
|
426 |
}
|
| 31170 |
amit.gupta |
427 |
|
| 31903 |
amit.gupta |
428 |
@Autowired
|
|
|
429 |
OfferTargetSlabRepository offerTargetSlabRepository;
|
|
|
430 |
|
| 31410 |
amit.gupta |
431 |
private Scheme toScheme(int creatorId, CreateSchemeRequest createSchemeRequest) {
|
|
|
432 |
Scheme scheme = new Scheme();
|
|
|
433 |
scheme.setName(createSchemeRequest.getName());
|
|
|
434 |
scheme.setDescription(createSchemeRequest.getDescription());
|
|
|
435 |
scheme.setType(createSchemeRequest.getType());
|
|
|
436 |
scheme.setAmountType(createSchemeRequest.getAmountType());
|
|
|
437 |
scheme.setAmount(createSchemeRequest.getAmount());
|
|
|
438 |
scheme.setPartnerType(createSchemeRequest.getPartnerType());
|
|
|
439 |
scheme.setStartDateTime(createSchemeRequest.getStartDate());
|
|
|
440 |
scheme.setEndDateTime(createSchemeRequest.getEndDate());
|
|
|
441 |
scheme.setCreatedBy(creatorId);
|
|
|
442 |
scheme.setCashback(createSchemeRequest.isCashback());
|
| 36451 |
amit |
443 |
scheme.setReference(createSchemeRequest.getReference());
|
| 31410 |
amit.gupta |
444 |
return scheme;
|
|
|
445 |
}
|
| 23444 |
amit.gupta |
446 |
|
| 31903 |
amit.gupta |
447 |
@Autowired
|
|
|
448 |
OfferRepository offerRepository;
|
|
|
449 |
@Autowired
|
|
|
450 |
OfferPayoutRepository offerPayoutRepository;
|
|
|
451 |
@Autowired
|
|
|
452 |
AgeingService ageingService;
|
| 31588 |
amit.gupta |
453 |
|
| 35060 |
amit |
454 |
@Override
|
|
|
455 |
public void sendCombinedSchemesNotification(List<Scheme> schemes) throws ProfitMandiBusinessException {
|
| 34709 |
amit.gupta |
456 |
if (schemes == null || schemes.isEmpty()) return;
|
|
|
457 |
|
|
|
458 |
|
| 35060 |
amit |
459 |
List<Scheme> filteredSchemes = schemes.stream()
|
|
|
460 |
.filter(s -> NOFITY_SCHEME_TYPES.contains(s.getType())).collect(Collectors.toList());
|
| 34709 |
amit.gupta |
461 |
|
| 35060 |
amit |
462 |
Map<Integer, Scheme> schemesMap = filteredSchemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
|
| 34709 |
amit.gupta |
463 |
|
| 35060 |
amit |
464 |
Map<Integer, List<Integer>> schemeIdRegionIdsMap = schemeRegionRepository.selectAllBySchemeIds(new ArrayList<>(schemesMap.keySet()))
|
|
|
465 |
.stream().collect(Collectors.groupingBy(SchemeRegion::getSchemeId,
|
|
|
466 |
Collectors.collectingAndThen(Collectors.mapping(SchemeRegion::getRegionId, Collectors.toList()),
|
|
|
467 |
list -> {
|
|
|
468 |
list.sort(Integer::compareTo); // sort ascending
|
|
|
469 |
return list;
|
|
|
470 |
})));
|
| 34709 |
amit.gupta |
471 |
|
| 35394 |
amit |
472 |
// Batch fetch all schemeItems for all filtered schemes at once
|
|
|
473 |
Map<Integer, List<SchemeItem>> schemeItemsBySchemeId = schemeItemRepository.selectBySchemeIds(schemesMap.keySet())
|
|
|
474 |
.stream().collect(Collectors.groupingBy(SchemeItem::getSchemeId));
|
|
|
475 |
|
|
|
476 |
// Collect all catalogIds for batch fetching items
|
|
|
477 |
Set<Integer> allCatalogIdsForFetch = schemeItemsBySchemeId.values().stream()
|
|
|
478 |
.flatMap(List::stream)
|
|
|
479 |
.map(SchemeItem::getCatalogId)
|
|
|
480 |
.collect(Collectors.toSet());
|
|
|
481 |
|
|
|
482 |
// Batch fetch all items by catalogIds once
|
|
|
483 |
Map<Integer, List<Item>> itemsByCatalogId = allCatalogIdsForFetch.isEmpty()
|
|
|
484 |
? Collections.emptyMap()
|
|
|
485 |
: itemRepository.selectAllByCatalogIds(allCatalogIdsForFetch).stream()
|
|
|
486 |
.collect(Collectors.groupingBy(Item::getCatalogItemId));
|
|
|
487 |
|
| 35060 |
amit |
488 |
Map<List<Integer>, Map<String, List<Scheme>>> groupedByRegionDate = filteredSchemes.stream()
|
|
|
489 |
.collect(Collectors.groupingBy(s -> schemeIdRegionIdsMap.get(s.getId()), Collectors.groupingBy(s ->
|
|
|
490 |
String.valueOf(s.getStartDateTime()).substring(0, 10) + " - " +
|
|
|
491 |
String.valueOf(s.getEndDateTime()).substring(0, 10)
|
|
|
492 |
)));
|
| 34709 |
amit.gupta |
493 |
|
| 35060 |
amit |
494 |
for (Map.Entry<List<Integer>, Map<String, List<Scheme>>> regionIdsDateKeyset : groupedByRegionDate.entrySet()) {
|
|
|
495 |
SendNotificationModel sendNotificationModel = new SendNotificationModel();
|
|
|
496 |
StringBuilder messageBuilder = new StringBuilder();
|
|
|
497 |
Set<Integer> allCatalogIds = new HashSet<>();
|
|
|
498 |
Set<String> allBrands = new HashSet<>();
|
|
|
499 |
String schemeTypeLabel = null;
|
|
|
500 |
List<Integer> regionIds = regionIdsDateKeyset.getKey();
|
|
|
501 |
for (Map.Entry<String, List<Scheme>> entry : regionIdsDateKeyset.getValue().entrySet()) {
|
|
|
502 |
String dateRange = entry.getKey();
|
|
|
503 |
List<Scheme> groupedSchemes = entry.getValue();
|
| 34709 |
amit.gupta |
504 |
|
|
|
505 |
|
| 35060 |
amit |
506 |
messageBuilder.append(String.format("Duration: %s\n", dateRange));
|
| 34962 |
vikas |
507 |
|
| 35060 |
amit |
508 |
for (Scheme scheme : groupedSchemes) {
|
|
|
509 |
if (scheme.getType().equals(SchemeType.SPECIAL_SUPPORT)) {
|
|
|
510 |
schemeTypeLabel = "Special Support";
|
|
|
511 |
} else if (scheme.getType().equals(SchemeType.SELLOUT)) {
|
|
|
512 |
schemeTypeLabel = "Sellout Scheme";
|
|
|
513 |
} else if (scheme.getType().equals(SchemeType.SELLIN)) {
|
|
|
514 |
schemeTypeLabel = "Sellin Scheme";
|
|
|
515 |
}
|
| 34962 |
vikas |
516 |
|
| 35394 |
amit |
517 |
// Use pre-fetched schemeItems instead of N+1 query
|
|
|
518 |
List<SchemeItem> schemeItems = schemeItemsBySchemeId.getOrDefault(scheme.getId(), Collections.emptyList());
|
| 35060 |
amit |
519 |
|
|
|
520 |
Set<Integer> catalogIds = schemeItems.stream()
|
|
|
521 |
.map(SchemeItem::getCatalogId)
|
|
|
522 |
.collect(Collectors.toSet());
|
|
|
523 |
allCatalogIds.addAll(catalogIds);
|
|
|
524 |
|
| 35394 |
amit |
525 |
// Use pre-fetched items instead of duplicate DB calls
|
|
|
526 |
List<Item> catalogItems = catalogIds.stream()
|
|
|
527 |
.flatMap(cid -> itemsByCatalogId.getOrDefault(cid, Collections.emptyList()).stream())
|
|
|
528 |
.collect(Collectors.toList());
|
|
|
529 |
|
|
|
530 |
List<String> itemBrand = catalogItems.stream()
|
| 35060 |
amit |
531 |
.map(Item::getBrand)
|
|
|
532 |
.filter(Objects::nonNull)
|
|
|
533 |
.distinct()
|
|
|
534 |
.collect(Collectors.toList());
|
|
|
535 |
allBrands.addAll(itemBrand);
|
|
|
536 |
|
| 35394 |
amit |
537 |
List<String> itemDescriptions = catalogItems.stream()
|
| 35060 |
amit |
538 |
.filter(Utils.distinctByKey(Item::getCatalogItemId))
|
|
|
539 |
.map(Item::getItemDescriptionNoColor)
|
|
|
540 |
.collect(Collectors.toList());
|
|
|
541 |
|
|
|
542 |
messageBuilder.append(String.format("%s of Rs.%s on Models: %s\n",
|
|
|
543 |
schemeTypeLabel,
|
|
|
544 |
FormattingUtils.formatDecimal(scheme.getAmount()),
|
|
|
545 |
String.join(", ", itemDescriptions)));
|
|
|
546 |
}
|
|
|
547 |
messageBuilder.append("\n");
|
| 34962 |
vikas |
548 |
}
|
| 34709 |
amit.gupta |
549 |
|
| 35060 |
amit |
550 |
if (allBrands.isEmpty() || schemeTypeLabel == null) return;
|
| 34709 |
amit.gupta |
551 |
|
| 35060 |
amit |
552 |
String title = String.format("%s for %s",
|
|
|
553 |
schemeTypeLabel,
|
|
|
554 |
String.join(", ", allBrands));
|
| 34962 |
vikas |
555 |
|
| 35060 |
amit |
556 |
sendNotificationModel.setCampaignName("activationscheme");
|
|
|
557 |
sendNotificationModel.setUrl("https://store.smartdukaan.com/pages/home/notifications");
|
|
|
558 |
sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
|
|
|
559 |
sendNotificationModel.setTitle(title);
|
|
|
560 |
sendNotificationModel.setMessage(messageBuilder.toString().trim());
|
|
|
561 |
sendNotificationModel.setType("url");
|
|
|
562 |
sendNotificationModel.setMessageType(MessageType.scheme);
|
|
|
563 |
sendNotificationModel.setRegionIds(regionIds);
|
|
|
564 |
System.out.println(sendNotificationModel);
|
|
|
565 |
notificationService.sendNotification(sendNotificationModel);
|
|
|
566 |
}
|
|
|
567 |
|
| 34709 |
amit.gupta |
568 |
}
|
|
|
569 |
|
|
|
570 |
//CDs would be rejected based on cdFreeDays
|
| 31903 |
amit.gupta |
571 |
public void processSchemeIn(int purchaseId, int retailerId) throws ProfitMandiBusinessException {
|
| 34504 |
amit.gupta |
572 |
LOGGER.info("Processing scheme in for purchaseId - {}", purchaseId);
|
| 31903 |
amit.gupta |
573 |
Purchase purchase = purchaseRepository.selectByIdAndFofoId(purchaseId, retailerId);
|
| 34709 |
amit.gupta |
574 |
String purchaseInvoice = purchase.getPurchaseReference();
|
|
|
575 |
|
|
|
576 |
Loan loan = loanRepository.selectLoanByInvoice(purchaseInvoice);
|
|
|
577 |
|
| 34317 |
amit.gupta |
578 |
PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
|
|
|
579 |
YearMonth.from(purchase.getCreateTimestamp()));
|
| 34139 |
amit.gupta |
580 |
List<InventoryItem> inventoryItems = inventoryItemRepository.selectByPurchaseId(purchaseId);
|
| 31903 |
amit.gupta |
581 |
//Remove imeis from blocked imeis list
|
| 34317 |
amit.gupta |
582 |
List<String> blockedImeis = this.getBlockedImeis();
|
|
|
583 |
inventoryItems = inventoryItems.stream().filter(inventoryItem -> !blockedImeis.contains(inventoryItem.getSerialNumber())).collect(Collectors.toList());
|
| 31903 |
amit.gupta |
584 |
if (inventoryItems.size() == 0) return;
|
| 23444 |
amit.gupta |
585 |
|
| 31903 |
amit.gupta |
586 |
Set<Integer> itemIds = inventoryItems.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
|
|
|
587 |
Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemIds).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
588 |
inventoryItems.stream().forEach(x -> x.setItem(itemsMap.get(x.getItemId())));
|
| 23444 |
amit.gupta |
589 |
|
|
|
590 |
|
| 34317 |
amit.gupta |
591 |
LocalDateTime billingDate = purchaseService.getBillingDateOfPurchase(purchaseId);
|
| 31903 |
amit.gupta |
592 |
Set<Integer> itemIdsSet = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds).stream()
|
|
|
593 |
.filter(x -> x.getEolDate() == null || x.getEolDate().isAfter(billingDate)).map(x -> x.getItemId())
|
|
|
594 |
.collect(Collectors.toSet());
|
|
|
595 |
// Only consider inventory items that were not returned and not eol
|
|
|
596 |
inventoryItems = inventoryItems.stream().filter(x -> itemIdsSet.contains(x.getItemId()))
|
|
|
597 |
.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET_BAD))
|
|
|
598 |
.filter(x -> !x.getLastScanType().equals(ScanType.PURCHASE_RET)).collect(Collectors.toList());
|
|
|
599 |
|
|
|
600 |
if (inventoryItems.size() == 0) return;
|
|
|
601 |
|
|
|
602 |
Map<Integer, List<InventoryItem>> catalogInventoryItemMap = inventoryItems.stream().collect(Collectors.groupingBy(x -> x.getItem().getCatalogItemId()));
|
| 34317 |
amit.gupta |
603 |
Map<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSchemeSummaryMap = tagListingRepository.getModelSchemesByCatalogIdsAndType(retailerId,
|
| 32454 |
amit.gupta |
604 |
partnerType, new ArrayList<>(catalogInventoryItemMap.keySet()), billingDate);
|
| 31903 |
amit.gupta |
605 |
|
|
|
606 |
|
|
|
607 |
int itemsCount = 0;
|
|
|
608 |
float totalCashback = 0;
|
| 34709 |
amit.gupta |
609 |
//LOGGER.info("catalogSchemeSummaryMap - {}", catalogSchemeSummaryMap);
|
| 31903 |
amit.gupta |
610 |
for (Map.Entry<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSummaryModelListEntry : catalogSchemeSummaryMap.entrySet()) {
|
|
|
611 |
CatalogSummaryModel catalogSummaryModel = catalogSummaryModelListEntry.getKey();
|
| 34504 |
amit.gupta |
612 |
List<SchemeSummaryModel> schemeSummaryModels = catalogSummaryModelListEntry.getValue().stream().filter(Objects::nonNull).collect(Collectors.toList());
|
| 34317 |
amit.gupta |
613 |
schemeSummaryModels.stream().filter(x -> x != null && x.getSchemeType().getTransactionType().equals(StockTransactionType.IN)).forEach(x -> x.setProcess(true));
|
| 31903 |
amit.gupta |
614 |
if (schemeSummaryModels.stream().filter(x -> x.isProcess()).count() == 0) continue;
|
|
|
615 |
List<InventoryItem> modelInventoryItems = catalogInventoryItemMap.get(catalogSummaryModel.getCatalogId());
|
|
|
616 |
for (InventoryItem inventoryItem : modelInventoryItems) {
|
| 36405 |
amit |
617 |
inventoryItemRepository.selectForUpdate(inventoryItem.getId());
|
| 32165 |
amit.gupta |
618 |
float inventoryItemCashback = this.createSchemeInOut(schemeSummaryModels, inventoryItem);
|
| 34709 |
amit.gupta |
619 |
if (loan != null && loan.getCdFreeDays() > 0) {
|
|
|
620 |
List<SchemeType> rejectedCDTypes = HALF_DAYS_CD_REJECT_SCHEME_TYPES;
|
| 36070 |
amit |
621 |
if (loan.getCdFreeDays() == ProfitMandiConstants.LOAN_FULL_CREDIT_DAYS
|
|
|
622 |
|| loan.getCdFreeDays() == ProfitMandiConstants.PREMIUM_LOAN_FULL_CREDIT_DAYS) {
|
| 34709 |
amit.gupta |
623 |
rejectedCDTypes = FULL_DAYS_CD_SCHEME_TYPES;
|
|
|
624 |
}
|
|
|
625 |
for (SchemeType rejectedCDType : rejectedCDTypes) {
|
| 35394 |
amit |
626 |
// Fixed: single DB call instead of duplicate calls
|
|
|
627 |
List<SchemeInOut> cdSios = schemeInOutRepository.selectAllByType(rejectedCDType, inventoryItem.getId());
|
|
|
628 |
SchemeInOut sio = cdSios.isEmpty() ? null : cdSios.get(0);
|
| 34800 |
amit.gupta |
629 |
if (sio == null) continue;
|
| 34709 |
amit.gupta |
630 |
sio.setStatus(SchemePayoutStatus.REJECTED);
|
| 34850 |
amit |
631 |
//Noone should change this
|
| 34709 |
amit.gupta |
632 |
sio.setStatusDescription("Rejected due to free days availed");
|
|
|
633 |
sio.setRolledBackTimestamp(LocalDateTime.now());
|
|
|
634 |
inventoryItemCashback -= sio.getAmount();
|
|
|
635 |
}
|
|
|
636 |
|
|
|
637 |
}
|
|
|
638 |
if (inventoryItemCashback > 0.01f) {
|
| 31903 |
amit.gupta |
639 |
itemsCount++;
|
|
|
640 |
totalCashback += inventoryItemCashback;
|
| 31410 |
amit.gupta |
641 |
}
|
|
|
642 |
}
|
| 31903 |
amit.gupta |
643 |
}
|
| 22653 |
ashik.ali |
644 |
|
| 29927 |
amit.gupta |
645 |
|
| 34317 |
amit.gupta |
646 |
LOGGER.info("Items count for purchase id {} is {}", purchaseId, itemsCount);
|
| 31903 |
amit.gupta |
647 |
if (itemsCount > 0) {
|
|
|
648 |
walletService.addAmountToWallet(
|
| 34317 |
amit.gupta |
649 |
retailerId, purchaseId, WalletReferenceType.SCHEME_IN, "Added for SCHEME IN against invoice "
|
| 31903 |
amit.gupta |
650 |
+ purchase.getPurchaseReference() + " (total " + itemsCount + " pcs)",
|
|
|
651 |
totalCashback, purchase.getCreateTimestamp());
|
|
|
652 |
LOGGER.info("Added Rs.{} for SCHEME IN against invoice {} total pcs({}) {}", totalCashback,
|
|
|
653 |
purchase.getPurchaseReference(), itemsCount);
|
| 34504 |
amit.gupta |
654 |
}
|
| 34317 |
amit.gupta |
655 |
|
| 31903 |
amit.gupta |
656 |
}
|
|
|
657 |
|
|
|
658 |
|
| 35895 |
amit |
659 |
// Calculate payout amount for an inventory item based on scheme type.
|
|
|
660 |
// For PERCENTAGE schemes: uses price-drop-adjusted DP (purchase price minus any price drop).
|
|
|
661 |
// GRN (IN): dpForCalc = purchasePrice - priceDropAmount
|
|
|
662 |
// Sale (OUT): dpForCalc = min(purchasePrice - priceDropAmount, currentSellingPrice)
|
|
|
663 |
// On price increase, priceDropAmount stays 0 so payout is on original purchase price.
|
|
|
664 |
// For FIXED schemes (IN only): returns the fixed scheme amount directly.
|
| 31410 |
amit.gupta |
665 |
private float getAmount(InventoryItem inventoryItem, Scheme scheme) throws ProfitMandiBusinessException {
|
| 34221 |
tejus.loha |
666 |
if (this.getBlockedImeis().contains(inventoryItem.getSerialNumber())) {
|
| 31410 |
amit.gupta |
667 |
return 0;
|
|
|
668 |
}
|
|
|
669 |
float amount = 0;
|
|
|
670 |
float dpForCalc = 0;
|
| 29927 |
amit.gupta |
671 |
|
| 31410 |
amit.gupta |
672 |
if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
|
| 34317 |
amit.gupta |
673 |
if (scheme.getType().getTransactionType().equals(StockTransactionType.IN)) {
|
| 31410 |
amit.gupta |
674 |
dpForCalc = inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
|
|
|
675 |
} else {
|
|
|
676 |
try {
|
|
|
677 |
dpForCalc = Math.min(inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount(),
|
|
|
678 |
tagListingRepository.selectByItemId(inventoryItem.getItemId()).getSellingPrice());
|
|
|
679 |
} catch (Exception e) {
|
| 35895 |
amit |
680 |
LOGGER.info("Could not find tag Listing entry for itemId {}", inventoryItem.getItemId());
|
| 31410 |
amit.gupta |
681 |
}
|
|
|
682 |
}
|
|
|
683 |
amount = dpForCalc * scheme.getAmount() / 100;
|
| 35895 |
amit |
684 |
LOGGER.debug("Scheme payout: invId={}, imei={}, schemeId={}, dpForCalc={}, schemeAmt={}%, payout={}",
|
|
|
685 |
inventoryItem.getId(), inventoryItem.getSerialNumber(), scheme.getId(),
|
|
|
686 |
dpForCalc, scheme.getAmount(), amount);
|
| 34317 |
amit.gupta |
687 |
} else if (scheme.getType().getTransactionType().equals(StockTransactionType.IN)) {
|
| 31410 |
amit.gupta |
688 |
amount = scheme.getAmount();
|
|
|
689 |
}
|
|
|
690 |
return amount;
|
|
|
691 |
}
|
| 23444 |
amit.gupta |
692 |
|
| 31903 |
amit.gupta |
693 |
//Only in and activation margins are allowed to be rolled out more than twice
|
| 32165 |
amit.gupta |
694 |
private float createSchemeInOut(List<SchemeSummaryModel> schemeSummaryModels, InventoryItem inventoryItem) throws ProfitMandiBusinessException {
|
| 33614 |
amit.gupta |
695 |
LOGGER.info("schemeSummaryModels - {}", schemeSummaryModels);
|
| 31921 |
amit.gupta |
696 |
InventoryPayoutModel inventoryPayoutModel = priceCircularService.getPayouts(inventoryItem);
|
| 31903 |
amit.gupta |
697 |
//Get all schemes
|
|
|
698 |
List<SchemeSummaryModel> inventoryPayoutModelToProcess = schemeSummaryModels.stream().filter(x -> x.isProcess()).collect(Collectors.toList());
|
| 34709 |
amit.gupta |
699 |
LOGGER.info("inventoryPayoutModel - {}", inventoryPayoutModel);
|
| 32165 |
amit.gupta |
700 |
List<SchemeInOut> paidSios = inventoryPayoutModel.getPaidSios();
|
|
|
701 |
List<SchemeInOut> pendingSios = inventoryPayoutModel.getPendingSios();
|
|
|
702 |
Map<SchemeType, List<SchemeInOut>> paidSchemeTypesMap = inventoryPayoutModel.getPaidSios().stream().collect(Collectors.groupingBy(x -> x.getScheme().getType()));
|
|
|
703 |
Map<Integer, SchemeInOut> paidSchemesMap = paidSios.stream().collect(Collectors.toMap(x -> x.getSchemeId(), x -> x));
|
|
|
704 |
Map<Integer, SchemeInOut> pendingSchemesMap = pendingSios.stream().collect(Collectors.toMap(x -> x.getSchemeId(), x -> x));
|
| 32155 |
amit.gupta |
705 |
Map<SchemeType, Float> schemeTypeCancelledAmountMap = new HashMap<>();
|
| 31903 |
amit.gupta |
706 |
|
|
|
707 |
double percentageToPay = 0d;
|
|
|
708 |
double fixedToPay = 0d;
|
|
|
709 |
Map<SchemeSummaryModel, AmountModel> payoutSchemeSummaryModelMap = new HashMap<>();
|
|
|
710 |
for (SchemeSummaryModel schemeSummaryModelToProcess : inventoryPayoutModelToProcess) {
|
| 32972 |
amit.gupta |
711 |
if (paidSchemesMap.containsKey(schemeSummaryModelToProcess.getSchemeId()) || pendingSchemesMap.containsKey(schemeSummaryModelToProcess.getSchemeId()))
|
|
|
712 |
continue;
|
| 34778 |
amit.gupta |
713 |
//All Valid margins are supposed to be credited invalid margins should be rejected
|
|
|
714 |
if (SchemeType.SPECIAL_SUPPORT.equals(schemeSummaryModelToProcess.getSchemeType())) {
|
|
|
715 |
//Create only if the activation date is not known
|
| 32165 |
amit.gupta |
716 |
ActivatedImei activatedImei = activatedImeiRepository.selectBySerialNumber(inventoryItem.getSerialNumber());
|
| 32972 |
amit.gupta |
717 |
if (activatedImei == null || activatedImei.getActivationTimestamp() == null) {
|
| 32165 |
amit.gupta |
718 |
SchemeInOut sio = new SchemeInOut();
|
|
|
719 |
sio.setAmount(0);
|
|
|
720 |
sio.setInventoryItemId(inventoryItem.getId());
|
|
|
721 |
sio.setSchemeId(schemeSummaryModelToProcess.getSchemeId());
|
|
|
722 |
sio.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
|
|
|
723 |
sio.setStatus(SchemePayoutStatus.PENDING);
|
|
|
724 |
schemeInOutRepository.persist(sio);
|
|
|
725 |
}
|
| 34317 |
amit.gupta |
726 |
} else if (!StockTransactionType.IN.equals(schemeSummaryModelToProcess.getSchemeType().getTransactionType())) {
|
| 31903 |
amit.gupta |
727 |
//We have got non repeating scheme type
|
| 34709 |
amit.gupta |
728 |
|
|
|
729 |
if (schemeSummaryModelToProcess.getAmountType().equals(AmountType.PERCENTAGE)) {
|
|
|
730 |
percentageToPay += schemeSummaryModelToProcess.getAmount();
|
| 31903 |
amit.gupta |
731 |
} else {
|
| 34709 |
amit.gupta |
732 |
fixedToPay += schemeSummaryModelToProcess.getAmount();
|
| 31903 |
amit.gupta |
733 |
}
|
| 34709 |
amit.gupta |
734 |
payoutSchemeSummaryModelMap.put(schemeSummaryModelToProcess, new AmountModel(schemeSummaryModelToProcess.getAmount(), schemeSummaryModelToProcess.getAmountType()));
|
|
|
735 |
|
| 31903 |
amit.gupta |
736 |
} else {
|
|
|
737 |
if (schemeSummaryModelToProcess.getAmountType().equals(AmountType.PERCENTAGE)) {
|
| 34709 |
amit.gupta |
738 |
//Check for rejected CashDiscounts dont continue if its ever rejected once
|
|
|
739 |
if (SchemeType.CDS.contains(schemeSummaryModelToProcess.getSchemeType())) {
|
|
|
740 |
List<SchemeInOut> cdSchemeInOuts = schemeInOutRepository.selectAllByType(schemeSummaryModelToProcess.getSchemeType(), inventoryItem.getId());
|
|
|
741 |
LOGGER.info(cdSchemeInOuts);
|
| 34850 |
amit |
742 |
if (!cdSchemeInOuts.isEmpty() && cdSchemeInOuts.get(0).getStatusDescription().equals("Rejected due to free days availed"))
|
|
|
743 |
continue;
|
| 34709 |
amit.gupta |
744 |
}
|
| 31903 |
amit.gupta |
745 |
percentageToPay += schemeSummaryModelToProcess.getAmount();
|
|
|
746 |
} else {
|
|
|
747 |
fixedToPay += schemeSummaryModelToProcess.getAmount();
|
|
|
748 |
}
|
|
|
749 |
payoutSchemeSummaryModelMap.put(schemeSummaryModelToProcess, new AmountModel(schemeSummaryModelToProcess.getAmount(), schemeSummaryModelToProcess.getAmountType()));
|
|
|
750 |
}
|
|
|
751 |
}
|
|
|
752 |
double walletCredit = 0d;
|
|
|
753 |
if (fixedToPay > 0) {
|
| 31913 |
amit.gupta |
754 |
double fixedRollout = fixedToPay * (100 / (100 + inventoryPayoutModel.getPercentageAmount()));
|
| 31903 |
amit.gupta |
755 |
for (Map.Entry<SchemeSummaryModel, AmountModel> schemeSummaryModelAmountModelEntry : payoutSchemeSummaryModelMap.entrySet()) {
|
|
|
756 |
SchemeSummaryModel schemeSummaryModel = schemeSummaryModelAmountModelEntry.getKey();
|
|
|
757 |
AmountModel amountModel = schemeSummaryModelAmountModelEntry.getValue();
|
|
|
758 |
if (amountModel.getAmountType().equals(AmountType.FIXED)) {
|
|
|
759 |
SchemeInOut sio = new SchemeInOut();
|
|
|
760 |
sio.setSchemeId(schemeSummaryModel.getSchemeId());
|
|
|
761 |
sio.setInventoryItemId(inventoryItem.getId());
|
|
|
762 |
sio.setStatus(SchemePayoutStatus.CREDITED);
|
|
|
763 |
sio.setCreditTimestamp(LocalDateTime.now());
|
| 32155 |
amit.gupta |
764 |
sio.setAmount((float) (fixedRollout * amountModel.getAmount() / fixedToPay) + schemeTypeCancelledAmountMap.getOrDefault(schemeSummaryModel.getSchemeType(), 0f));
|
| 34317 |
amit.gupta |
765 |
if (schemeSummaryModel.getSchemeType().getTransactionType().equals(StockTransactionType.IN))
|
| 31903 |
amit.gupta |
766 |
sio.setStatusDescription("Credited for GRN of IMEI-" + inventoryItem.getSerialNumber());
|
|
|
767 |
else
|
|
|
768 |
sio.setStatusDescription("Credited for Sale of IMEI-" + inventoryItem.getSerialNumber());
|
|
|
769 |
schemeInOutRepository.persist(sio);
|
|
|
770 |
}
|
|
|
771 |
}
|
|
|
772 |
walletCredit += fixedRollout;
|
|
|
773 |
}
|
|
|
774 |
|
|
|
775 |
if (percentageToPay > 0) {
|
| 31987 |
amit.gupta |
776 |
LOGGER.info("inventoryPayoutModel.getFixedAmount() ----> {}", inventoryPayoutModel.getFixedAmount());
|
| 31914 |
amit.gupta |
777 |
double effectiveDP = inventoryPayoutModel.getDp() - (inventoryPayoutModel.getFixedAmount() + fixedToPay);
|
| 31903 |
amit.gupta |
778 |
double totalPercentage = inventoryPayoutModel.getPercentageAmount() + percentageToPay;
|
|
|
779 |
double percentageRollout = effectiveDP * (totalPercentage / (100 + totalPercentage) - (inventoryPayoutModel.getPercentageAmount() / (100 + inventoryPayoutModel.getPercentageAmount())));
|
|
|
780 |
for (Map.Entry<SchemeSummaryModel, AmountModel> schemeSummaryModelAmountModelEntry : payoutSchemeSummaryModelMap.entrySet()) {
|
|
|
781 |
SchemeSummaryModel schemeSummaryModel = schemeSummaryModelAmountModelEntry.getKey();
|
|
|
782 |
AmountModel amountModel = schemeSummaryModelAmountModelEntry.getValue();
|
|
|
783 |
if (amountModel.getAmountType().equals(AmountType.PERCENTAGE)) {
|
|
|
784 |
SchemeInOut sio = new SchemeInOut();
|
|
|
785 |
sio.setInventoryItemId(inventoryItem.getId());
|
|
|
786 |
sio.setSchemeId(schemeSummaryModel.getSchemeId());
|
|
|
787 |
sio.setStatus(SchemePayoutStatus.CREDITED);
|
|
|
788 |
sio.setCreditTimestamp(LocalDateTime.now());
|
| 32155 |
amit.gupta |
789 |
sio.setAmount((float) (percentageRollout * amountModel.getAmount() / percentageToPay) +
|
|
|
790 |
schemeTypeCancelledAmountMap.getOrDefault(schemeSummaryModel.getSchemeType(), 0f));
|
| 34317 |
amit.gupta |
791 |
if (schemeSummaryModel.getSchemeType().getTransactionType().equals(StockTransactionType.IN))
|
| 31903 |
amit.gupta |
792 |
sio.setStatusDescription("Credited for GRN of IMEI-" + inventoryItem.getSerialNumber());
|
|
|
793 |
else
|
|
|
794 |
sio.setStatusDescription("Credited for Sale of IMEI-" + inventoryItem.getSerialNumber());
|
|
|
795 |
schemeInOutRepository.persist(sio);
|
|
|
796 |
}
|
|
|
797 |
}
|
|
|
798 |
walletCredit += percentageRollout;
|
|
|
799 |
}
|
|
|
800 |
|
|
|
801 |
return (float) walletCredit;
|
|
|
802 |
}
|
|
|
803 |
|
|
|
804 |
private Set<Integer> filterImeisByAgeing(Set<Integer> inventoryItemIds, FofoOrder fofoOrder) {
|
|
|
805 |
Set<Integer> filteredInventoryIds = new HashSet<>();
|
|
|
806 |
List<PartnerAgeingModel> partnerAgeingModels = ageingService.filterAgedInventory(inventoryItemIds);
|
| 35394 |
amit |
807 |
|
|
|
808 |
// Batch fetch all Samsung activated imeis at once to avoid N+1 queries
|
|
|
809 |
List<String> samsungSerialNumbers = partnerAgeingModels.stream()
|
|
|
810 |
.filter(p -> "Samsung".equalsIgnoreCase(p.getBrand()))
|
|
|
811 |
.map(PartnerAgeingModel::getSerialNumber)
|
|
|
812 |
.collect(Collectors.toList());
|
|
|
813 |
Map<String, ActivatedImei> activatedImeiMap = samsungSerialNumbers.isEmpty()
|
|
|
814 |
? Collections.emptyMap()
|
|
|
815 |
: activatedImeiRepository.selectBySerialNumbers(samsungSerialNumbers).stream()
|
|
|
816 |
.collect(Collectors.toMap(ActivatedImei::getSerialNumber, x -> x, (a, b) -> a));
|
|
|
817 |
|
| 31903 |
amit.gupta |
818 |
for (PartnerAgeingModel partnerAgeingModel : partnerAgeingModels) {
|
|
|
819 |
LOGGER.info("Serial Number - {}", partnerAgeingModel.getSerialNumber());
|
|
|
820 |
if (partnerAgeingModel.getBrand().equalsIgnoreCase("Samsung")) {
|
| 35394 |
amit |
821 |
ActivatedImei activatedImei = activatedImeiMap.get(partnerAgeingModel.getSerialNumber());
|
| 31903 |
amit.gupta |
822 |
if (activatedImei != null && activatedImei.getActivationTimestamp().toLocalDate()
|
|
|
823 |
.isBefore(partnerAgeingModel.getBillingDate().plusDays(partnerAgeingModel.getMaxAgeingDays()))) {
|
|
|
824 |
//Lets give money if activation is there and is before the ageing limit of that brand.
|
|
|
825 |
filteredInventoryIds.add(partnerAgeingModel.getInventoryItemId());
|
|
|
826 |
} else {
|
|
|
827 |
//If billing happens before ageing expiry
|
|
|
828 |
if (fofoOrder.getCreateTimestamp().toLocalDate().isBefore(partnerAgeingModel.getBillingDate().plusDays(partnerAgeingModel.getMaxAgeingDays()))) {
|
|
|
829 |
filteredInventoryIds.add(partnerAgeingModel.getInventoryItemId());
|
|
|
830 |
}
|
|
|
831 |
}
|
|
|
832 |
} else {
|
|
|
833 |
filteredInventoryIds.add(partnerAgeingModel.getInventoryItemId());
|
|
|
834 |
}
|
|
|
835 |
}
|
|
|
836 |
return filteredInventoryIds;
|
|
|
837 |
}
|
|
|
838 |
|
| 33087 |
amit.gupta |
839 |
@Autowired
|
|
|
840 |
WarehouseInventoryItemRepository warehouseInventoryItemRepository;
|
|
|
841 |
|
| 31410 |
amit.gupta |
842 |
@Override
|
|
|
843 |
public float processSchemeOut(int fofoOrderId, int retailerId) throws ProfitMandiBusinessException {
|
| 34746 |
amit.gupta |
844 |
|
|
|
845 |
float totalCashback = 0;
|
| 31410 |
amit.gupta |
846 |
FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(retailerId, fofoOrderId);
|
|
|
847 |
// Process only if order is not cancelled
|
|
|
848 |
if (fofoOrder.getCancelledTimestamp() == null) {
|
|
|
849 |
// PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(retailerId,
|
|
|
850 |
// fofoOrder.getCreateTimestamp().toLocalDate());
|
|
|
851 |
// TODO - SCHEME
|
|
|
852 |
PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(retailerId,
|
|
|
853 |
YearMonth.from(fofoOrder.getCreateTimestamp()));
|
| 34778 |
amit.gupta |
854 |
LOGGER.info("OrderDate - {}, Partner Type - {}", fofoOrder.getCreateTimestamp(), partnerType);
|
| 29927 |
amit.gupta |
855 |
|
| 31410 |
amit.gupta |
856 |
List<ScanRecord> scanRecords = scanRecordRepository.selectAllByOrderId(fofoOrderId);
|
|
|
857 |
if (scanRecords.size() == 0) return 0;
|
|
|
858 |
Set<Integer> inventoryItemIds = scanRecords.stream().map(x -> x.getInventoryItemId())
|
|
|
859 |
.collect(Collectors.toSet());
|
| 31903 |
amit.gupta |
860 |
//Check for ageing
|
| 31912 |
amit.gupta |
861 |
//inventoryItemIds = this.filterImeisByAgeing(inventoryItemIds, fofoOrder);
|
| 31903 |
amit.gupta |
862 |
//ageingService.filterAgedInventory(inventoryItemIds);
|
| 31410 |
amit.gupta |
863 |
LOGGER.info("fofoOrderId --- {}", fofoOrderId);
|
|
|
864 |
LOGGER.info("scanRecords --- {}", scanRecords);
|
|
|
865 |
LOGGER.info("inventoryItemIds --- {}", inventoryItemIds);
|
| 31903 |
amit.gupta |
866 |
|
|
|
867 |
if (inventoryItemIds.size() == 0) return 0;
|
|
|
868 |
|
| 35394 |
amit |
869 |
// Cache blocked imeis to avoid repeated DB calls inside stream
|
|
|
870 |
Set<String> blockedImeisSet = new HashSet<>(this.getBlockedImeis());
|
|
|
871 |
|
| 31410 |
amit.gupta |
872 |
Set<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIds).stream()
|
|
|
873 |
.filter(x -> x.getSerialNumber() != null && !x.getSerialNumber().equals(""))
|
|
|
874 |
.collect(Collectors.toSet());
|
| 35394 |
amit |
875 |
inventoryItems = inventoryItems.stream().filter(inventoryItem -> !blockedImeisSet.contains(inventoryItem.getSerialNumber())).collect(Collectors.toSet());
|
| 29927 |
amit.gupta |
876 |
|
| 33087 |
amit.gupta |
877 |
//Do not consider imei above 90 days for samsung
|
| 33432 |
amit.gupta |
878 |
List<String> samsungSerialNumbers = inventoryItems.stream().filter(x -> x.getItem().getBrand().equalsIgnoreCase("samsung")).map(x -> x.getSerialNumber()).collect(Collectors.toList());
|
| 33600 |
ranu |
879 |
|
| 33432 |
amit.gupta |
880 |
if (samsungSerialNumbers.size() > 0) {
|
| 33087 |
amit.gupta |
881 |
List<AgeingSummaryModel> billedImeiModels = warehouseInventoryItemRepository.findStockAgeingByFofoIdSerialNumbers(retailerId, samsungSerialNumbers);
|
| 33606 |
ranu |
882 |
List<String> agedSerialNumbers = billedImeiModels.stream().filter(x -> x.isAgedAbove(365)).map(x -> x.getSerialNumber()).collect(Collectors.toList());
|
|
|
883 |
if (agedSerialNumbers.size() > 0) {
|
|
|
884 |
List<String> samsungExceptionsSerialNumbers = samsungExceptionRepository.selectAllBySerialNumber(agedSerialNumbers).stream().map(x -> x.getSerialNumber()).collect(Collectors.toList());
|
|
|
885 |
agedSerialNumbers.removeAll(samsungExceptionsSerialNumbers);
|
|
|
886 |
}
|
| 33432 |
amit.gupta |
887 |
inventoryItems = inventoryItems.stream().filter(x -> !agedSerialNumbers.contains(x.getSerialNumber())).collect(Collectors.toSet());
|
| 33087 |
amit.gupta |
888 |
}
|
|
|
889 |
|
| 31903 |
amit.gupta |
890 |
if (inventoryItems.size() == 0) return 0;
|
| 29927 |
amit.gupta |
891 |
|
| 36397 |
amit |
892 |
// Resolve GRN billing date per inventory item: InventoryItem.purchaseId -> Purchase.purchaseReference -> Order.billingTimestamp.
|
|
|
893 |
// Scheme resolution for OUT must use each item's own GRN billing date, not fofoOrder.createTimestamp.
|
|
|
894 |
Set<Integer> purchaseIds = inventoryItems.stream().map(InventoryItem::getPurchaseId).collect(Collectors.toSet());
|
|
|
895 |
Map<Integer, LocalDateTime> purchaseBillingDateMap = new HashMap<>();
|
|
|
896 |
for (Integer purchaseId : purchaseIds) {
|
|
|
897 |
purchaseBillingDateMap.put(purchaseId, purchaseService.getBillingDateOfPurchase(purchaseId));
|
|
|
898 |
}
|
| 23444 |
amit.gupta |
899 |
|
| 36397 |
amit |
900 |
// Group items by (GRN billingDate -> catalogId -> items). Items with identical GRN billing date share a scheme lookup.
|
|
|
901 |
Map<LocalDateTime, Map<Integer, List<InventoryItem>>> billingDateCatalogItemsMap = inventoryItems.stream()
|
|
|
902 |
.collect(Collectors.groupingBy(
|
|
|
903 |
x -> purchaseBillingDateMap.get(x.getPurchaseId()),
|
|
|
904 |
Collectors.groupingBy(x -> x.getItem().getCatalogItemId())));
|
| 31903 |
amit.gupta |
905 |
|
| 35493 |
amit |
906 |
// N+1 fix: Batch fetch all SchemeInOut records for all inventoryItems at once
|
|
|
907 |
Set<Integer> allInventoryItemIds = inventoryItems.stream().map(InventoryItem::getId).collect(Collectors.toSet());
|
|
|
908 |
List<SchemeInOut> allSchemeInOuts = schemeInOutRepository.selectByInventoryItemIds(allInventoryItemIds);
|
|
|
909 |
Map<Integer, List<SchemeInOut>> schemeInOutByInventoryItemId = allSchemeInOuts.stream()
|
|
|
910 |
.collect(Collectors.groupingBy(SchemeInOut::getInventoryItemId));
|
| 34317 |
amit.gupta |
911 |
|
| 31410 |
amit.gupta |
912 |
int count = 0;
|
| 36397 |
amit |
913 |
for (Map.Entry<LocalDateTime, Map<Integer, List<InventoryItem>>> billingDateEntry : billingDateCatalogItemsMap.entrySet()) {
|
|
|
914 |
LocalDateTime grnBillingDate = billingDateEntry.getKey();
|
|
|
915 |
Map<Integer, List<InventoryItem>> catalogInventoryItemMap = billingDateEntry.getValue();
|
|
|
916 |
Map<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSchemeSummaryMap = tagListingRepository.getModelSchemesByCatalogIdsAndType(retailerId,
|
|
|
917 |
partnerType, new ArrayList<>(catalogInventoryItemMap.keySet()), grnBillingDate);
|
| 34317 |
amit.gupta |
918 |
|
| 36397 |
amit |
919 |
LOGGER.info("catalogSchemeSummaryMap (grnBillingDate={}) - {}", grnBillingDate, catalogSchemeSummaryMap);
|
| 23444 |
amit.gupta |
920 |
|
| 36397 |
amit |
921 |
for (Map.Entry<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSummaryModelListEntry : catalogSchemeSummaryMap.entrySet()) {
|
|
|
922 |
CatalogSummaryModel catalogSummaryModel = catalogSummaryModelListEntry.getKey();
|
|
|
923 |
List<SchemeSummaryModel> schemeSummaryModels = catalogSummaryModelListEntry.getValue().stream().filter(x -> x != null).collect(Collectors.toList());
|
| 35394 |
amit |
924 |
|
| 36397 |
amit |
925 |
schemeSummaryModels.stream().filter(x -> x.getSchemeType().getTransactionType().equals(StockTransactionType.OUT)).forEach(x -> x.setProcess(true));
|
|
|
926 |
if (schemeSummaryModels.stream().filter(x -> x.isProcess()).count() == 0) continue;
|
|
|
927 |
|
|
|
928 |
// Create map once per catalog instead of per inventoryItem
|
|
|
929 |
Map<Integer, SchemeSummaryModel> schemeSummaryModelMap = schemeSummaryModels.stream().collect(Collectors.toMap(x -> x.getSchemeId(), x -> x));
|
|
|
930 |
|
|
|
931 |
List<InventoryItem> modelInventoryItems = catalogInventoryItemMap.get(catalogSummaryModel.getCatalogId());
|
|
|
932 |
for (InventoryItem inventoryItem : modelInventoryItems) {
|
| 35493 |
amit |
933 |
// N+1 fix: Use pre-fetched schemeInOut map instead of querying per inventoryItem
|
|
|
934 |
List<SchemeInOut> sios = schemeInOutByInventoryItemId.getOrDefault(inventoryItem.getId(), Collections.emptyList());
|
| 34740 |
amit.gupta |
935 |
|
| 34705 |
amit.gupta |
936 |
List<Integer> creditedSchemeIds = sios.stream()
|
|
|
937 |
.filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED))
|
|
|
938 |
.map(x -> x.getSchemeId()).collect(Collectors.toList());
|
| 34698 |
amit.gupta |
939 |
|
| 34742 |
amit.gupta |
940 |
double sioRejectedValue = 0;
|
| 34740 |
amit.gupta |
941 |
if (creditedSchemeIds.size() > 0) {
|
| 34778 |
amit.gupta |
942 |
//Also ignore special support
|
| 34802 |
amit.gupta |
943 |
//This code block needs to be deleted
|
| 34803 |
amit.gupta |
944 |
List<Integer> schemeIdsToReject = null;
|
| 34802 |
amit.gupta |
945 |
if (Arrays.asList(1025588, 1025589).contains(inventoryItem.getItem().getCatalogItemId())) {
|
| 34803 |
amit.gupta |
946 |
schemeIdsToReject = schemeRepository.selectBySchemeIds(creditedSchemeIds).stream()
|
| 34802 |
amit.gupta |
947 |
.filter(x -> !SchemeType.SPECIAL_SUPPORT.equals(x.getType()))
|
|
|
948 |
.map(x -> x.getId()).collect(Collectors.toList());
|
| 34803 |
amit.gupta |
949 |
//List<Integer> schemeIdsToReject = schemeRepository.selectBySchemeIds(creditedSchemeIds).stream()
|
|
|
950 |
//This code block needs to be deleted
|
|
|
951 |
} else {
|
|
|
952 |
schemeIdsToReject = schemeRepository.selectBySchemeIds(creditedSchemeIds).stream()
|
|
|
953 |
.filter(x -> SchemeType.OUT_TYPES.contains(x.getType()) && !SchemeType.SPECIAL_SUPPORT.equals(x.getType()))
|
|
|
954 |
.map(x -> x.getId()).collect(Collectors.toList());
|
|
|
955 |
//Reject invalid scheme payouts due to upgrade in Category or any change in schemes historically
|
|
|
956 |
//Lets not touchs
|
| 34802 |
amit.gupta |
957 |
}
|
| 34740 |
amit.gupta |
958 |
for (SchemeInOut sio : sios) {
|
|
|
959 |
if (schemeIdsToReject.contains(sio.getSchemeId()) && !schemeSummaryModelMap.containsKey(sio.getSchemeId())) {
|
| 35394 |
amit |
960 |
// Removed unused schemeRepository.selectById call
|
| 34778 |
amit.gupta |
961 |
sio.setStatusDescription("Rolledback due to Category upgrade/invalid scheme");
|
|
|
962 |
sio.setStatus(SchemePayoutStatus.REJECTED);
|
|
|
963 |
sio.setRolledBackTimestamp(LocalDateTime.now());
|
|
|
964 |
sioRejectedValue += sio.getAmount();
|
| 34740 |
amit.gupta |
965 |
}
|
| 34705 |
amit.gupta |
966 |
}
|
| 34698 |
amit.gupta |
967 |
}
|
| 32165 |
amit.gupta |
968 |
float inventoryItemCashback = this.createSchemeInOut(schemeSummaryModels, inventoryItem);
|
| 34742 |
amit.gupta |
969 |
if (inventoryItemCashback > 0 || sioRejectedValue > 0) {
|
| 31903 |
amit.gupta |
970 |
count++;
|
| 34742 |
amit.gupta |
971 |
totalCashback += inventoryItemCashback - sioRejectedValue;
|
| 31903 |
amit.gupta |
972 |
}
|
| 31410 |
amit.gupta |
973 |
}
|
| 36397 |
amit |
974 |
}
|
| 31410 |
amit.gupta |
975 |
}
|
| 31903 |
amit.gupta |
976 |
|
| 31410 |
amit.gupta |
977 |
if (count > 0) {
|
|
|
978 |
walletService.addAmountToWallet(
|
|
|
979 |
retailerId, fofoOrderId, WalletReferenceType.SCHEME_OUT, "Sales margin for invoice number "
|
|
|
980 |
+ fofoOrder.getInvoiceNumber() + ". Total " + count + " pc(s)",
|
|
|
981 |
totalCashback, fofoOrder.getCreateTimestamp());
|
|
|
982 |
fofoOrder.setCashback(totalCashback + fofoOrder.getCashback());
|
|
|
983 |
}
|
|
|
984 |
}
|
| 34746 |
amit.gupta |
985 |
return totalCashback;
|
| 31410 |
amit.gupta |
986 |
}
|
| 22653 |
ashik.ali |
987 |
|
| 31410 |
amit.gupta |
988 |
@Override
|
|
|
989 |
//Tax rate has been passed to 0 to ensure no tax deduction
|
|
|
990 |
public float getSpecialSupportAmount(float supportAmount, PartnerType partnerType, LocalDate onDate,
|
|
|
991 |
int catalogId) throws ProfitMandiBusinessException {
|
|
|
992 |
//int itemId = itemRepository.selectAllByCatalogItemId(catalogId).stream().findAny().get().getId();
|
|
|
993 |
//float totalTaxRate = stateGstRateRepository.getTotalTaxRate(itemId);
|
|
|
994 |
return this.getSpecialSupportAmount(supportAmount, partnerType, onDate, catalogId, 0);
|
|
|
995 |
}
|
| 23444 |
amit.gupta |
996 |
|
| 31410 |
amit.gupta |
997 |
@Override
|
|
|
998 |
public float getSpecialSupportAmount(float supportAmount, PartnerType partnerType, LocalDate onDate,
|
|
|
999 |
int catalogId, float taxRate) throws ProfitMandiBusinessException {
|
|
|
1000 |
float totalMargin = this.selectPercentageScheme(partnerType, onDate, catalogId, false, 0, 0).stream().collect(Collectors.summingDouble(x -> x.getAmount())).floatValue();
|
|
|
1001 |
float amountToCredit = supportAmount * (1 - (totalMargin / (100 + taxRate)));
|
|
|
1002 |
return amountToCredit;
|
|
|
1003 |
}
|
| 23444 |
amit.gupta |
1004 |
|
| 31410 |
amit.gupta |
1005 |
@Override
|
| 33614 |
amit.gupta |
1006 |
public void rollbackSchemes(List<Integer> inventoryItemIds, String rollbackReason)
|
| 31410 |
amit.gupta |
1007 |
throws Exception {
|
| 33614 |
amit.gupta |
1008 |
List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(inventoryItemIds);
|
|
|
1009 |
Map<Integer, InventoryItem> inventoryItemMap = inventoryItems.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
1010 |
Map<Integer, Integer> purchasePartnerMap = inventoryItems.stream().collect(Collectors.toMap(x -> x.getPurchaseId(), x -> x.getFofoId(), (u, v) -> u));
|
|
|
1011 |
|
|
|
1012 |
LOGGER.info("inventoryItemIds - {}", inventoryItemIds);
|
|
|
1013 |
List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(inventoryItemIds));
|
|
|
1014 |
List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).distinct().collect(Collectors.toList());
|
| 34139 |
amit.gupta |
1015 |
if (schemeIds.size() == 0) return;
|
| 33614 |
amit.gupta |
1016 |
List<Scheme> schemes = schemeRepository.selectBySchemeIds(schemeIds);
|
|
|
1017 |
Map<Integer, Float> inSchemesMap = new HashMap<>();
|
|
|
1018 |
Map<Integer, Float> outSchemesMap = new HashMap<>();
|
|
|
1019 |
Map<Integer, Scheme> schemesMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
1020 |
for (SchemeInOut schemeInOut : schemeInOuts) {
|
|
|
1021 |
Map<Integer, Float> schemePayoutMap;
|
|
|
1022 |
int inventoryItemId = schemeInOut.getInventoryItemId();
|
| 31410 |
amit.gupta |
1023 |
if (schemeInOut.getRolledBackTimestamp() == null) {
|
|
|
1024 |
schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
|
|
|
1025 |
if (schemeInOut.getStatus() == null || schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
|
| 33614 |
amit.gupta |
1026 |
Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
|
| 34317 |
amit.gupta |
1027 |
if (scheme.getType().getTransactionType().equals(StockTransactionType.IN)) {
|
| 33614 |
amit.gupta |
1028 |
schemePayoutMap = inSchemesMap;
|
|
|
1029 |
} else {
|
|
|
1030 |
schemePayoutMap = outSchemesMap;
|
|
|
1031 |
}
|
|
|
1032 |
if (!schemePayoutMap.containsKey(inventoryItemId)) {
|
|
|
1033 |
schemePayoutMap.put(inventoryItemId, 0f);
|
|
|
1034 |
}
|
| 34139 |
amit.gupta |
1035 |
schemePayoutMap.put(inventoryItemId, inSchemesMap.get(inventoryItemId) == null ? 0 : inSchemesMap.get(inventoryItemId) + schemeInOut.getAmount());
|
| 31410 |
amit.gupta |
1036 |
}
|
|
|
1037 |
schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
|
|
|
1038 |
schemeInOut.setStatusDescription(rollbackReason);
|
|
|
1039 |
}
|
|
|
1040 |
}
|
| 33614 |
amit.gupta |
1041 |
Map<Integer, Double> purchaseRollbackAmountMap = inSchemesMap.entrySet().stream().collect(Collectors.groupingBy(x -> inventoryItemMap.get(x.getKey()).getPurchaseId(), Collectors.summingDouble(x -> x.getValue())));
|
|
|
1042 |
|
|
|
1043 |
for (Map.Entry<Integer, Double> purchaseRollbackAmountEntry : purchaseRollbackAmountMap.entrySet()) {
|
|
|
1044 |
int purchaseId = purchaseRollbackAmountEntry.getKey();
|
|
|
1045 |
Double amountToRollback = purchaseRollbackAmountEntry.getValue();
|
|
|
1046 |
if (amountToRollback != null && amountToRollback > 0) {
|
|
|
1047 |
walletService.rollbackAmountFromWallet(purchasePartnerMap.get(purchaseId), amountToRollback.floatValue(), purchaseId,
|
|
|
1048 |
WalletReferenceType.SCHEME_IN, rollbackReason, LocalDateTime.now());
|
|
|
1049 |
}
|
| 31410 |
amit.gupta |
1050 |
}
|
|
|
1051 |
}
|
| 23444 |
amit.gupta |
1052 |
|
| 31410 |
amit.gupta |
1053 |
@Override
|
| 36103 |
amit |
1054 |
public void restoreSchemes(List<Integer> inventoryItemIds, String debitNoteNumber) throws Exception {
|
|
|
1055 |
String rollbackDescription = "Schemes rolled back for DebitNote #" + debitNoteNumber;
|
|
|
1056 |
|
|
|
1057 |
List<InventoryItem> inventoryItems = inventoryItemRepository.selectAllByIds(inventoryItemIds);
|
|
|
1058 |
Map<Integer, InventoryItem> inventoryItemMap = inventoryItems.stream()
|
|
|
1059 |
.collect(Collectors.toMap(InventoryItem::getId, x -> x));
|
|
|
1060 |
Map<Integer, Integer> purchasePartnerMap = inventoryItems.stream()
|
|
|
1061 |
.collect(Collectors.toMap(InventoryItem::getPurchaseId, InventoryItem::getFofoId, (u, v) -> u));
|
|
|
1062 |
|
|
|
1063 |
List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(inventoryItemIds));
|
|
|
1064 |
List<Integer> schemeIds = schemeInOuts.stream().map(SchemeInOut::getSchemeId).distinct()
|
|
|
1065 |
.collect(Collectors.toList());
|
|
|
1066 |
if (schemeIds.isEmpty()) return;
|
|
|
1067 |
|
|
|
1068 |
List<Scheme> schemes = schemeRepository.selectBySchemeIds(schemeIds);
|
|
|
1069 |
Map<Integer, Scheme> schemesMap = schemes.stream().collect(Collectors.toMap(Scheme::getId, x -> x));
|
|
|
1070 |
Map<Integer, Float> inSchemesRestoreMap = new HashMap<>();
|
|
|
1071 |
|
|
|
1072 |
for (SchemeInOut schemeInOut : schemeInOuts) {
|
|
|
1073 |
if (schemeInOut.getStatus() != null
|
|
|
1074 |
&& schemeInOut.getStatus().equals(SchemePayoutStatus.REJECTED)
|
|
|
1075 |
&& rollbackDescription.equals(schemeInOut.getStatusDescription())) {
|
|
|
1076 |
|
|
|
1077 |
Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
|
|
|
1078 |
if (scheme != null && scheme.getType().getTransactionType().equals(StockTransactionType.IN)) {
|
|
|
1079 |
int inventoryItemId = schemeInOut.getInventoryItemId();
|
|
|
1080 |
inSchemesRestoreMap.merge(inventoryItemId, schemeInOut.getAmount(), Float::sum);
|
|
|
1081 |
}
|
|
|
1082 |
|
|
|
1083 |
schemeInOut.setStatus(SchemePayoutStatus.CREDITED);
|
|
|
1084 |
schemeInOut.setStatusDescription("Restored: DN rejection reversal #" + debitNoteNumber);
|
|
|
1085 |
schemeInOut.setRolledBackTimestamp(null);
|
|
|
1086 |
}
|
|
|
1087 |
}
|
|
|
1088 |
|
|
|
1089 |
Map<Integer, Double> purchaseRestoreAmountMap = inSchemesRestoreMap.entrySet().stream()
|
|
|
1090 |
.collect(Collectors.groupingBy(
|
|
|
1091 |
x -> inventoryItemMap.get(x.getKey()).getPurchaseId(),
|
|
|
1092 |
Collectors.summingDouble(Map.Entry::getValue)));
|
|
|
1093 |
|
|
|
1094 |
String restoreReason = "Scheme restored: DN rejection reversal #" + debitNoteNumber;
|
|
|
1095 |
for (Map.Entry<Integer, Double> entry : purchaseRestoreAmountMap.entrySet()) {
|
|
|
1096 |
int purchaseId = entry.getKey();
|
|
|
1097 |
Double amountToRestore = entry.getValue();
|
|
|
1098 |
if (amountToRestore != null && amountToRestore > 0) {
|
|
|
1099 |
walletService.addAmountToWallet(purchasePartnerMap.get(purchaseId), purchaseId,
|
|
|
1100 |
WalletReferenceType.SCHEME_IN, restoreReason,
|
|
|
1101 |
amountToRestore.floatValue(), LocalDateTime.now());
|
|
|
1102 |
}
|
|
|
1103 |
}
|
|
|
1104 |
}
|
|
|
1105 |
|
|
|
1106 |
@Override
|
| 31410 |
amit.gupta |
1107 |
public Map<String, Object> getSchemes(Set<Integer> roleIds, int offset, int limit)
|
|
|
1108 |
throws ProfitMandiBusinessException {
|
|
|
1109 |
Map<String, Object> map = new HashMap<>();
|
|
|
1110 |
List<Scheme> schemes = null;
|
|
|
1111 |
long size = 0;
|
|
|
1112 |
if (roleManager.isAdmin(roleIds)) {
|
|
|
1113 |
schemes = schemeRepository.selectAll(offset, limit);
|
|
|
1114 |
size = schemeRepository.selectAllCount();
|
|
|
1115 |
} else {
|
|
|
1116 |
schemes = schemeRepository.selectActiveAll(offset, limit);
|
|
|
1117 |
size = schemeRepository.selectAllActiveCount();
|
|
|
1118 |
}
|
|
|
1119 |
map.put("schemes", schemes);
|
|
|
1120 |
map.put("start", offset + 1);
|
|
|
1121 |
map.put("size", size);
|
|
|
1122 |
if (schemes.size() < limit) {
|
|
|
1123 |
map.put("end", offset + schemes.size());
|
|
|
1124 |
} else {
|
|
|
1125 |
map.put("end", offset + limit);
|
|
|
1126 |
}
|
|
|
1127 |
return map;
|
|
|
1128 |
}
|
| 26722 |
amit.gupta |
1129 |
|
| 31410 |
amit.gupta |
1130 |
@Override
|
|
|
1131 |
public List<Scheme> getPaginatedSchemes(Set<Integer> roleIds, int offset, int limit)
|
|
|
1132 |
throws ProfitMandiBusinessException {
|
|
|
1133 |
LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
|
|
|
1134 |
List<Scheme> schemes = null;
|
|
|
1135 |
if (roleManager.isAdmin(roleIds)) {
|
|
|
1136 |
schemes = schemeRepository.selectAll(offset, limit);
|
|
|
1137 |
} else {
|
|
|
1138 |
schemes = schemeRepository.selectActiveAll(offset, limit);
|
|
|
1139 |
}
|
|
|
1140 |
return schemes;
|
|
|
1141 |
}
|
| 27898 |
amit.gupta |
1142 |
|
| 31410 |
amit.gupta |
1143 |
@Override
|
|
|
1144 |
// This is being called to reverse schemes while processing price Drop
|
|
|
1145 |
public void reverseSchemes(List<InventoryItem> inventoryItems, int priceDropId, String reversalReason)
|
|
|
1146 |
throws ProfitMandiBusinessException {
|
|
|
1147 |
PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
|
|
|
1148 |
Map<Integer, List<InventoryItem>> purchaseInventoryListMap = inventoryItems.stream()
|
|
|
1149 |
.collect(Collectors.groupingBy(InventoryItem::getPurchaseId, Collectors.toList()));
|
| 29927 |
amit.gupta |
1150 |
|
| 31410 |
amit.gupta |
1151 |
for (Map.Entry<Integer, List<InventoryItem>> purchaseEntry : purchaseInventoryListMap.entrySet()) {
|
|
|
1152 |
float amountToCredit = 0;
|
|
|
1153 |
float amountToDebit = 0;
|
|
|
1154 |
int purchaseId = purchaseEntry.getKey();
|
|
|
1155 |
List<InventoryItem> purchaseInventoryItemList = purchaseEntry.getValue();
|
| 30454 |
amit.gupta |
1156 |
|
| 31410 |
amit.gupta |
1157 |
Map<Integer, InventoryItem> inventoryItemsMap = purchaseInventoryItemList.stream()
|
|
|
1158 |
.collect(Collectors.toMap(x -> x.getId(), x -> x));
|
| 29927 |
amit.gupta |
1159 |
|
| 31410 |
amit.gupta |
1160 |
List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
|
|
|
1161 |
LOGGER.info("Scheme InOuts , {}", schemeInOuts);
|
|
|
1162 |
if (schemeInOuts.size() == 0) {
|
|
|
1163 |
continue;
|
|
|
1164 |
}
|
|
|
1165 |
List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
|
|
|
1166 |
Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
|
|
|
1167 |
.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
1168 |
for (SchemeInOut schemeInOut : schemeInOuts) {
|
|
|
1169 |
InventoryItem ii = inventoryItemsMap.get(schemeInOut.getInventoryItemId());
|
|
|
1170 |
Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
|
|
|
1171 |
if (scheme.getAmountType().equals(AmountType.FIXED)) {
|
|
|
1172 |
continue;
|
|
|
1173 |
}
|
| 34317 |
amit.gupta |
1174 |
if (scheme.getType().getTransactionType().equals(StockTransactionType.IN) && schemeInOut.getRolledBackTimestamp() == null) {
|
| 33432 |
amit.gupta |
1175 |
schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
|
|
|
1176 |
schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
|
|
|
1177 |
schemeInOut.setStatusDescription("Margin reversed due to price drop");
|
|
|
1178 |
// IF not credited then dont consider any credit/debit for that sio entry
|
|
|
1179 |
if (schemeInOut.getCreditTimestamp() != null) {
|
|
|
1180 |
amountToDebit += schemeInOut.getAmount();
|
| 31410 |
amit.gupta |
1181 |
}
|
|
|
1182 |
}
|
|
|
1183 |
}
|
|
|
1184 |
int fofoId = inventoryItems.get(0).getFofoId();
|
|
|
1185 |
if (amountToDebit > 0) {
|
|
|
1186 |
walletService.addAmountToWallet(fofoId, purchaseId, WalletReferenceType.SCHEME_IN,
|
|
|
1187 |
MessageFormat.format(reversalReason, purchaseInventoryItemList.size()), -amountToDebit,
|
|
|
1188 |
priceDrop.getAffectedOn());
|
|
|
1189 |
}
|
|
|
1190 |
}
|
|
|
1191 |
}
|
| 29231 |
amit.gupta |
1192 |
|
| 31609 |
amit.gupta |
1193 |
@Autowired
|
| 32060 |
amit.gupta |
1194 |
UserWalletRepository userWalletRepository;
|
|
|
1195 |
@Autowired
|
| 31609 |
amit.gupta |
1196 |
UserWalletHistoryRepository userWalletHistoryRepository;
|
|
|
1197 |
|
| 31410 |
amit.gupta |
1198 |
@Override
|
|
|
1199 |
// Always being called from cancel order/bad return means no SCHEME IN is considered
|
|
|
1200 |
public void reverseSchemes(List<InventoryItem> inventoryItems, int reversalReference, String reversalReason,
|
|
|
1201 |
List<SchemeType> schemeTypes) throws ProfitMandiBusinessException {
|
|
|
1202 |
Map<Integer, InventoryItem> inventoryItemsMap = inventoryItems.stream()
|
|
|
1203 |
.collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
1204 |
LOGGER.info("inventoryItems" + inventoryItems);
|
| 23444 |
amit.gupta |
1205 |
|
| 31410 |
amit.gupta |
1206 |
Map<SchemeType, SchemeInOut> schemeTypeMap = new HashMap<>();
|
| 30454 |
amit.gupta |
1207 |
|
| 31410 |
amit.gupta |
1208 |
List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(inventoryItemsMap.keySet());
|
| 32060 |
amit.gupta |
1209 |
List<SchemeInOut> rolledBacks = schemeInOuts.stream().filter(x -> x.getStatusDescription().equals(reversalReason)).collect(Collectors.toList());
|
| 31410 |
amit.gupta |
1210 |
float amountToRollback = 0;
|
| 23444 |
amit.gupta |
1211 |
|
| 31410 |
amit.gupta |
1212 |
if (!schemeInOuts.isEmpty()) {
|
|
|
1213 |
List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
|
|
|
1214 |
LOGGER.info("schemeIds" + schemeIds);
|
| 29231 |
amit.gupta |
1215 |
|
| 31410 |
amit.gupta |
1216 |
Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, schemeIds.size())
|
|
|
1217 |
.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
|
| 32060 |
amit.gupta |
1218 |
if (rolledBacks.size() > 0) {
|
|
|
1219 |
for (SchemeInOut schemeInOut : rolledBacks) {
|
|
|
1220 |
Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
|
|
|
1221 |
if (schemeTypes.contains(scheme.getType())) {
|
|
|
1222 |
schemeTypeMap.put(scheme.getType(), schemeInOut);
|
|
|
1223 |
if (schemeInOut.getCreditTimestamp() != null) {
|
| 31410 |
amit.gupta |
1224 |
amountToRollback += schemeInOut.getAmount();
|
|
|
1225 |
}
|
|
|
1226 |
}
|
|
|
1227 |
}
|
| 32060 |
amit.gupta |
1228 |
} else {
|
|
|
1229 |
for (SchemeInOut schemeInOut : schemeInOuts) {
|
|
|
1230 |
Scheme scheme = schemesMap.get(schemeInOut.getSchemeId());
|
|
|
1231 |
if (schemeTypes.contains(scheme.getType())) {
|
|
|
1232 |
if (schemeInOut.getRolledBackTimestamp() == null) {
|
|
|
1233 |
schemeInOut.setRolledBackTimestamp(LocalDateTime.now());
|
|
|
1234 |
if (schemeInOut.getStatus().equals(SchemePayoutStatus.CREDITED)) {
|
|
|
1235 |
amountToRollback += schemeInOut.getAmount();
|
|
|
1236 |
}
|
|
|
1237 |
schemeInOut.setStatus(SchemePayoutStatus.REJECTED);
|
|
|
1238 |
schemeInOut.setStatusDescription(reversalReason);
|
|
|
1239 |
}
|
|
|
1240 |
}
|
|
|
1241 |
}
|
| 31410 |
amit.gupta |
1242 |
}
|
|
|
1243 |
}
|
| 32060 |
amit.gupta |
1244 |
|
| 31410 |
amit.gupta |
1245 |
int fofoId = inventoryItems.get(0).getFofoId();
|
| 34486 |
amit.gupta |
1246 |
WalletReferenceType walletReferenceType = schemeTypes.containsAll(SchemeType.OUT_SCHEME_TYPES) ? WalletReferenceType.SCHEME_OUT
|
| 31609 |
amit.gupta |
1247 |
: schemeTypes.contains(SchemeType.SPECIAL_SUPPORT) ? WalletReferenceType.SPECIAL_SUPPORT
|
| 34486 |
amit.gupta |
1248 |
: schemeTypes.contains(SchemeType.INVESTMENT) ? WalletReferenceType.SCHEME_OUT : null;
|
| 32060 |
amit.gupta |
1249 |
List<UserWalletHistory> userWalletHistoryList = null;
|
| 32058 |
amit.gupta |
1250 |
if (amountToRollback > 0 && walletReferenceType != null) {
|
|
|
1251 |
// Mark appropriate reference of rollback investment margin
|
| 32060 |
amit.gupta |
1252 |
if (schemeTypes.contains(SchemeType.INVESTMENT) && schemeTypeMap.containsKey(SchemeType.INVESTMENT)) {
|
|
|
1253 |
LocalDateTime creditTime = schemeTypeMap.get(SchemeType.INVESTMENT).getCreditTimestamp();
|
|
|
1254 |
if (creditTime == null) return;
|
|
|
1255 |
int investmentReversalReference = Integer.parseInt(FormattingUtils.getYearMonth(creditTime.minusMonths(1)));
|
|
|
1256 |
UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
|
|
|
1257 |
userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(userWallet.getUserId(), investmentReversalReference, WalletReferenceType.INVESTMENT_PAYOUT);
|
|
|
1258 |
if (userWalletHistoryList.size() > 0) {
|
|
|
1259 |
walletReferenceType = WalletReferenceType.INVESTMENT_PAYOUT;
|
|
|
1260 |
} else {
|
|
|
1261 |
userWalletHistoryList = null;
|
| 32058 |
amit.gupta |
1262 |
}
|
| 32060 |
amit.gupta |
1263 |
}
|
|
|
1264 |
if (userWalletHistoryList == null) {
|
|
|
1265 |
userWalletHistoryList = userWalletHistoryRepository.selectAllByreferenceIdandreferenceType(reversalReference, walletReferenceType);
|
|
|
1266 |
}
|
|
|
1267 |
if (userWalletHistoryList.size() > 0) {
|
|
|
1268 |
int maxDeductible = userWalletHistoryList.stream().collect(Collectors.summingInt(x -> x.getAmount()));
|
|
|
1269 |
if (maxDeductible > 0) {
|
| 32165 |
amit.gupta |
1270 |
LOGGER.info("----------> maxDeductible {}, amountToRollback {}, reversalReference {}, walletReferenceType {} ", maxDeductible, amountToRollback, reversalReference, walletReferenceType);
|
| 32060 |
amit.gupta |
1271 |
walletService.rollbackAmountFromWallet(fofoId, Math.min(maxDeductible, amountToRollback), reversalReference, walletReferenceType,
|
|
|
1272 |
reversalReason, LocalDateTime.now());
|
|
|
1273 |
}
|
| 31609 |
amit.gupta |
1274 |
|
| 31903 |
amit.gupta |
1275 |
}
|
| 32058 |
amit.gupta |
1276 |
}
|
| 31410 |
amit.gupta |
1277 |
}
|
| 29231 |
amit.gupta |
1278 |
|
| 32060 |
amit.gupta |
1279 |
|
| 31410 |
amit.gupta |
1280 |
@Override
|
| 33614 |
amit.gupta |
1281 |
public Map<Integer, Float> getCatalogSchemeCashBack(int fofoId, List<Integer> catalogIds) throws
|
|
|
1282 |
ProfitMandiBusinessException {
|
| 32972 |
amit.gupta |
1283 |
PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
|
|
|
1284 |
Map<CatalogSummaryModel, List<SchemeSummaryModel>> catalogModelMap = tagListingRepository.getModelSchemesByCatalogIdsAndType(fofoId, partnerType, catalogIds, LocalDate.now().atStartOfDay());
|
|
|
1285 |
|
|
|
1286 |
Map<Integer, Float> catalogCashbackMap = new HashMap<>();
|
|
|
1287 |
for (Map.Entry<CatalogSummaryModel, List<SchemeSummaryModel>> catalogSummaryModelListEntry : catalogModelMap.entrySet()) {
|
|
|
1288 |
int catalogItemId = catalogSummaryModelListEntry.getKey().getCatalogId();
|
|
|
1289 |
List<SchemeSummaryModel> schemeSummaryModels = catalogSummaryModelListEntry.getValue();
|
|
|
1290 |
|
|
|
1291 |
float totalCashback = schemeSummaryModels.stream()
|
| 34317 |
amit.gupta |
1292 |
.filter(x -> Arrays.asList(SchemeType.SPECIAL_SUPPORT, SchemeType.SELLOUT).contains(x.getSchemeType())
|
| 32972 |
amit.gupta |
1293 |
&& x.getAmountType().equals(AmountType.FIXED))
|
|
|
1294 |
.collect(Collectors.summingDouble(x -> x.getAmount())).floatValue();
|
|
|
1295 |
catalogCashbackMap.put(catalogItemId, totalCashback);
|
| 31410 |
amit.gupta |
1296 |
}
|
| 32972 |
amit.gupta |
1297 |
return catalogCashbackMap;
|
| 31410 |
amit.gupta |
1298 |
}
|
| 30572 |
amit.gupta |
1299 |
|
| 31410 |
amit.gupta |
1300 |
@Override
|
| 31903 |
amit.gupta |
1301 |
public List<Scheme> selectSchemeByPartnerTypeFofoId(PartnerType partnerType, LocalDate onDate, int catalogId,
|
|
|
1302 |
int fofoId, int offset, int limit) throws ProfitMandiBusinessException {
|
| 31410 |
amit.gupta |
1303 |
Session session = sessionFactory.getCurrentSession();
|
|
|
1304 |
final TypedQuery<Scheme> typedQuery = session.createNamedQuery(
|
|
|
1305 |
"Scheme.selectSchemeByModelsPartnerTypeFofoId", Scheme.class);
|
|
|
1306 |
typedQuery.setParameter("catalogIds", Arrays.asList(catalogId));
|
|
|
1307 |
typedQuery.setParameter("fofoIds", Arrays.asList(fofoId, 0));
|
|
|
1308 |
typedQuery.setParameter("onDate", onDate.atStartOfDay());
|
|
|
1309 |
typedQuery.setParameter("partnerTypes", Arrays.asList(partnerType, partnerType.ALL));
|
|
|
1310 |
typedQuery.setFirstResult(offset);
|
|
|
1311 |
if (limit != 0) {
|
|
|
1312 |
typedQuery.setMaxResults(limit);
|
|
|
1313 |
}
|
|
|
1314 |
return typedQuery.getResultList();
|
|
|
1315 |
}
|
| 30463 |
amit.gupta |
1316 |
|
| 33432 |
amit.gupta |
1317 |
@Override
|
|
|
1318 |
public void processSchemeIn(List<InventoryItem> inventoryItems) throws ProfitMandiBusinessException {
|
|
|
1319 |
Map<Integer, List<InventoryItem>> purchaseIdInventoryItemsMap = inventoryItems.stream().collect(Collectors.groupingBy(x -> x.getPurchaseId()));
|
|
|
1320 |
for (Map.Entry<Integer, List<InventoryItem>> purchaseIdInventoryItemEntry : purchaseIdInventoryItemsMap.entrySet()) {
|
| 34317 |
amit.gupta |
1321 |
int retailerId = purchaseIdInventoryItemEntry.getValue().get(0).getFofoId();
|
|
|
1322 |
this.processSchemeIn(purchaseIdInventoryItemEntry.getKey(), retailerId);
|
| 33432 |
amit.gupta |
1323 |
}
|
|
|
1324 |
}
|
|
|
1325 |
|
| 32309 |
amit.gupta |
1326 |
@Autowired
|
|
|
1327 |
FofoStoreRepository fofoStoreRepository;
|
|
|
1328 |
|
|
|
1329 |
|
| 31410 |
amit.gupta |
1330 |
@Override
|
| 32309 |
amit.gupta |
1331 |
@Cacheable(value = "staticscheme", cacheManager = "oneDayCacheManager")
|
|
|
1332 |
public Scheme getStaticScheme(int fofoId) throws ProfitMandiBusinessException {
|
| 33165 |
amit.gupta |
1333 |
FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
|
| 32504 |
amit.gupta |
1334 |
Scheme scheme = null;
|
|
|
1335 |
if (fofoStore.getTarget() > 0) {
|
|
|
1336 |
scheme = new Scheme();
|
| 35096 |
amit |
1337 |
scheme.setName("Super Retailer - Club 4");
|
|
|
1338 |
scheme.setStartDateTime(LocalDate.of(2025, 8, 1).atStartOfDay());
|
| 35559 |
amit |
1339 |
scheme.setEndDateTime(LocalDate.of(2026, 01, 20).atTime(LocalTime.MAX));
|
| 32504 |
amit.gupta |
1340 |
scheme.setTarget(fofoStore.getTarget());
|
| 33548 |
amit.gupta |
1341 |
|
| 33704 |
amit.gupta |
1342 |
if (scheme.getEndDateTime().plusDays(5).isBefore(LocalDateTime.now())) return null;
|
| 32504 |
amit.gupta |
1343 |
}
|
| 33165 |
amit.gupta |
1344 |
return scheme;
|
| 32309 |
amit.gupta |
1345 |
}
|
|
|
1346 |
|
|
|
1347 |
@Override
|
| 31410 |
amit.gupta |
1348 |
public List<Scheme> selectSchemeByPartnerType(PartnerType partnerType, LocalDate onDate, int catalogId,
|
|
|
1349 |
boolean isAdmin, int offset, int limit) throws ProfitMandiBusinessException {
|
|
|
1350 |
Session session = sessionFactory.getCurrentSession();
|
|
|
1351 |
List<Predicate> andPredicates = new ArrayList<>();
|
|
|
1352 |
CriteriaBuilder cb = session.getCriteriaBuilder();
|
|
|
1353 |
CriteriaQuery<Scheme> query = cb.createQuery(Scheme.class);
|
|
|
1354 |
Root<Scheme> scheme = query.from(Scheme.class);
|
|
|
1355 |
if (!partnerType.equals(PartnerType.ALL)) {
|
|
|
1356 |
List<PartnerType> pt = new ArrayList<>();
|
|
|
1357 |
pt.add(PartnerType.ALL);
|
|
|
1358 |
pt.add(partnerType);
|
|
|
1359 |
andPredicates.add(cb.in(scheme.get("partnerType")).value(pt));
|
|
|
1360 |
}
|
|
|
1361 |
cb.desc(cb.isNull(scheme.get("expireTimestamp")));
|
|
|
1362 |
if (catalogId > 0) {
|
| 30454 |
amit.gupta |
1363 |
|
| 31410 |
amit.gupta |
1364 |
List<Integer> schemeIds = schemeItemRepository.selectSchemeIdByCatalogId(catalogId);
|
|
|
1365 |
LOGGER.info("schemeId" + schemeIds);
|
|
|
1366 |
if (schemeIds.isEmpty()) {
|
|
|
1367 |
return new ArrayList<>();
|
|
|
1368 |
}
|
|
|
1369 |
andPredicates.add(cb.in(scheme.get("id")).value(schemeIds));
|
|
|
1370 |
if (onDate != null) {
|
|
|
1371 |
andPredicates.add(cb.greaterThan(scheme.get("endDateTime"), onDate.atStartOfDay()));
|
|
|
1372 |
andPredicates.add(cb.lessThanOrEqualTo(scheme.get("startDateTime"), onDate.atStartOfDay()));
|
|
|
1373 |
}
|
|
|
1374 |
}
|
|
|
1375 |
if (!isAdmin) {
|
|
|
1376 |
andPredicates.add(cb.isNotNull(scheme.get("activeTimestamp")));
|
|
|
1377 |
}
|
|
|
1378 |
query.where(cb.and(andPredicates.toArray(new Predicate[0])));
|
|
|
1379 |
query.orderBy(cb.desc(cb.function("isnull", Boolean.class, scheme.get("expireTimestamp"))));
|
|
|
1380 |
if (limit == 0) {
|
|
|
1381 |
return session.createQuery(query).setFirstResult(offset).getResultList();
|
|
|
1382 |
}
|
|
|
1383 |
return session.createQuery(query).setFirstResult(offset).setMaxResults(limit).getResultList();
|
| 30454 |
amit.gupta |
1384 |
|
| 31410 |
amit.gupta |
1385 |
}
|
| 30454 |
amit.gupta |
1386 |
|
| 31410 |
amit.gupta |
1387 |
@Override
|
|
|
1388 |
public List<Scheme> selectPercentageScheme(PartnerType partnerType, LocalDate onDate, int catalogId,
|
|
|
1389 |
boolean isAdmin, int offset, int limit) throws ProfitMandiBusinessException {
|
|
|
1390 |
List<Scheme> schemes = this.selectSchemeByPartnerType(partnerType, onDate, catalogId, isAdmin, offset, limit);
|
|
|
1391 |
return schemes.stream().filter(x -> x.getAmountType().equals(AmountType.PERCENTAGE)).collect(Collectors.toList());
|
|
|
1392 |
}
|
| 30454 |
amit.gupta |
1393 |
|
| 31410 |
amit.gupta |
1394 |
@Override
|
|
|
1395 |
public void processActivation() throws ProfitMandiBusinessException {
|
|
|
1396 |
List<SchemeInOut> pendingPayouts = schemeInOutRepository.selectAllPending();
|
|
|
1397 |
List<Integer> schemeIds = new ArrayList<>();
|
|
|
1398 |
Set<Integer> inventoryIds = new HashSet<>();
|
|
|
1399 |
for (SchemeInOut pendingPayout : pendingPayouts) {
|
|
|
1400 |
schemeIds.add(pendingPayout.getSchemeId());
|
|
|
1401 |
}
|
|
|
1402 |
Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds, 0, 0).stream()
|
| 34317 |
amit.gupta |
1403 |
.filter(x -> x.getType().equals(SchemeType.SPECIAL_SUPPORT))
|
| 31410 |
amit.gupta |
1404 |
.collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
1405 |
pendingPayouts = pendingPayouts.stream().filter(x -> schemesMap.get(x.getSchemeId()) != null)
|
|
|
1406 |
.collect(Collectors.toList());
|
| 23884 |
amit.gupta |
1407 |
|
| 31410 |
amit.gupta |
1408 |
for (SchemeInOut pendingPayout : pendingPayouts) {
|
|
|
1409 |
inventoryIds.add(pendingPayout.getInventoryItemId());
|
|
|
1410 |
}
|
|
|
1411 |
Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryIds).stream()
|
|
|
1412 |
.collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
1413 |
Map<String, InventoryItem> serialNumberMap = inventoryItemMap.values().stream()
|
|
|
1414 |
.collect(Collectors.toMap(x -> x.getSerialNumber(), x -> x));
|
| 23796 |
amit.gupta |
1415 |
|
| 31410 |
amit.gupta |
1416 |
List<ActivatedImei> activatedImeis = activatedImeiRepository
|
|
|
1417 |
.selectBySerialNumbers(new ArrayList<>(serialNumberMap.keySet())).stream().collect(Collectors.toList());
|
| 23508 |
amit.gupta |
1418 |
|
| 31410 |
amit.gupta |
1419 |
Map<String, ActivatedImei> activatedImeiMap = activatedImeis.stream()
|
|
|
1420 |
.collect(Collectors.toMap(x -> x.getSerialNumber().toLowerCase(), x -> x));
|
|
|
1421 |
for (SchemeInOut pendingPayout : pendingPayouts) {
|
| 31914 |
amit.gupta |
1422 |
Scheme scheme = schemesMap.get(pendingPayout.getSchemeId());
|
| 31410 |
amit.gupta |
1423 |
InventoryItem ii = inventoryItemMap.get(pendingPayout.getInventoryItemId());
|
|
|
1424 |
String serialNumber = ii.getSerialNumber().toLowerCase();
|
|
|
1425 |
ActivatedImei activatedImei = activatedImeiMap.get(serialNumber);
|
|
|
1426 |
if (activatedImei == null) {
|
|
|
1427 |
continue;
|
|
|
1428 |
}
|
|
|
1429 |
if (scheme.isWithinRange(activatedImei.getActivationTimestamp())) {
|
|
|
1430 |
int fofoId = ii.getFofoId();
|
|
|
1431 |
// Get latest order Id
|
|
|
1432 |
int orderId = scanRecordRepository.selectByInventoryItemId(ii.getId()).stream()
|
|
|
1433 |
.filter(x -> x.getOrderId() > 0)
|
|
|
1434 |
.sorted(Comparator.comparing(ScanRecord::getCreateTimestamp).reversed()).findFirst().get()
|
|
|
1435 |
.getOrderId();
|
|
|
1436 |
FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
|
| 31916 |
amit.gupta |
1437 |
|
| 31921 |
amit.gupta |
1438 |
InventoryPayoutModel inventoryPayoutModel = priceCircularService.getPayouts(ii);
|
| 31916 |
amit.gupta |
1439 |
AmountModel amountModel = new AmountModel();
|
|
|
1440 |
amountModel.setAmount(scheme.getAmount());
|
|
|
1441 |
amountModel.setAmountType(scheme.getAmountType());
|
| 31921 |
amit.gupta |
1442 |
double amountToRollout = inventoryPayoutModel.getRolloutAmount(amountModel);
|
| 32058 |
amit.gupta |
1443 |
pendingPayout.setAmount((float) amountToRollout);
|
| 34317 |
amit.gupta |
1444 |
walletService.addAmountToWallet(fofoId, orderId, WalletReferenceType.SPECIAL_SUPPORT,
|
|
|
1445 |
"Special Support for " + ii.getItem().getItemDescriptionNoColor() + ", Imei - " + serialNumber, (float) amountToRollout,
|
|
|
1446 |
fofoOrder.getCreateTimestamp());
|
|
|
1447 |
pendingPayout.setStatusDescription("Special support credited, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
|
|
|
1448 |
|
| 31410 |
amit.gupta |
1449 |
pendingPayout.setCreditTimestamp(LocalDateTime.now());
|
|
|
1450 |
pendingPayout.setStatus(SchemePayoutStatus.CREDITED);
|
|
|
1451 |
} else {
|
|
|
1452 |
pendingPayout.setStatus(SchemePayoutStatus.REJECTED);
|
|
|
1453 |
pendingPayout.setRolledBackTimestamp(LocalDateTime.now());
|
|
|
1454 |
pendingPayout.setStatusDescription(
|
|
|
1455 |
"Rejected, activated on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()));
|
|
|
1456 |
}
|
|
|
1457 |
}
|
|
|
1458 |
}
|
| 24976 |
amit.gupta |
1459 |
|
| 31410 |
amit.gupta |
1460 |
@Override
|
| 35629 |
amit |
1461 |
public void rejectActivatedSchemeIds(List<Integer> schemeIds) throws ProfitMandiBusinessException {
|
|
|
1462 |
List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectBySchemeIds(new HashSet<>(schemeIds));
|
|
|
1463 |
// Filter to CREDITED records that haven't been rolled back
|
|
|
1464 |
List<SchemeInOut> creditedPayouts = schemeInOuts.stream()
|
|
|
1465 |
.filter(x -> SchemePayoutStatus.CREDITED.equals(x.getStatus()) && x.getRolledBackTimestamp() == null)
|
|
|
1466 |
.collect(Collectors.toList());
|
|
|
1467 |
if (creditedPayouts.isEmpty()) return;
|
|
|
1468 |
|
|
|
1469 |
Map<Integer, Scheme> schemesMap = schemeRepository.selectBySchemeIds(schemeIds).stream()
|
|
|
1470 |
.filter(x -> SchemeType.SPECIAL_SUPPORT.equals(x.getType()))
|
|
|
1471 |
.collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
1472 |
creditedPayouts = creditedPayouts.stream().filter(x -> schemesMap.containsKey(x.getSchemeId()))
|
|
|
1473 |
.collect(Collectors.toList());
|
|
|
1474 |
if (creditedPayouts.isEmpty()) return;
|
|
|
1475 |
|
|
|
1476 |
Set<Integer> inventoryIds = creditedPayouts.stream().map(SchemeInOut::getInventoryItemId).collect(Collectors.toSet());
|
|
|
1477 |
Map<Integer, InventoryItem> inventoryItemMap = inventoryItemRepository.selectByIds(inventoryIds).stream()
|
|
|
1478 |
.collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
1479 |
List<String> serialNumbers = inventoryItemMap.values().stream().map(InventoryItem::getSerialNumber).collect(Collectors.toList());
|
|
|
1480 |
Map<String, ActivatedImei> activatedImeiMap = activatedImeiRepository.selectBySerialNumbers(serialNumbers).stream()
|
|
|
1481 |
.collect(Collectors.toMap(x -> x.getSerialNumber().toLowerCase(), x -> x, (a, b) -> a));
|
|
|
1482 |
|
|
|
1483 |
for (SchemeInOut payout : creditedPayouts) {
|
|
|
1484 |
Scheme scheme = schemesMap.get(payout.getSchemeId());
|
|
|
1485 |
InventoryItem ii = inventoryItemMap.get(payout.getInventoryItemId());
|
|
|
1486 |
if (ii == null) continue;
|
|
|
1487 |
ActivatedImei activatedImei = activatedImeiMap.get(ii.getSerialNumber().toLowerCase());
|
|
|
1488 |
if (activatedImei == null || activatedImei.getActivationTimestamp() == null) continue;
|
|
|
1489 |
|
|
|
1490 |
if (!scheme.isWithinRange(activatedImei.getActivationTimestamp())) {
|
|
|
1491 |
payout.setStatus(SchemePayoutStatus.REJECTED);
|
|
|
1492 |
payout.setRolledBackTimestamp(LocalDateTime.now());
|
|
|
1493 |
payout.setStatusDescription("Rejected, activation on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()) + " outside scheme period");
|
|
|
1494 |
|
|
|
1495 |
List<ScanRecord> scanRecords = scanRecordRepository.selectByInventoryItemId(ii.getId());
|
|
|
1496 |
int orderId = scanRecords.stream()
|
|
|
1497 |
.filter(x -> x.getOrderId() > 0)
|
|
|
1498 |
.sorted(Comparator.comparing(ScanRecord::getCreateTimestamp).reversed()).findFirst()
|
|
|
1499 |
.map(ScanRecord::getOrderId).orElse(0);
|
|
|
1500 |
if (orderId > 0) {
|
|
|
1501 |
walletService.rollbackAmountFromWallet(ii.getFofoId(), payout.getAmount(), orderId,
|
|
|
1502 |
WalletReferenceType.SPECIAL_SUPPORT,
|
|
|
1503 |
"Rejected, activation on " + FormattingUtils.formatDate(activatedImei.getActivationTimestamp()) + " outside scheme period",
|
|
|
1504 |
LocalDateTime.now());
|
|
|
1505 |
}
|
|
|
1506 |
}
|
|
|
1507 |
}
|
|
|
1508 |
}
|
|
|
1509 |
|
|
|
1510 |
@Override
|
| 31410 |
amit.gupta |
1511 |
public void processActivatedImeisForSchemes() throws ProfitMandiBusinessException {
|
|
|
1512 |
List<SchemesImeisModel> schemesImeisModels = schemeRepository.selectSelectUnpaidSchemes();
|
|
|
1513 |
LOGGER.info("Total Size - " + schemesImeisModels.size());
|
|
|
1514 |
List<Integer> orderIds = schemesImeisModels.stream().map(x -> x.getOrderId()).collect(Collectors.toList());
|
|
|
1515 |
List<FofoOrder> fofoOrders = fofoOrderRepository.selectAllByOrderIds(orderIds);
|
|
|
1516 |
Map<Integer, FofoOrder> validOrdersMap = fofoOrders.stream().filter(x -> x.getCancelledTimestamp() == null).collect(Collectors.toMap(x -> x.getId(), x -> x));
|
|
|
1517 |
Map<String, List<SchemesImeisModel>> validImeiSchemesModelMap = schemesImeisModels.stream().filter(x -> validOrdersMap.containsKey(x.getOrderId())).collect(Collectors.groupingBy(x -> x.getImei()));
|
| 35394 |
amit |
1518 |
|
|
|
1519 |
// Batch fetch all inventoryItems to avoid N+1 queries
|
|
|
1520 |
Set<Integer> inventoryItemIds = validImeiSchemesModelMap.values().stream()
|
|
|
1521 |
.map(list -> list.get(0).getInventoryItemId())
|
|
|
1522 |
.collect(Collectors.toSet());
|
|
|
1523 |
Map<Integer, InventoryItem> inventoryItemsMap = inventoryItemIds.isEmpty()
|
|
|
1524 |
? Collections.emptyMap()
|
|
|
1525 |
: inventoryItemRepository.selectAllByIds(new ArrayList<>(inventoryItemIds)).stream()
|
|
|
1526 |
.collect(Collectors.toMap(InventoryItem::getId, x -> x));
|
|
|
1527 |
|
| 31410 |
amit.gupta |
1528 |
for (Map.Entry<String, List<SchemesImeisModel>> imeiListEntry : validImeiSchemesModelMap.entrySet()) {
|
|
|
1529 |
SchemesImeisModel schemesImeisModel = imeiListEntry.getValue().get(0);
|
|
|
1530 |
List<Integer> schemeIds = imeiListEntry.getValue().stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
|
|
|
1531 |
LOGGER.info("Serial Number - {}, Scheme IDs - {}", schemesImeisModel.getImei(), schemeIds);
|
| 35394 |
amit |
1532 |
InventoryItem inventoryItem = inventoryItemsMap.get(schemesImeisModel.getInventoryItemId());
|
|
|
1533 |
if (inventoryItem == null) continue;
|
| 31410 |
amit.gupta |
1534 |
List<Scheme> schemes = schemeRepository.selectBySchemeIds(schemeIds);
|
| 34317 |
amit.gupta |
1535 |
List<Scheme> supportSchemes = schemes.stream().filter(x -> Arrays.asList(SchemeType.SPECIAL_SUPPORT).contains(x.getType())).collect(Collectors.toList());
|
| 31410 |
amit.gupta |
1536 |
if (supportSchemes.size() > 0) {
|
| 32165 |
amit.gupta |
1537 |
for (Scheme scheme : supportSchemes) {
|
|
|
1538 |
List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectByScheme(scheme.getId(), inventoryItem.getId());
|
| 32972 |
amit.gupta |
1539 |
if (schemeInOuts.stream().filter(x -> Arrays.asList(SchemePayoutStatus.CREDITED, SchemePayoutStatus.PENDING).contains(x.getStatus())).count() > 0) {
|
| 32165 |
amit.gupta |
1540 |
continue;
|
|
|
1541 |
}
|
|
|
1542 |
SchemeInOut sio = new SchemeInOut();
|
|
|
1543 |
sio.setAmount(0);
|
|
|
1544 |
sio.setInventoryItemId(inventoryItem.getId());
|
|
|
1545 |
sio.setSchemeId(scheme.getId());
|
|
|
1546 |
sio.setStatusDescription("Activation pending for IMEI#" + inventoryItem.getSerialNumber());
|
|
|
1547 |
sio.setStatus(SchemePayoutStatus.PENDING);
|
|
|
1548 |
schemeInOutRepository.persist(sio);
|
|
|
1549 |
}
|
| 31410 |
amit.gupta |
1550 |
}
|
|
|
1551 |
}
|
|
|
1552 |
}
|
| 36397 |
amit |
1553 |
|
|
|
1554 |
@Override
|
|
|
1555 |
public void updateSchemeItemWindow(long schemeItemId, LocalDateTime startDate, LocalDateTime endDate, int updatedBy)
|
|
|
1556 |
throws ProfitMandiBusinessException {
|
|
|
1557 |
SchemeItem item = schemeItemRepository.selectById(schemeItemId);
|
|
|
1558 |
if (item == null) {
|
|
|
1559 |
throw new ProfitMandiBusinessException("schemeItemId", String.valueOf(schemeItemId), "Scheme item not found");
|
|
|
1560 |
}
|
|
|
1561 |
|
|
|
1562 |
Scheme scheme = schemeRepository.selectById(item.getSchemeId());
|
|
|
1563 |
if (scheme == null) {
|
|
|
1564 |
throw new ProfitMandiBusinessException("schemeId", String.valueOf(item.getSchemeId()), "Scheme not found");
|
|
|
1565 |
}
|
|
|
1566 |
|
|
|
1567 |
if (startDate.isAfter(endDate)) {
|
|
|
1568 |
throw new ProfitMandiBusinessException("startDate, endDate",
|
|
|
1569 |
FormattingUtils.formatDate(startDate) + ", " + FormattingUtils.formatDate(endDate),
|
|
|
1570 |
"Start date must be before end date");
|
|
|
1571 |
}
|
|
|
1572 |
|
|
|
1573 |
// Containment: item window must be within scheme window
|
|
|
1574 |
if (startDate.isBefore(scheme.getStartDateTime()) || endDate.isAfter(scheme.getEndDateTime())) {
|
|
|
1575 |
throw new ProfitMandiBusinessException("startDate, endDate",
|
|
|
1576 |
FormattingUtils.formatDate(startDate) + ", " + FormattingUtils.formatDate(endDate),
|
|
|
1577 |
"Item dates must be within scheme window ["
|
|
|
1578 |
+ FormattingUtils.formatDate(scheme.getStartDateTime()) + " - "
|
|
|
1579 |
+ FormattingUtils.formatDate(scheme.getEndDateTime()) + "]");
|
|
|
1580 |
}
|
|
|
1581 |
|
|
|
1582 |
// Non-overlap check within same (catalogId, schemeId)
|
|
|
1583 |
if (schemeItemRepository.existsOverlapping(item.getCatalogId(), item.getSchemeId(), startDate, endDate, item.getId())) {
|
|
|
1584 |
throw new ProfitMandiBusinessException("startDate, endDate",
|
|
|
1585 |
FormattingUtils.formatDate(startDate) + ", " + FormattingUtils.formatDate(endDate),
|
|
|
1586 |
"Date range overlaps with existing entry for this model in this scheme");
|
|
|
1587 |
}
|
|
|
1588 |
|
|
|
1589 |
item.setStartDate(startDate);
|
|
|
1590 |
item.setEndDate(endDate);
|
|
|
1591 |
item.setUpdatedBy(updatedBy);
|
|
|
1592 |
item.setUpdatedOn(LocalDateTime.now());
|
|
|
1593 |
schemeItemRepository.persist(item);
|
|
|
1594 |
}
|
|
|
1595 |
|
|
|
1596 |
@Override
|
|
|
1597 |
public SchemeItem addSchemeItemWithDates(int schemeId, int catalogId, LocalDateTime startDate, LocalDateTime endDate, int createdBy)
|
|
|
1598 |
throws ProfitMandiBusinessException {
|
|
|
1599 |
Scheme scheme = schemeRepository.selectById(schemeId);
|
|
|
1600 |
if (scheme == null) {
|
|
|
1601 |
throw new ProfitMandiBusinessException("schemeId", String.valueOf(schemeId), "Scheme not found");
|
|
|
1602 |
}
|
|
|
1603 |
|
|
|
1604 |
if (startDate.isAfter(endDate)) {
|
|
|
1605 |
throw new ProfitMandiBusinessException("startDate, endDate",
|
|
|
1606 |
FormattingUtils.formatDate(startDate) + ", " + FormattingUtils.formatDate(endDate),
|
|
|
1607 |
"Start date must be before end date");
|
|
|
1608 |
}
|
|
|
1609 |
|
|
|
1610 |
// Containment
|
|
|
1611 |
if (startDate.isBefore(scheme.getStartDateTime()) || endDate.isAfter(scheme.getEndDateTime())) {
|
|
|
1612 |
throw new ProfitMandiBusinessException("startDate, endDate",
|
|
|
1613 |
FormattingUtils.formatDate(startDate) + ", " + FormattingUtils.formatDate(endDate),
|
|
|
1614 |
"Item dates must be within scheme window ["
|
|
|
1615 |
+ FormattingUtils.formatDate(scheme.getStartDateTime()) + " - "
|
|
|
1616 |
+ FormattingUtils.formatDate(scheme.getEndDateTime()) + "]");
|
|
|
1617 |
}
|
|
|
1618 |
|
|
|
1619 |
// Non-overlap
|
|
|
1620 |
if (schemeItemRepository.existsOverlapping(catalogId, schemeId, startDate, endDate, 0)) {
|
|
|
1621 |
throw new ProfitMandiBusinessException("startDate, endDate",
|
|
|
1622 |
FormattingUtils.formatDate(startDate) + ", " + FormattingUtils.formatDate(endDate),
|
|
|
1623 |
"Date range overlaps with existing entry for this model in this scheme");
|
|
|
1624 |
}
|
|
|
1625 |
|
|
|
1626 |
SchemeItem item = new SchemeItem();
|
|
|
1627 |
item.setSchemeId(schemeId);
|
|
|
1628 |
item.setCatalogId(catalogId);
|
|
|
1629 |
item.setStartDate(startDate);
|
|
|
1630 |
item.setEndDate(endDate);
|
|
|
1631 |
item.setCreateTimestamp(LocalDateTime.now());
|
|
|
1632 |
item.setUpdatedBy(createdBy);
|
|
|
1633 |
item.setUpdatedOn(LocalDateTime.now());
|
|
|
1634 |
schemeItemRepository.persist(item);
|
|
|
1635 |
return item;
|
|
|
1636 |
}
|
|
|
1637 |
|
|
|
1638 |
@Override
|
|
|
1639 |
public List<SchemeItem> clampSchemeItems(int schemeId, LocalDateTime newStart, LocalDateTime newEnd, int updatedBy)
|
|
|
1640 |
throws ProfitMandiBusinessException {
|
|
|
1641 |
List<SchemeItem> outsideItems = schemeItemRepository.selectItemsOutsideWindow(schemeId, newStart, newEnd);
|
|
|
1642 |
List<SchemeItem> clamped = new ArrayList<>();
|
|
|
1643 |
|
|
|
1644 |
for (SchemeItem item : outsideItems) {
|
|
|
1645 |
LocalDateTime clampedStart = item.getStartDate().isBefore(newStart) ? newStart : item.getStartDate();
|
|
|
1646 |
LocalDateTime clampedEnd = item.getEndDate().isAfter(newEnd) ? newEnd : item.getEndDate();
|
|
|
1647 |
|
|
|
1648 |
if (clampedStart.isAfter(clampedEnd) || clampedStart.isEqual(clampedEnd)) {
|
|
|
1649 |
throw new ProfitMandiBusinessException("schemeId, catalogId",
|
|
|
1650 |
schemeId + ", " + item.getCatalogId(),
|
|
|
1651 |
"Cannot clamp: item window for catalogId " + item.getCatalogId()
|
|
|
1652 |
+ " (" + FormattingUtils.formatDate(item.getStartDate()) + " - " + FormattingUtils.formatDate(item.getEndDate()) + ")"
|
|
|
1653 |
+ " falls entirely outside new scheme window ("
|
|
|
1654 |
+ FormattingUtils.formatDate(newStart) + " - " + FormattingUtils.formatDate(newEnd)
|
|
|
1655 |
+ "). Adjust this item first.");
|
|
|
1656 |
}
|
|
|
1657 |
|
|
|
1658 |
item.setStartDate(clampedStart);
|
|
|
1659 |
item.setEndDate(clampedEnd);
|
|
|
1660 |
item.setUpdatedBy(updatedBy);
|
|
|
1661 |
item.setUpdatedOn(LocalDateTime.now());
|
|
|
1662 |
schemeItemRepository.persist(item);
|
|
|
1663 |
clamped.add(item);
|
|
|
1664 |
}
|
|
|
1665 |
return clamped;
|
|
|
1666 |
}
|
| 22653 |
ashik.ali |
1667 |
}
|