Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
22980 ashik.ali 1
package com.spice.profitmandi.service.user;
2
 
26528 amit.gupta 3
import com.google.common.hash.Hashing;
30097 tejbeer 4
import com.spice.profitmandi.common.enumuration.ActivationType;
5
import com.spice.profitmandi.common.enumuration.FofoType;
22980 ashik.ali 6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30017 amit.gupta 7
import com.spice.profitmandi.common.model.*;
23329 ashik.ali 8
import com.spice.profitmandi.common.util.StringUtils;
9
import com.spice.profitmandi.common.util.Utils;
22980 ashik.ali 10
import com.spice.profitmandi.dao.entity.dtr.User;
30017 amit.gupta 11
import com.spice.profitmandi.dao.entity.dtr.*;
12
import com.spice.profitmandi.dao.entity.fofo.*;
24349 amit.gupta 13
import com.spice.profitmandi.dao.entity.inventory.State;
33124 ranu 14
import com.spice.profitmandi.dao.entity.logistics.AST;
15
import com.spice.profitmandi.dao.entity.logistics.ASTRepository;
30017 amit.gupta 16
import com.spice.profitmandi.dao.entity.user.*;
23063 ashik.ali 17
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
23106 ashik.ali 18
import com.spice.profitmandi.dao.enumuration.dtr.RetailerType;
23136 ashik.ali 19
import com.spice.profitmandi.dao.enumuration.dtr.RoleType;
23365 ashik.ali 20
import com.spice.profitmandi.dao.enumuration.fofo.PaymentOptionType;
29042 tejbeer 21
import com.spice.profitmandi.dao.enumuration.transaction.PartnerVerificationApprovalStatus;
34813 aman 22
import com.spice.profitmandi.dao.model.LastMonthCreditedIncomeModel;
22980 ashik.ali 23
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
30017 amit.gupta 24
import com.spice.profitmandi.dao.repository.dtr.*;
34813 aman 25
import com.spice.profitmandi.dao.repository.fofo.*;
24349 amit.gupta 26
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
30017 amit.gupta 27
import com.spice.profitmandi.dao.repository.user.*;
33124 ranu 28
import com.spice.profitmandi.service.PostOfficeService;
23043 ashik.ali 29
import in.shop2020.model.v1.user.CartStatus;
30017 amit.gupta 30
import org.apache.logging.log4j.LogManager;
31
import org.apache.logging.log4j.Logger;
32
import org.springframework.beans.factory.annotation.Autowired;
33
import org.springframework.beans.factory.annotation.Qualifier;
34
import org.springframework.cache.annotation.Cacheable;
35
import org.springframework.stereotype.Component;
23043 ashik.ali 36
 
30017 amit.gupta 37
import java.nio.charset.StandardCharsets;
34813 aman 38
import java.time.LocalDate;
30017 amit.gupta 39
import java.time.LocalDateTime;
34813 aman 40
import java.time.YearMonth;
41
import java.time.format.DateTimeFormatter;
30017 amit.gupta 42
import java.util.*;
43
import java.util.function.Function;
44
import java.util.stream.Collectors;
45
import java.util.stream.Stream;
46
 
22980 ashik.ali 47
@Component
48
public class RetailerServiceImpl implements RetailerService {
23955 govind 49
 
31734 tejbeer 50
    private static final Logger LOGGER = LogManager.getLogger(RetailerServiceImpl.class);
23955 govind 51
 
31734 tejbeer 52
    @Autowired
53
    private RetailerRepository retailerRepository;
23955 govind 54
 
31734 tejbeer 55
    @Autowired
56
    private RetailerBlockBrandsRepository retailerBlockBrandsRepository;
28024 tejbeer 57
 
31734 tejbeer 58
    @Autowired
59
    private UserAccountRepository userAccountRepository;
23955 govind 60
 
31734 tejbeer 61
    @Autowired
62
    private Mongo mongoClient;
28024 tejbeer 63
 
31734 tejbeer 64
    @Autowired
65
    private UserRepository userRepository;
23955 govind 66
 
31734 tejbeer 67
    @Autowired
68
    private CartRepository cartRepository;
23955 govind 69
 
31734 tejbeer 70
    @Autowired
71
    private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
23955 govind 72
 
31734 tejbeer 73
    @Autowired
74
    private AddressRepository addressRepository;
23955 govind 75
 
31734 tejbeer 76
    @Autowired
77
    private ShopRepository shopRepository;
23955 govind 78
 
31734 tejbeer 79
    @Autowired
80
    private ShopAddressRepository shopAddressRepository;
23955 govind 81
 
31734 tejbeer 82
    @Autowired
83
    private UserRoleRepository userRoleRepository;
23955 govind 84
 
31734 tejbeer 85
    @Autowired
86
    private DocumentRepository documentRepository;
23955 govind 87
 
31734 tejbeer 88
    @Autowired
89
    private PrivateDealUserRepository privateDealUserRepository;
23955 govind 90
 
31734 tejbeer 91
    @Autowired
32737 amit.gupta 92
    private RetailerContactRepository retailerContactRepository;
93
 
94
    @Autowired
31734 tejbeer 95
    private PrivateDealUserAddressMappingRepository privateDealUserAddressMappingRepository;
23955 govind 96
 
31734 tejbeer 97
    @Autowired
98
    private CounterRepository counterRepository;
25295 amit.gupta 99
 
31734 tejbeer 100
    @Autowired
101
    private StateRepository stateRepository;
23955 govind 102
 
31734 tejbeer 103
    @Autowired
104
    @Qualifier("userUserRepository")
105
    private com.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;
23955 govind 106
 
31734 tejbeer 107
    @Autowired
108
    private DistrictMasterRepository districtMasterRepository;
23955 govind 109
 
31734 tejbeer 110
    @Autowired
111
    private FofoStoreRepository fofoStoreRepository;
23955 govind 112
 
31734 tejbeer 113
    @Autowired
33124 ranu 114
    private ASTRepository aSTRepository;
115
 
116
    @Autowired
117
    private PostOfficeService postOfficeService;
118
 
119
    @Autowired
31734 tejbeer 120
    private PaymentOptionRepository paymentOptionRepository;
23955 govind 121
 
31734 tejbeer 122
    @Autowired
123
    private FofoPartnerPaymentOptionRepository fofoPartnerPaymentOptionRepository;
23955 govind 124
 
31734 tejbeer 125
    @Autowired
126
    private RoleRepository roleRepository;
23955 govind 127
 
31734 tejbeer 128
    @Autowired
129
    private StoreTimelineTatService storeTimelineTatService;
28908 tejbeer 130
 
31734 tejbeer 131
    @Autowired
132
    private PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
28908 tejbeer 133
 
31734 tejbeer 134
    @Autowired
135
    private PartnerOnboardingVerificationRepository partnerOnboardingVerificationRepository;
29042 tejbeer 136
 
31734 tejbeer 137
    @Autowired
138
    private PincodePartnerRepository pincodePartnerRepository;
30719 tejbeer 139
 
34813 aman 140
    @Autowired
141
    SchemeInOutRepository schemeInOutRepository;
142
 
143
    @Autowired
144
    OfferPayoutRepository offerPayoutRepository;
145
 
146
    @Autowired
147
    PartnerTypeChangeService partnerTypeChangeService;
148
 
31734 tejbeer 149
    @Override
150
    public Map<String, Object> getByEmailIdOrMobileNumber(String emailIdOrMobileNumber) throws ProfitMandiBusinessException {
151
        User user = null;
152
        int fofoId = Utils.SYSTEM_PARTNER_ID;
28024 tejbeer 153
 
31734 tejbeer 154
        try {
155
            user = userRepository.selectByEmailIdOrMobileNumber(emailIdOrMobileNumber);
156
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
23955 govind 157
 
31734 tejbeer 158
        }
159
        if (user == null) {
160
            try {
161
                user = userRepository.selectBySecondryEmailId(emailIdOrMobileNumber);
162
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
23955 govind 163
 
31734 tejbeer 164
            }
165
        }
166
        Map<String, Object> map = new HashMap<>();
167
        map.put("stateNames", stateRepository.selectAll().stream().map(x -> x.getName()).collect(Collectors.toList()));
23955 govind 168
 
31734 tejbeer 169
        if (user != null) {
23955 govind 170
 
31734 tejbeer 171
            List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
23955 govind 172
 
31734 tejbeer 173
            Role role = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 174
 
31734 tejbeer 175
            map.put("userRoles", userRoles);
176
            map.put("user", user);
177
            // map.put("retailer", retailer);
178
            map.put("fofoRole", this.containsRoleType(userRoles, role.getId()));
23955 govind 179
 
31734 tejbeer 180
            map.put("userRoleNames", this.toString(userRoles));
181
            try {
182
                int retailerId = userAccountRepository.selectRetailerIdByUserId(user.getId());
183
                Retailer retailer = retailerRepository.selectById(retailerId);
23955 govind 184
 
31734 tejbeer 185
                map.put("retailer", retailer);
23955 govind 186
 
31734 tejbeer 187
                List<String> retailerBlockBrands = null;
188
                Set<String> brands = null;
189
                if (retailer.getId() != fofoId) {
190
                    brands = mongoClient.getMongoBrands(retailer.getId(), null, 3).stream().map(x -> (String) x.get("name")).collect(Collectors.toSet());
191
                    retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream().map(x -> x.getBlockBrands()).collect(Collectors.toList());
28189 tejbeer 192
 
31734 tejbeer 193
                    LOGGER.info("loginDetailsFofoId" + retailer.getId());
194
                } else {
195
                    LOGGER.info("fofoId" + fofoId);
196
                    brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name")).collect(Collectors.toSet());
197
                }
198
                map.put("brands", brands);
199
                map.put("retailerBlockBrands", retailerBlockBrands);
23955 govind 200
 
31734 tejbeer 201
                try {
202
                    PrivateDealUser privateDealUser = privateDealUserRepository.selectById(retailer.getId());
203
                    if (privateDealUser.getCounterId() != null) {
204
                        Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
205
                        map.put("gstNumber", counter.getGstin());
206
                        // LOGGER.info("gstNumber" + counter.getGstin());
207
                    }
208
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
209
                    LOGGER.error("PrivateDealUser not found");
210
                }
211
                try {
212
                    int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId());
213
                    Address retailerAddress = addressRepository.selectById(retailerAddressId);
214
                    map.put("retailerAddress", retailerAddress);
215
                    State state = stateRepository.selectByName(retailerAddress.getState());
216
                    // LOGGER.info("retailerAddress.." + retailerAddress);
217
                    List<DistrictMaster> districtMasters = districtMasterRepository.selectByStateShortName(state.getShortName());
218
                    map.put("districtMasters", districtMasters);
219
                    // LOGGER.info("districtMasters" + districtMasters);
220
                    List<Shop> shops = shopRepository.selectByRetailerId(retailer.getId());
221
                    map.put("shops", shops);
222
                    this.addAddress(shops);
33128 amit.gupta 223
 
224
                    if (this.containsRoleType(userRoles, role.getId())) {
225
                        try {
226
                            FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
227
                            map.put("fofoStore", fofoStore);
228
                            List<AST> astDetail = postOfficeService.getAreasAndTerritoriesByStateName(retailerAddress.getState());
229
                            LOGGER.info("astDetail {}", astDetail);
230
                            map.put("astDetail", astDetail);
231
 
232
 
233
                            // map.put("counterSize", fofoStore.getCounterSize().toString());
234
                            // LOGGER.info("fofoStore" + fofoStore);
235
                        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
236
                            LOGGER.error("FofoStore code not found");
237
                        }
238
                    }
31734 tejbeer 239
                    // LOGGER.info("shops" + shops);
240
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
241
                    LOGGER.error("Retailer Registered Address not found");
242
                }
243
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
244
                LOGGER.error("Retailer not found in user_account");
245
            }
246
        }
23955 govind 247
 
31734 tejbeer 248
        return map;
249
    }
23955 govind 250
 
31734 tejbeer 251
    private boolean containsRoleType(List<UserRole> userRoles, int roleId) {
252
        for (UserRole userRole : userRoles) {
253
            if (userRole.getRoleId() == roleId) {
254
                return true;
255
            }
256
        }
257
        return false;
258
    }
23955 govind 259
 
31734 tejbeer 260
    private List<UserRole> addRole(List<UserRole> userRoles, int userId, int roleId) {
261
        if (userRoles == null) {
262
            userRoles = new ArrayList<>();
263
        }
264
        if (!this.containsRoleType(userRoles, roleId)) {
265
            UserRole userRole = new UserRole();
266
            userRole.setUserId(userId);
267
            userRole.setRoleId(roleId);
268
            try {
269
                userRoleRepository.persist(userRole);
270
            } catch (ProfitMandiBusinessException e) {
271
                LOGGER.error("UserRole is already exist");
272
            }
273
            userRoles.add(userRole);
274
        }
275
        return userRoles;
23955 govind 276
 
31734 tejbeer 277
    }
23955 govind 278
 
31734 tejbeer 279
    private List<UserRole> removeRole(List<UserRole> userRoles, int userId, int roleId) {
280
        if (userRoles == null) {
281
            userRoles = new ArrayList<>();
282
            return userRoles;
283
        }
284
        try {
285
            userRoles.remove(userRoleRepository.deleteByRoleUserId(userId, roleId));
286
        } catch (Exception e) {
25295 amit.gupta 287
 
31734 tejbeer 288
        }
289
        return userRoles;
25295 amit.gupta 290
 
31734 tejbeer 291
    }
25295 amit.gupta 292
 
31734 tejbeer 293
    @SuppressWarnings("unchecked")
294
    @Override
33128 amit.gupta 295
    public Map<String, Object> updateRetailerDetails(UpdateRetailerRequest updateRetailerRequest) throws
296
            ProfitMandiBusinessException {
31734 tejbeer 297
        Map<String, Object> map = this.getByEmailIdOrMobileNumber(updateRetailerRequest.getEmailIdOrMobileNumber());
32953 amit.gupta 298
        User dtrUser = (User) map.get("user");
28024 tejbeer 299
 
32953 amit.gupta 300
        dtrUser = this.createUser(dtrUser, updateRetailerRequest);
28024 tejbeer 301
 
32953 amit.gupta 302
        map.put("user", dtrUser);
31734 tejbeer 303
        List<UserRole> userRoles = (List<UserRole>) map.get("userRoles");
304
        Role roleUser = roleRepository.selectByName(RoleType.USER.toString());
32953 amit.gupta 305
        userRoles = this.addRole(userRoles, dtrUser.getId(), roleUser.getId());
31734 tejbeer 306
        Retailer retailer = (Retailer) map.get("retailer");
32953 amit.gupta 307
        retailer = this.updateRetailer(dtrUser, retailer, updateRetailerRequest);
28024 tejbeer 308
 
31734 tejbeer 309
        map.put("retailer", retailer);
23955 govind 310
 
31734 tejbeer 311
        List<String> retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream().map(x -> x.getBlockBrands()).collect(Collectors.toList());
28024 tejbeer 312
 
31734 tejbeer 313
        LOGGER.info("retailerBlockBrands" + retailerBlockBrands);
28189 tejbeer 314
 
31734 tejbeer 315
        if (!retailerBlockBrands.isEmpty()) {
316
            retailerBlockBrandsRepository.deleteBrands(retailer.getId());
317
        }
28024 tejbeer 318
 
31734 tejbeer 319
        for (String blockBrand : updateRetailerRequest.getBlocksBrands()) {
320
            RetailerBlockBrands retailerBlockBrand = new RetailerBlockBrands();
28024 tejbeer 321
 
31734 tejbeer 322
            retailerBlockBrand.setFofoId(retailer.getId());
323
            retailerBlockBrand.setBlockBrands(blockBrand);
324
            retailerBlockBrandsRepository.persist(retailerBlockBrand);
28024 tejbeer 325
 
31734 tejbeer 326
        }
327
        map.put("retailerBlockBrands", retailerBlockBrands);
28024 tejbeer 328
 
31734 tejbeer 329
        Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
23955 govind 330
 
32953 amit.gupta 331
        userRoles = this.addRole(userRoles, dtrUser.getId(), roleRetailer.getId());
23955 govind 332
 
31734 tejbeer 333
        Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 334
 
31734 tejbeer 335
        if (updateRetailerRequest.isFofo()) {
32953 amit.gupta 336
            userRoles = this.addRole(userRoles, dtrUser.getId(), roleFofo.getId());
31734 tejbeer 337
        } else {
32953 amit.gupta 338
            userRoles = this.removeRole(userRoles, dtrUser.getId(), roleFofo.getId());
31734 tejbeer 339
        }
340
        map.put("fofoRole", this.containsRoleType(userRoles, roleFofo.getId()));
23955 govind 341
 
31734 tejbeer 342
        if (this.containsRoleType(userRoles, roleFofo.getId())) {
343
            this.createDefaultPaymentOption(retailer.getId());
344
        }
23955 govind 345
 
31734 tejbeer 346
        map.put("userRoles", userRoles);
347
        map.put("userRoleNames", this.toString(userRoles));
23955 govind 348
 
31734 tejbeer 349
        Address retailerAddress = (Address) map.get("retailerAddress");
350
        retailerAddress = this.updateRetailerAddress(retailerAddress, updateRetailerRequest.getAddress(), retailer.getId());
351
        map.put("retailerAddress", retailerAddress);
23955 govind 352
 
31734 tejbeer 353
        if (updateRetailerRequest.isFofo()) {
354
            FofoStore fofoStore = this.createFofoStoreCodeByRetailerId(retailer.getId(), updateRetailerRequest.getDistrictName(), retailerAddress.getState(), updateRetailerRequest);
355
            map.put("fofoStore", fofoStore);
356
            fofoStore.setActive(updateRetailerRequest.isActive());
33131 ranu 357
            List<AST> astDetail = postOfficeService.getAreasAndTerritoriesByStateName(retailerAddress.getState());
358
            map.put("astDetail", astDetail);
31734 tejbeer 359
        }
23955 govind 360
 
32953 amit.gupta 361
        this.createPrivateDealUser(dtrUser, updateRetailerRequest.isFofo(), updateRetailerRequest.getGstNumber(), retailer, retailerAddress.getId());
31734 tejbeer 362
        map.put("gstNumber", updateRetailerRequest.getGstNumber());
363
        this.updateSaholicUser(retailer.getId(), retailerAddress.getId());
23955 govind 364
 
31734 tejbeer 365
        List<Shop> shops = (List<Shop>) map.get("shops");
366
        if (shops == null) {
367
            shops = new ArrayList<>();
368
            map.put("shops", shops);
369
        }
370
        this.updateRetailerShops(shops, updateRetailerRequest.getShops(), retailer.getId(), retailerAddress);
23955 govind 371
 
31734 tejbeer 372
        return map;
23955 govind 373
 
31734 tejbeer 374
    }
23955 govind 375
 
31734 tejbeer 376
    private void createDefaultPaymentOption(int fofoId) {
377
        List<Integer> paymentOptionIds = fofoPartnerPaymentOptionRepository.selectPaymentOptionIdsByFofoId(fofoId);
378
        if (paymentOptionIds.isEmpty()) {
379
            PaymentOption paymentOption = null;
380
            try {
381
                paymentOption = paymentOptionRepository.selectByName(PaymentOptionType.CASH.toString());
382
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
383
                paymentOption = new PaymentOption();
384
                paymentOption.setName(PaymentOptionType.CASH.toString());
385
                paymentOptionRepository.persist(paymentOption);
386
            }
387
            FofoPartnerPaymentOption fofoPartnerPaymentOption = new FofoPartnerPaymentOption();
388
            fofoPartnerPaymentOption.setFofoId(fofoId);
389
            fofoPartnerPaymentOption.setPaymentOptionId(paymentOption.getId());
390
            fofoPartnerPaymentOptionRepository.persist(fofoPartnerPaymentOption);
391
        }
23955 govind 392
 
31734 tejbeer 393
    }
23955 govind 394
 
33128 amit.gupta 395
    private User createUser(User user, UpdateRetailerRequest updateRetailerRequest) throws
396
            ProfitMandiBusinessException {
32965 amit.gupta 397
 
398
        User dtrUser = null;
399
        try {
400
            dtrUser = userRepository.selectByMobileNumber(updateRetailerRequest.getUserMobileNumber());
401
        } catch (ProfitMandiBusinessException e) {
402
            //Ignore the exception
403
        }
33140 ranu 404
        if (dtrUser != null && (user == null || user.getId() != dtrUser.getId()))
405
            throw new ProfitMandiBusinessException("Mobile already exist", updateRetailerRequest.getUserMobileNumber(), dtrUser.getEmailId());
32966 amit.gupta 406
 
407
        User dtrUserByEmail = null;
408
        try {
409
            dtrUserByEmail = userRepository.selectByEmailId(updateRetailerRequest.getUserEmailId());
410
        } catch (ProfitMandiBusinessException e) {
411
            //ignore the exception
412
        }
33025 amit.gupta 413
        if (user != null && dtrUserByEmail != null && user.getId() != dtrUserByEmail.getId())
32965 amit.gupta 414
            throw new ProfitMandiBusinessException("Email already exist", updateRetailerRequest.getUserEmailId(), "");
32953 amit.gupta 415
 
416
 
31734 tejbeer 417
        if (user == null) {
418
            user = new User();
419
            user.setCity("");
420
            user.setPinCode(0);
421
            user.setState("");
422
            user.setPassword("");
423
            user.setMobile_verified(false);
424
            user.setReferral_url("");
425
            user.setGroup_id(1);
426
            user.setStatus(1);
427
            user.setActivated(true);
428
            user.setCreateTimestamp(LocalDateTime.now());
429
        }
430
        user.setActivated(updateRetailerRequest.isActive());
431
        user.setFirstName(updateRetailerRequest.getUserFirstName());
432
        user.setLastName(updateRetailerRequest.getUserLastName());
433
        user.setMobileNumber(updateRetailerRequest.getUserMobileNumber());
434
        user.setEmailId(updateRetailerRequest.getUserEmailId());
435
        user.setUsername(updateRetailerRequest.getUserEmailId());
436
        user.setUpdateTimestamp(LocalDateTime.now());
437
        userRepository.persist(user);
438
        return user;
23955 govind 439
 
31734 tejbeer 440
    }
23955 govind 441
 
31734 tejbeer 442
    private int createSaholicUser(User user, String retailerName) {
443
        com.spice.profitmandi.dao.entity.user.User saholicUser = null;
444
        try {
445
            saholicUser = userUserRepository.selectByEmailId(user.getEmailId());
446
        } catch (ProfitMandiBusinessException e) {
447
            LOGGER.info("User doesnt exist in old system");
448
        }
449
        if (saholicUser == null) {
450
            Cart cart = new Cart();
451
            cart.setCartStatus(CartStatus.ACTIVE);
452
            cartRepository.persist(cart);
453
            saholicUser = new com.spice.profitmandi.dao.entity.user.User();
454
            saholicUser.setEmailId(user.getEmailId());
455
            saholicUser.setName(retailerName);
456
            saholicUser.setActiveCartId(cart.getId());
457
            saholicUser.setCreateTimestamp(LocalDateTime.now());
458
            userUserRepository.persist(saholicUser);
23955 govind 459
 
31734 tejbeer 460
            UserAccount ua = new UserAccount();
461
            ua.setAccountKey(saholicUser.getId());
462
            ua.setUserId(user.getId());
463
            ua.setType(AccountType.saholic);
464
            userAccountRepository.persist(ua);
23063 ashik.ali 465
 
31734 tejbeer 466
            UserAccount ua2 = new UserAccount();
467
            ua2.setAccountKey(saholicUser.getActiveCartId());
468
            ua2.setUserId(user.getId());
469
            ua2.setType(AccountType.cartId);
470
            userAccountRepository.persist(ua2);
471
            LOGGER.info("created....");
472
        }
473
        return saholicUser.getId();
474
    }
23955 govind 475
 
31734 tejbeer 476
    private com.spice.profitmandi.dao.entity.user.User createSaholicUser(
32953 amit.gupta 477
            LoginRequestResponseModel loginRequestResponseModel) {
31734 tejbeer 478
        com.spice.profitmandi.dao.entity.user.User saholicUser = null;
479
        try {
480
            saholicUser = userUserRepository.selectByEmailId(loginRequestResponseModel.getEmail());
481
            saholicUser.setCreateTimestamp(LocalDateTime.now());
482
        } catch (ProfitMandiBusinessException e) {
483
            LOGGER.info("User doesnt exist in old system");
484
        }
485
        if (saholicUser == null) {
486
            Cart cart = new Cart();
487
            cart.setCartStatus(CartStatus.ACTIVE);
488
            cartRepository.persist(cart);
489
            saholicUser = new com.spice.profitmandi.dao.entity.user.User();
490
            saholicUser.setPassword(getHash256(loginRequestResponseModel.getPassword()));
491
            saholicUser.setEmailId(loginRequestResponseModel.getEmail());
492
            saholicUser.setName(loginRequestResponseModel.getCustomerName());
493
            saholicUser.setActiveCartId(cart.getId());
494
            saholicUser.setCreateTimestamp(LocalDateTime.now());
495
            loginRequestResponseModel.setPassword(null);
496
            userUserRepository.persist(saholicUser);
497
        }
498
        return saholicUser;
499
    }
26522 amit.gupta 500
 
33128 amit.gupta 501
    private Retailer updateRetailer(User user, Retailer retailer, UpdateRetailerRequest updateRetailerRequest) throws
502
            ProfitMandiBusinessException {
31734 tejbeer 503
        if (retailer == null) {
504
            LOGGER.info("createSaholicUser.....");
505
            int saholicUserId = this.createSaholicUser(user, updateRetailerRequest.getName());
506
            retailer = new Retailer();
507
            retailer.setId(saholicUserId);
508
        }
509
        retailer.setActive(updateRetailerRequest.isActive());
510
        user.setActivated(updateRetailerRequest.isActive());//
511
        // this.createRole(user.getId(), RoleType.RETAILER);
512
        retailer.setName(updateRetailerRequest.getName());
513
        retailer.setNumber(updateRetailerRequest.getNumber());
514
        if (updateRetailerRequest.getNumber() == null || updateRetailerRequest.getNumber().isEmpty()) {
515
            retailer.setType(RetailerType.UNREGISTERED_SHOP);
516
        } else {
517
            retailer.setType(RetailerType.GSTIN);
518
        }
519
        if (updateRetailerRequest.getDocumentId() > 0) {
520
            if (retailer.getDocumentId() != null && retailer.getDocumentId() != updateRetailerRequest.getDocumentId()) {
521
                try {
522
                    documentRepository.deleteById(retailer.getDocumentId());
523
                } catch (Exception e) {
524
                    e.printStackTrace();
525
                }
526
            }
527
            retailer.setDocumentId(updateRetailerRequest.getDocumentId());
528
            documentRepository.markDocumentAsPersisted(updateRetailerRequest.getDocumentId());
529
        }
530
        retailerRepository.persist(retailer);
531
        return retailer;
532
    }
23955 govind 533
 
31734 tejbeer 534
    private void updateSaholicUser(int retailerId, int retailerAddressId) {
535
        try {
536
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(retailerId);
537
            user.setAddressId(retailerAddressId);
32555 amit.gupta 538
            Cart cart = cartRepository.selectById(user.getActiveCartId());
539
            cart.setAddressId(retailerAddressId);
31734 tejbeer 540
        } catch (ProfitMandiBusinessException e) {
23955 govind 541
 
31734 tejbeer 542
        }
543
    }
23955 govind 544
 
33128 amit.gupta 545
    private void createPrivateDealUser(User user, boolean fofo, String gstNumber, Retailer retailer,
546
                                       int retailerAddressId) {
31734 tejbeer 547
        PrivateDealUser privateDealUser = null;
548
        try {
549
            privateDealUser = privateDealUserRepository.selectById(retailer.getId());
550
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
551
            LOGGER.error("PrivateDealUser not found");
552
        }
23955 govind 553
 
31734 tejbeer 554
        // = privateDealUserRepository.selectById(saholicUser.getId());
555
        if (privateDealUser == null) {
556
            Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
557
            try {
558
                this.createPrivateDealUser(retailer.getId(), counterId, fofo);
559
            } catch (Exception e) {
560
                LOGGER.error("ERROR : ", e);
561
            }
562
        } else {
563
            if (privateDealUser.getCounterId() == null) {
564
                Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
565
                privateDealUser.setCounterId(counterId);
566
                privateDealUser.setFofo(fofo);
567
                privateDealUserRepository.persist(privateDealUser);
568
            } else {
569
                Counter counter = null;
570
                try {
571
                    counter = counterRepository.selectById(privateDealUser.getCounterId());
572
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
573
                    LOGGER.error("Counter not found with id [{}]", privateDealUser.getCounterId());
574
                }
575
                if (counter == null) {
576
                    this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
577
                } else {
578
                    counter.setGstin(gstNumber);
579
                    counterRepository.persist(counter);
580
                }
581
                privateDealUser.setFofo(fofo);
582
                privateDealUserRepository.persist(privateDealUser);
583
            }
584
        }
23955 govind 585
 
31734 tejbeer 586
        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
587
        privateDealUserAddressMapping.setUserId(retailer.getId());
588
        privateDealUserAddressMapping.setAddressId(retailerAddressId);
589
        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
590
    }
23955 govind 591
 
31734 tejbeer 592
    // Specifically set isFofo to true that has to be used by old system
593
    private void createPrivateDealUser(int retailerId, int counterId, boolean fofo) {
594
        PrivateDealUser privateDealUser = new PrivateDealUser();
595
        privateDealUser.setActive(true);
596
        privateDealUser.setBulkShipmentAmountLimit(fofo ? 1000000 : 50000);
597
        privateDealUser.setId(retailerId);
598
        privateDealUser.setCounterId(counterId);
599
        privateDealUser.setFofo(fofo);
600
        privateDealUserRepository.persist(privateDealUser);
601
    }
23955 govind 602
 
31734 tejbeer 603
    private Integer createCounter(String emailId, String gstNumber, String mobileNumber, String name, int addressId) {
604
        if (gstNumber != null && !gstNumber.isEmpty()) {
605
            Counter counter = new Counter();
606
            counter.setEmailId(emailId);
607
            counter.setGstin(gstNumber);
608
            counter.setMobileNumber(mobileNumber);
609
            counter.setName(name);
610
            counter.setAddressId(addressId);
611
            counterRepository.persist(counter);
612
            return counter.getId();
613
        } else {
614
            return null;
615
        }
616
    }
23955 govind 617
 
33128 amit.gupta 618
    private Address updateRetailerAddress(Address address, CustomAddress customAddress, int retailerId) throws
619
            ProfitMandiBusinessException {
31734 tejbeer 620
        if (address == null) {
621
            address = new Address();
622
            address.setRetaierId(retailerId);
623
            this.updateAddress(address, customAddress);
624
            // addressRepository.persist(addressRetailer);
23955 govind 625
 
31734 tejbeer 626
            final RetailerRegisteredAddress retailerRegisteredAddress = new RetailerRegisteredAddress();
627
            retailerRegisteredAddress.setRetailerId(retailerId);
628
            retailerRegisteredAddress.setAddressId(address.getId());
629
            retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
630
        } else {
631
            this.updateAddress(address, customAddress);
632
            RetailerRegisteredAddress retailerRegisteredAddress = retailerRegisteredAddressRepository.selectByRetailerId(retailerId);
633
            retailerRegisteredAddress.setAddressId(address.getId());
634
            retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
635
        }
636
        return address;
637
    }
23955 govind 638
 
31734 tejbeer 639
    private void updateAddress(Address address, CustomAddress customAddress) throws ProfitMandiBusinessException {
640
        address.setName(customAddress.getName());
641
        address.setPhoneNumber(customAddress.getPhoneNumber());
642
        address.setLine1(customAddress.getLine1());
643
        address.setLine2(customAddress.getLine2());
644
        address.setCity(customAddress.getCity());
645
        address.setPinCode(customAddress.getPinCode());
646
        State state = stateRepository.selectByName(customAddress.getState());
647
        if (state == null) {
648
            throw new ProfitMandiBusinessException("State name", "Invalid State - Pls Contact Technology", "Invalid State - Pls Contact Technology");
649
        }
650
        address.setState(state.getName());
651
        addressRepository.persist(address);
652
        LOGGER.info("Address Updated" + address);
653
    }
23955 govind 654
 
33128 amit.gupta 655
    private void updateRetailerShops(List<Shop> shops, Set<CustomShop> customShops, int retailerId, Address
656
            sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
31734 tejbeer 657
        if (shops.isEmpty()) {
658
            for (CustomShop customShop : customShops) {
659
                Shop shop = new Shop();
660
                this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
661
                shops.add(shop);
662
            }
663
        } else {
664
            for (Shop shop : shops) {
665
                for (CustomShop customShop : customShops) {
666
                    if (shop.getId() == customShop.getShopId()) {
667
                        this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
668
                    }
669
                }
670
            }
671
            for (CustomShop customShop : customShops) {
672
                if (customShop.getShopId() == 0) {
673
                    Shop shop = new Shop();
674
                    this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
675
                    shops.add(shop);
676
                }
677
            }
678
        }
679
    }
23955 govind 680
 
33128 amit.gupta 681
    private void createOrUpdateShop(Shop shop, CustomShop customShop, int retailerId, Address
682
            sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
31734 tejbeer 683
        shop.setRetailerId(retailerId);
684
        shop.setName(customShop.getName());
685
        if (customShop.getDocumentId() > 0) {
686
            if (shop.getDocumentId() != null && shop.getDocumentId() != customShop.getDocumentId()) {
687
                try {
688
                    documentRepository.deleteById(shop.getDocumentId());
689
                } catch (Exception e) {
690
                    e.printStackTrace();
691
                }
692
            }
693
            shop.setDocumentId(customShop.getDocumentId());
694
            documentRepository.markDocumentAsPersisted(customShop.getDocumentId());
695
        }
696
        if (shop.getAddressId() == null) {
697
            Address address = null;
698
            if (customShop.isSameAsRetailerAddress()) {
699
                address = sameAsRetailerAddressValue;
700
            } else {
701
                // shop.setDocumentId(customShop.getDocumentId());
702
                address = new Address();
703
                this.updateAddress(address, customShop.getAddress());
704
            }
705
            shop.setAddressId(address.getId());
706
            shop.setAddress(address);
707
            shopRepository.persist(shop);
708
            ShopAddress shopAddress = null;
709
            try {
710
                shopAddress = shopAddressRepository.selectByShopId(shop.getId());
711
                shopAddress.setAddressId(address.getId());
712
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
713
                shopAddress = new ShopAddress();
714
                shopAddress.setAddressId(address.getId());
715
                shopAddress.setShopId(shop.getId());
716
            }
717
            shopAddressRepository.persist(shopAddress);
718
        } else {
719
            Address address = null;
720
            try {
721
                address = addressRepository.selectById(shop.getAddressId());
722
                CustomAddress customAddress = customShop.getAddress();
723
                if (!(address.getName().equals(customAddress.getName()) && address.getLine1().equals(customAddress.getLine1()) && address.getLine2().equals(customAddress.getLine2()) && address.getCity().equals(customAddress.getCity()) && address.getPinCode().equals(customAddress.getPinCode()) && address.getState().equals(customAddress.getState()))) {
724
                    address = new Address();
725
                    ShopAddress shopAddress = shopAddressRepository.selectByShopId(shop.getId());
726
                    this.updateAddress(address, customAddress);
727
                    shopAddress.setAddressId(address.getId());
728
                    shopAddressRepository.persist(shopAddress);
729
                    shop.setAddress(address);
730
                    shopRepository.persist(shop);
731
                }
732
            } catch (Exception e) {
733
                if (customShop.isSameAsRetailerAddress()) {
734
                    address = sameAsRetailerAddressValue;
735
                } else {
736
                    // shop.setDocumentId(customShop.getDocumentId());
737
                    address = new Address();
738
                    this.updateAddress(address, customShop.getAddress());
739
                }
740
                shop.setAddressId(address.getId());
741
                shop.setAddress(address);
742
                shopRepository.persist(shop);
743
                ShopAddress shopAddress = null;
744
                try {
745
                    shopAddress = shopAddressRepository.selectByShopId(shop.getId());
746
                    shopAddress.setAddressId(address.getId());
747
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
748
                    shopAddress = new ShopAddress();
749
                    shopAddress.setAddressId(address.getId());
750
                    shopAddress.setShopId(shop.getId());
751
                }
752
                shopAddressRepository.persist(shopAddress);
753
            }
23955 govind 754
 
31734 tejbeer 755
        }
23955 govind 756
 
31734 tejbeer 757
    }
23955 govind 758
 
33247 ranu 759
    private void addAddress(List<Shop> shops) throws ProfitMandiBusinessException {
31734 tejbeer 760
        Set<Integer> shopIds = this.toShopIds(shops);
761
        if (shopIds.isEmpty()) {
762
            return;
763
        }
764
        List<ShopAddress> shopAddresses = shopAddressRepository.selectByShopIds(shopIds);
765
        Map<Integer, Address> addressIdAddressMap = this.toAddressIdAddressMap(shopAddresses);
23955 govind 766
 
31734 tejbeer 767
        for (Shop shop : shops) {
768
            shop.setAddress(addressIdAddressMap.get(shop.getAddressId()));
769
        }
770
    }
22980 ashik.ali 771
 
33247 ranu 772
    private Map<Integer, Address> toAddressIdAddressMap(List<ShopAddress> shopAddresses) throws ProfitMandiBusinessException {
31734 tejbeer 773
        Map<Integer, Address> addressIdAddressMap = new HashMap<>();
774
        List<Integer> addressIds = this.toAddressIds(shopAddresses);
775
        List<Address> addresses = addressRepository.selectByIds(addressIds);
776
        for (Address address : addresses) {
777
            addressIdAddressMap.put(address.getId(), address);
778
        }
779
        return addressIdAddressMap;
780
    }
23955 govind 781
 
31734 tejbeer 782
    private List<Integer> toAddressIds(List<ShopAddress> shopAddresses) {
783
        Function<ShopAddress, Integer> shopAddressToAddressIdFunction = new Function<ShopAddress, Integer>() {
784
            @Override
785
            public Integer apply(ShopAddress shopAddress) {
786
                return shopAddress.getAddressId();
787
            }
788
        };
789
        return shopAddresses.stream().map(shopAddressToAddressIdFunction).collect(Collectors.toList());
790
    }
23955 govind 791
 
31734 tejbeer 792
    private Set<Integer> toShopIds(List<Shop> shops) {
793
        Function<Shop, Integer> shopToAddressIdFunction = new Function<Shop, Integer>() {
794
            @Override
795
            public Integer apply(Shop shop) {
796
                return shop.getId();
797
            }
798
        };
799
        return shops.stream().map(shopToAddressIdFunction).collect(Collectors.toSet());
800
    }
23955 govind 801
 
33247 ranu 802
    private String toString(List<UserRole> userRoles) throws ProfitMandiBusinessException {
31734 tejbeer 803
        Set<Integer> roleIds = new HashSet<>();
804
        for (UserRole userRole : userRoles) {
805
            roleIds.add(userRole.getRoleId());
806
        }
807
        List<Role> roles = roleRepository.selectByIds(roleIds);
31735 amit.gupta 808
        Function<Role, String> roleToNameFunction = role -> String.valueOf(role.getName());
31734 tejbeer 809
        Set<String> userRoleStrings = roles.stream().map(roleToNameFunction).collect(Collectors.toSet());
810
        return String.join(", ", userRoleStrings);
811
    }
23955 govind 812
 
33128 amit.gupta 813
    private FofoStore createFofoStoreCodeByRetailerId(int retailerId, String districtName, String
814
            stateName, UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
31734 tejbeer 815
        FofoStore fofoStore = null;
816
        try {
817
            fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
818
            fofoStore.setActivationType(ActivationType.ACTIVE);
30097 tejbeer 819
 
31734 tejbeer 820
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
23955 govind 821
 
31734 tejbeer 822
        }
23955 govind 823
 
31734 tejbeer 824
        if (fofoStore != null) {
825
            fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
33124 ranu 826
            fofoStore.setAstId(updateRetailerRequest.getAstId());
31734 tejbeer 827
            fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
828
            fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
829
            fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
830
            fofoStore.setFofoType(updateRetailerRequest.getFofoType());
831
        } else {
832
            int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailerId);
833
            Address retailerAddress = addressRepository.selectById(retailerAddressId);
23955 govind 834
 
31734 tejbeer 835
            // StateInfo stateInfo = null;
836
            State stateInfo = null;
837
            try {
30527 tejbeer 838
 
31734 tejbeer 839
                stateInfo = stateRepository.selectByName(retailerAddress.getState());
840
                // stateInfo = Utils.getStateInfo(retailerAddress.getState());
841
            } catch (Exception e) {
842
                // TODO Auto-generated catch block
843
                e.printStackTrace();
844
                // throw new ProfitMandiBusinessException();
845
            }
846
            DistrictMaster districtMaster = districtMasterRepository.selectByNameAndStateShortName(districtName, stateInfo.getShortName());
23955 govind 847
 
31734 tejbeer 848
            fofoStore = new FofoStore();
849
            fofoStore.setId(retailerId);
850
            fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
851
            fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
31730 tejbeer 852
 
31734 tejbeer 853
            fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
854
            fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
32615 raveendra. 855
            int nextStoreCodeInt = fofoStoreRepository.selectLatestStore().getCodeInt() + 1;
856
 
31734 tejbeer 857
            String fofoStoreCode = StringUtils.generateFofoStoreSequence(
32615 raveendra. 858
                    districtMaster.getStateShortName() + districtMaster.getShortName(), nextStoreCodeInt);
31734 tejbeer 859
            fofoStore.setCode(fofoStoreCode);
32615 raveendra. 860
            fofoStore.setCodeInt(nextStoreCodeInt);
31734 tejbeer 861
            fofoStore.setBagsLastCredited(LocalDateTime.now());
862
            fofoStore.setFofoType(updateRetailerRequest.getFofoType());
863
            fofoStore.setActivationType(ActivationType.ACTIVE);
864
            fofoStoreRepository.persist(fofoStore);
28908 tejbeer 865
 
31734 tejbeer 866
            // Auto fill in onboarding Panel
867
            PartnerOnBoardingPanel pobp = partnerOnBoardingPanelRepository.selectByPhoneNumber(Long.parseLong(retailerAddress.getPhoneNumber()));
868
            if (pobp != null) {
28908 tejbeer 869
 
31734 tejbeer 870
                PartnerVerificationpanel partnerVerificationpanel = partnerOnboardingVerificationRepository.selectByOnboardingId(pobp.getId());
29042 tejbeer 871
 
31734 tejbeer 872
                if (partnerVerificationpanel != null) {
873
                    if (partnerVerificationpanel.getApproval().equals(PartnerVerificationApprovalStatus.YES)) {
874
                        pobp.setCode(fofoStore.getCode());
29042 tejbeer 875
 
31734 tejbeer 876
                        storeTimelineTatService.onCodeCreated(pobp.getId());
29042 tejbeer 877
 
31734 tejbeer 878
                    }
29042 tejbeer 879
 
31734 tejbeer 880
                }
29042 tejbeer 881
 
31734 tejbeer 882
            }
30719 tejbeer 883
 
31734 tejbeer 884
            PincodePartner pincodePartner = pincodePartnerRepository.selectPartnerByPincode(retailerAddress.getPinCode(), fofoStore.getId());
885
            if (pincodePartner == null) {
886
                PincodePartner pinPartner = new PincodePartner();
887
                pinPartner.setFofoId(fofoStore.getId());
888
                pinPartner.setPincode(retailerAddress.getPinCode());
889
                pincodePartnerRepository.perist(pinPartner);
890
            }
891
        }
23955 govind 892
 
31734 tejbeer 893
        return fofoStore;
894
    }
23955 govind 895
 
31734 tejbeer 896
    @Override
33128 amit.gupta 897
    public FofoStore createFofoStoreCodeByUserId(int userId, String districtName, String
898
            stateName, UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
31734 tejbeer 899
        User user = userRepository.selectById(userId);
900
        // = userAccountRepository.selectRetailerIdByUserId(user.getId());
901
        UserAccount userAccounts = userAccountRepository.selectSaholicByUserId(user.getId());
902
        Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
903
        Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
904
        try {
905
            userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleFofo.getId());
906
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
907
            throw new ProfitMandiBusinessException(ProfitMandiConstants.USER_ID, user.getId(), "USR_1013");
908
        }
909
        return this.createFofoStoreCodeByRetailerId(retailer.getId(), districtName, stateName, updateRetailerRequest);
23955 govind 910
 
31734 tejbeer 911
    }
23955 govind 912
 
31734 tejbeer 913
    @Override
914
    public List<DistrictMaster> getAllDistrictMaster(String stateName) {
915
        // StateInfo stateInfo = null;
916
        State stateInfo = null;
917
        try {
918
            // stateInfo = Utils.getStateInfo(stateName);
30525 tejbeer 919
 
31734 tejbeer 920
            stateInfo = stateRepository.selectByName(stateName);
921
        } catch (Exception e) {
922
            e.printStackTrace();
923
            // throw new ProfitMandiBusinessException();
924
        }
925
        return districtMasterRepository.selectByStateShortName(stateInfo.getShortName());
926
    }
22980 ashik.ali 927
 
31734 tejbeer 928
    @Override
34149 tejus.loha 929
    @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 930
    public Map<Integer, CustomRetailer> getFofoRetailers(List<Integer> fofoIds) throws ProfitMandiBusinessException {
31734 tejbeer 931
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
932
        Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream().filter(x -> x.getAddressId() != null).collect(Collectors.toMap(x -> x.getAddressId(), x -> x));
933
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
934
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
935
        for (Address address : addresses) {
936
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
937
            CustomRetailer customRetailer = new CustomRetailer();
938
            customRetailer.setEmail(user.getEmailId());
939
            customRetailer.setBusinessName(address.getName());
940
            customRetailer.setMobileNumber(address.getPhoneNumber());
941
            try {
942
                FofoStore fs = fofoStoreRepository.selectByRetailerId(address.getRetaierId());
943
                customRetailer.setCode(fs.getCode());
33553 ranu 944
                customRetailer.setAstId(fs.getAstId());
31734 tejbeer 945
                customRetailer.setActivationType(fs.getActivationType());
946
                customRetailer.setCounterSize(fs.getCounterSize());
31180 tejbeer 947
 
31743 tejbeer 948
 
949
                customRetailer.setCounterPotential(fs.getCounterPotential());
950
 
31734 tejbeer 951
                customRetailer.setWarehouseId(fs.getWarehouseId());
952
                customRetailer.setPartnerId(fs.getId());
953
                customRetailer.setFofoType(fs.getFofoType());
954
            } catch (Exception e) {
955
                continue;
956
            }
957
            try {
958
                customRetailer.setCartId(user.getActiveCartId());
959
                PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
960
                Counter counter = counterRepository.selectById(pdu.getCounterId());
961
                customRetailer.setGstNumber(counter.getGstin());
962
            } catch (Exception e) {
963
                customRetailer.setGstNumber(null);
964
            }
965
            CustomAddress address1 = new CustomAddress();
966
            address1.setCity(address.getCity());
967
            address1.setState(address.getState());
968
            address1.setLine1(address.getLine1());
969
            address1.setLine2(address.getLine2());
970
            address1.setPinCode(address.getPinCode());
971
            address1.setName(address.getName());
972
            customRetailer.setAddress(address1);
973
            customRetailer.setDisplayName(
974
                    customRetailer.getBusinessName() + "-" + customRetailer.getCode() + "- " + address1.getCity());
975
            customRetailersMap.put(customRetailer.getPartnerId(), customRetailer);
976
        }
977
        return customRetailersMap;
978
    }
25295 amit.gupta 979
 
31734 tejbeer 980
    @Override
981
    @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
982
    public CustomRetailer getFofoRetailer(int fofoId) throws ProfitMandiBusinessException {
983
        com.spice.profitmandi.dao.entity.user.User saholicUser = userUserRepository.selectById(fofoId);
31862 tejbeer 984
 
985
        User dtrUser = userRepository.selectByEmailId(saholicUser.getEmailId());
31734 tejbeer 986
        FofoStore store = fofoStoreRepository.selectByRetailerId(fofoId);
987
        Address address = null;
988
        try {
989
            address = addressRepository.selectById(saholicUser.getAddressId());
990
        } catch (ProfitMandiBusinessException e1) {
991
            // TODO Auto-generated catch block
992
            e1.printStackTrace();
993
        }
994
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
995
        CustomRetailer customRetailer = new CustomRetailer();
996
        customRetailer.setEmail(saholicUser.getEmailId());
997
        customRetailer.setBusinessName(address.getName());
998
        customRetailer.setMobileNumber(address.getPhoneNumber());
31862 tejbeer 999
        customRetailer.setFirstName(dtrUser.getFirstName());
1000
        customRetailer.setLastName(dtrUser.getLastName());
31734 tejbeer 1001
        try {
1002
            customRetailer.setCartId(saholicUser.getActiveCartId());
1003
            PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
1004
            Counter counter = counterRepository.selectById(pdu.getCounterId());
1005
            customRetailer.setGstNumber(counter.getGstin());
1006
        } catch (Exception e) {
1007
            customRetailer.setGstNumber(null);
1008
        }
1009
        CustomAddress address1 = new CustomAddress();
1010
        address1.setCity(address.getCity());
1011
        address1.setState(address.getState());
1012
        address1.setLine1(address.getLine1());
1013
        address1.setLine2(address.getLine2());
1014
        address1.setPinCode(address.getPinCode());
1015
        address1.setPhoneNumber(address.getPhoneNumber());
1016
        address1.setName(address.getName());
1017
        customRetailer.setDisplayName(address.getName() + " - " + address.getCity());
1018
        customRetailer.setAddress(address1);
1019
        customRetailer.setPartnerId(address.getRetaierId());
1020
        customRetailer.setCode(store.getCode());
33553 ranu 1021
        customRetailer.setAstId(store.getAstId());
31734 tejbeer 1022
        customRetailer.setActivationType(store.getActivationType());
1023
        customRetailer.setWarehouseId(store.getWarehouseId());
1024
        customRetailersMap.put(address.getRetaierId(), customRetailer);
1025
        return customRetailer;
25295 amit.gupta 1026
 
31734 tejbeer 1027
    }
26125 amit.gupta 1028
 
31734 tejbeer 1029
    @Override
33247 ranu 1030
    public Map<Integer, CustomRetailer> getFofoRetailerUserId(List<Integer> fofoIds) throws ProfitMandiBusinessException {
31734 tejbeer 1031
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
1032
        Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream().filter(x -> x.getAddressId() != null).collect(Collectors.toMap(x -> x.getAddressId(), x -> x));
1033
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
1034
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
1035
        for (Address address : addresses) {
1036
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
1037
            CustomRetailer customRetailer = new CustomRetailer();
1038
            customRetailer.setEmail(user.getEmailId());
1039
            customRetailer.setBusinessName(address.getName());
1040
            customRetailer.setMobileNumber(address.getPhoneNumber());
1041
            int userId = 0;
1042
            try {
1043
                userId = userAccountRepository.selectUserIdByRetailerId(user.getId());
1044
            } catch (ProfitMandiBusinessException e) {
1045
                continue;
1046
            }
1047
            try {
1048
                customRetailer.setCartId(user.getActiveCartId());
1049
                PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
1050
                Counter counter = counterRepository.selectById(pdu.getCounterId());
1051
                customRetailer.setGstNumber(counter.getGstin());
1052
            } catch (Exception e) {
1053
                customRetailer.setGstNumber(null);
1054
            }
1055
            CustomAddress address1 = new CustomAddress();
1056
            address1.setCity(address.getCity());
1057
            address1.setState(address.getState());
1058
            address1.setLine1(address.getLine1());
1059
            address1.setLine2(address.getLine2());
1060
            address1.setPinCode(address.getPinCode());
1061
            address1.setName(address.getName());
1062
            customRetailer.setAddress(address1);
1063
            customRetailer.setPartnerId(address.getRetaierId());
1064
            customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + address1.getCity());
1065
            customRetailersMap.put(userId, customRetailer);
1066
        }
1067
        return customRetailersMap;
1068
    }
25295 amit.gupta 1069
 
31734 tejbeer 1070
    @Override
33247 ranu 1071
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap() throws ProfitMandiBusinessException {
31734 tejbeer 1072
        Role roleFofo = null;
1073
        try {
1074
            roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
1075
        } catch (ProfitMandiBusinessException e) {
1076
            // TODO Auto-generated catch block
1077
            e.printStackTrace();
1078
        }
1079
        Role roleRetailer = null;
1080
        try {
1081
            roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
1082
        } catch (ProfitMandiBusinessException e) {
1083
            // TODO Auto-generated catch block
1084
            e.printStackTrace();
1085
        }
1086
        Set<Integer> roleIds = new HashSet<>();
1087
        roleIds.add(roleFofo.getId());
1088
        roleIds.add(roleRetailer.getId());
1089
        List<Integer> userIds = userRoleRepository.selectUserIdsByRoleIds(roleIds);
1090
        List<User> users = userRepository.selectAllByIds(new HashSet<>(userIds));
1091
        Map<Integer, Integer> userIdRetailerIdMap = this.getUserIdRetailerIdMap(userIds);
1092
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1093
        for (User user : users) {
1094
            retailerIdEmailIdMap.put(userIdRetailerIdMap.get(user.getId()), user.getEmailId());
1095
        }
1096
        return retailerIdEmailIdMap;
1097
    }
23955 govind 1098
 
31734 tejbeer 1099
    private Map<Integer, Integer> getUserIdRetailerIdMap(List<Integer> userIds) {
1100
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByUserIds(new HashSet<>(userIds));
1101
        Map<Integer, Integer> userIdRetailerIdMap = new HashMap<>();
1102
        for (UserAccount userAccount : userAccounts) {
1103
            userIdRetailerIdMap.put(userAccount.getUserId(), userAccount.getAccountKey());
1104
        }
1105
        return userIdRetailerIdMap;
1106
    }
25295 amit.gupta 1107
 
33247 ranu 1108
    private Map<Integer, String> getUserIdEmailIdMap(Set<Integer> userIds) throws ProfitMandiBusinessException {
31734 tejbeer 1109
        List<User> users = userRepository.selectAllByIds(userIds);
1110
        Map<Integer, String> userIdEmailIdMap = new HashMap<>();
1111
        for (User user : users) {
1112
            userIdEmailIdMap.put(user.getId(), user.getEmailId());
1113
        }
1114
        return userIdEmailIdMap;
1115
    }
23509 amit.gupta 1116
 
31734 tejbeer 1117
    @Override
33247 ranu 1118
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap(Set<Integer> retailerIds) throws ProfitMandiBusinessException {
31734 tejbeer 1119
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1120
        Set<Integer> userIds = new HashSet<>();
1121
        for (UserAccount userAccount : userAccounts) {
1122
            userIds.add(userAccount.getUserId());
1123
        }
1124
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1125
        Map<Integer, String> userIdEmailIdMap = this.getUserIdEmailIdMap(userIds);
1126
        for (UserAccount userAccount : userAccounts) {
1127
            retailerIdEmailIdMap.put(userAccount.getAccountKey(), userIdEmailIdMap.get(userAccount.getUserId()));
1128
        }
1129
        return retailerIdEmailIdMap;
1130
    }
25295 amit.gupta 1131
 
31734 tejbeer 1132
    @Override
33247 ranu 1133
    public Map<Integer, String> getAllFofoRetailerIdNameMap(List<Integer> storeIds) throws ProfitMandiBusinessException {
31734 tejbeer 1134
        Map<Integer, CustomRetailer> retailersMap = this.getFofoRetailers(storeIds);
1135
        Map<Integer, String> retailerIdNameMap = new HashMap<>();
1136
        for (Map.Entry<Integer, CustomRetailer> entry : retailersMap.entrySet()) {
1137
            retailerIdNameMap.put(entry.getKey(), entry.getValue().getBusinessName() + "-" + entry.getValue().getAddress().getCity());
1138
        }
1139
        return retailerIdNameMap;
1140
    }
24168 amit.gupta 1141
 
31734 tejbeer 1142
    @Override
1143
    @Cacheable(value = "FofoRetailerIdNameMap", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1144
    public Map<Integer, String> getAllFofoRetailerIdNameMap() throws ProfitMandiBusinessException {
31734 tejbeer 1145
        List<FofoStore> stores = fofoStoreRepository.selectAll();
1146
        List<Integer> storeIds = stores.stream().map(x -> x.getId()).collect(Collectors.toList());
1147
        return this.getAllFofoRetailerIdNameMap(storeIds);
1148
    }
24349 amit.gupta 1149
 
31734 tejbeer 1150
    @Override
33247 ranu 1151
    public List<MapWrapper<Integer, String>> getAllFofoRetailerIdNameList() throws ProfitMandiBusinessException {
31734 tejbeer 1152
        List<MapWrapper<Integer, String>> mapWrappers = new ArrayList<>();
1153
        // TODO Auto-generated method stub
1154
        Map<Integer, String> fofoIdNameMap = this.getAllFofoRetailerIdNameMap();
1155
        fofoIdNameMap.forEach((fofoId, name) -> {
1156
            MapWrapper<Integer, String> idWrapper = new MapWrapper<>();
1157
            idWrapper.setKey(fofoId);
1158
            idWrapper.setValue(name);
1159
            mapWrappers.add(idWrapper);
1160
        });
1161
        return mapWrappers;
1162
    }
24349 amit.gupta 1163
 
31734 tejbeer 1164
    @Override
1165
    @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1166
    public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly) throws ProfitMandiBusinessException {
31734 tejbeer 1167
        // TODO Auto-generated method stub
34936 amit 1168
        Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream().filter(x -> x.getFofoType().equals(FofoType.INTERNAL));
31734 tejbeer 1169
        if (activeOnly) {
1170
            storeStream = storeStream.filter(x -> x.isActive());
1171
        }
1172
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1173
        return this.getFofoRetailers(storeIds);
1174
    }
25295 amit.gupta 1175
 
31734 tejbeer 1176
    @Override
33367 ranu 1177
    @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
1178
    public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly, String pinCode) throws ProfitMandiBusinessException {
1179
        List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pinCode);
1180
        List<Integer> storeIds = new ArrayList<>();
1181
        if (pincodePartners.size() > 0) {
1182
            List<Integer> fofoIds = pincodePartners.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
1183
            List<FofoStore> fofoStores = fofoStoreRepository.selectActivePartnersByRetailerIds(fofoIds);
1184
            storeIds = fofoStores.stream().map(x -> x.getId()).collect(Collectors.toList());
1185
        }
1186
        return this.getFofoRetailers(storeIds);
1187
    }
1188
 
1189
    @Override
31734 tejbeer 1190
    @Cacheable(value = "allFofoRetailers", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1191
    public Map<Integer, CustomRetailer> getAllFofoRetailers() throws ProfitMandiBusinessException {
31734 tejbeer 1192
        // TODO Auto-generated method stub
1193
        Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream();
27861 tejbeer 1194
 
31734 tejbeer 1195
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1196
        return this.getFofoRetailers(storeIds);
1197
    }
27861 tejbeer 1198
 
31734 tejbeer 1199
    @Override
34619 ranu 1200
    @Cacheable(value = "allFofoRetailersInternalFalse", cacheManager = "thirtyMinsTimeOutCacheManager")
1201
    public Map<Integer, CustomRetailer> getAllFofoRetailersInternalFalse() throws ProfitMandiBusinessException {
1202
        // TODO Auto-generated method stub
1203
        Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream().filter(x-> !x.isInternal());
1204
 
1205
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1206
        return this.getFofoRetailers(storeIds);
1207
    }
1208
 
1209
    @Override
33128 amit.gupta 1210
    public LoginRequestResponseModel registerWebUser(LoginRequestResponseModel loginRequestModel) throws
1211
            ProfitMandiBusinessException {
26522 amit.gupta 1212
 
31734 tejbeer 1213
        com.spice.profitmandi.dao.entity.user.User saholicUser = this.createSaholicUser(loginRequestModel);
1214
        loginRequestModel.setUserId(saholicUser.getId());
26522 amit.gupta 1215
 
31734 tejbeer 1216
        this.createRetailerAddress(loginRequestModel);
26522 amit.gupta 1217
 
31734 tejbeer 1218
        this.createPrivateDealUser(loginRequestModel);
1219
        this.updateSaholicUser(saholicUser.getId(), loginRequestModel.getBusinessAddress().getId());
26522 amit.gupta 1220
 
31734 tejbeer 1221
        return loginRequestModel;
26522 amit.gupta 1222
 
31734 tejbeer 1223
    }
26522 amit.gupta 1224
 
31734 tejbeer 1225
    private void createPrivateDealUser(LoginRequestResponseModel loginRequestModel) {
26522 amit.gupta 1226
 
31734 tejbeer 1227
        Integer counterId = this.createCounter(loginRequestModel.getEmail(), loginRequestModel.getGstNumber(), loginRequestModel.getBusinessAddress().getPhoneNumber(), loginRequestModel.getBusinessAddress().getName(), loginRequestModel.getBusinessAddress().getId());
1228
        try {
1229
            this.createPrivateDealUser(loginRequestModel.getUserId(), counterId, false);
1230
        } catch (Exception e) {
1231
            LOGGER.error("ERROR : ", e);
1232
        }
26522 amit.gupta 1233
 
31734 tejbeer 1234
        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
1235
        privateDealUserAddressMapping.setUserId(loginRequestModel.getUserId());
1236
        privateDealUserAddressMapping.setAddressId(loginRequestModel.getBusinessAddress().getId());
1237
        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
26522 amit.gupta 1238
 
31734 tejbeer 1239
    }
26522 amit.gupta 1240
 
33128 amit.gupta 1241
    private void createRetailerAddress(LoginRequestResponseModel loginRequestResponseModel) throws
1242
            ProfitMandiBusinessException {
31734 tejbeer 1243
        Address businessAddress = loginRequestResponseModel.getBusinessAddress();
1244
        businessAddress.setRetaierId(loginRequestResponseModel.getUserId());
1245
        addressRepository.persist(businessAddress);
1246
    }
26536 amit.gupta 1247
 
31734 tejbeer 1248
    private String getHash256(String originalString) {
1249
        String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
1250
        LOGGER.info("Hash String {}", hashString);
1251
        return hashString;
1252
    }
26533 amit.gupta 1253
 
31734 tejbeer 1254
    @Override
1255
    @Cacheable(value = "fofoIdUrl", cacheManager = "thirtyMinsTimeOutCacheManager")
1256
    public Map<Integer, String> getAllFofoRetailerIdUrlMap() {
1257
        Map<Integer, String> fofoRetailerUrlMap = new HashMap<>();
1258
        List<FofoStore> stores = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).collect(Collectors.toList());
1259
        Map<Integer, com.spice.profitmandi.dao.entity.user.User> userMap = userUserRepository.selectByIds(stores.stream().map(x -> x.getId()).collect(Collectors.toList())).stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1260
        for (FofoStore store : stores) {
1261
            LOGGER.info("Store is {}", store);
1262
            String districtShortName = store.getCode().replaceAll("\\d+", "").substring(2);
1263
            String stateShortName = store.getCode().replaceAll("\\d+", "").substring(0, 2);
1264
            DistrictMaster districtMaster = null;
1265
            LOGGER.info("Store shortname is {}", districtShortName);
1266
            districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName(districtShortName, stateShortName);
1267
            if (districtMaster == null) {
1268
                districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName("FB", "HR");
1269
            }
1270
            LOGGER.info("Store id - {}", store.getId());
1271
            // com.spice.profitmandi.dao.entity.user.User user = userMap.get(store.getId());
1272
            String urlString = districtMaster.getStateShortName() + "/" + Utils.getHyphenatedString(districtMaster.getName()) + "/" + store.getCode();
1273
            fofoRetailerUrlMap.put(store.getId(), urlString.toLowerCase());
1274
            LOGGER.info("Store is {} end", store);
26536 amit.gupta 1275
 
31734 tejbeer 1276
        }
1277
        return fofoRetailerUrlMap;
1278
    }
26533 amit.gupta 1279
 
31734 tejbeer 1280
    @Override
1281
    @Cacheable(value = "storeCodeRetailerMap", cacheManager = "thirtyMinsTimeOutCacheManager")
1282
    public Map<String, Integer> getStoreCodeRetailerMap() {
1283
        Map<Integer, String> map = this.getAllFofoRetailerIdUrlMap();
1284
        Map<String, Integer> returnMap = map.entrySet().stream().collect(Collectors.toMap(x -> {
1285
            String[] splitString = x.getValue().split("/");
1286
            return splitString[splitString.length - 1];
1287
        }, x -> x.getKey()));
1288
        LOGGER.info("returnMap {}", returnMap);
1289
        return returnMap;
1290
    }
27877 amit.gupta 1291
 
1292
 
31734 tejbeer 1293
    @Override
32668 raveendra. 1294
    public User getEmail() {
1295
        return null;
1296
    }
1297
 
1298
    @Override
1299
    public void update(com.spice.profitmandi.dao.entity.user.User user) {
1300
    }
1301
 
1302
    @Override
1303
    public void updateRetailerEmail(int fofoId, String newEmail) throws ProfitMandiBusinessException {
1304
        User dtrUser = null;
1305
        com.spice.profitmandi.dao.entity.user.User user = null;
1306
 
1307
        try {
1308
            dtrUser = userRepository.selectByEmailId(newEmail);
1309
        } catch (Exception e) {
1310
        }
1311
 
1312
        try {
1313
            user = userUserRepository.selectByEmailId(newEmail);
1314
        } catch (Exception e) {
1315
        }
1316
 
1317
        if (user != null || dtrUser != null) {
1318
            throw new ProfitMandiBusinessException("Email", newEmail, "Email already exist");
1319
        }
1320
        com.spice.profitmandi.dao.entity.user.User fofoUser = userUserRepository.selectById(fofoId);
1321
        String oldEmail = fofoUser.getEmailId();
1322
        LOGGER.info("old email {}", oldEmail);
1323
        User thisDtrUser = userRepository.selectByEmailId(oldEmail);
1324
 
1325
        fofoUser.setEmailId(newEmail);
1326
        thisDtrUser.setEmailId(newEmail);
1327
    }
1328
 
1329
 
32953 amit.gupta 1330
    //    @Override
32737 amit.gupta 1331
    @Cacheable(value = "getContactsByFofoId", cacheManager = "oneDayCacheManager")
33128 amit.gupta 1332
    public List<RetailerContact> getContactsByFofoId(int fofoId, boolean activeOnly) throws
1333
            ProfitMandiBusinessException {
32737 amit.gupta 1334
        List<RetailerContact> retailerContacts = retailerContactRepository.selectAllByRetailerId(fofoId, activeOnly);
1335
        com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
1336
        RetailerContact retailerContact = new RetailerContact();
1337
        retailerContact.setMobile(user.getMobileNumber());
1338
        retailerContact.setName(user.getName());
1339
        retailerContact.setActive(true);
1340
        retailerContact.setFofoId(fofoId);
1341
        retailerContacts.add(retailerContact);
1342
        return retailerContacts;
1343
    }
1344
 
1345
 
1346
    @Override
33128 amit.gupta 1347
    public Map<Integer, CustomRetailer> getFofoRetailersPaginated(boolean activeOnly, int offset,
33247 ranu 1348
                                                                  int limit, FofoType fofoType) throws ProfitMandiBusinessException {
30097 tejbeer 1349
 
31734 tejbeer 1350
        Stream<FofoStore> storeStream = fofoStoreRepository.selectByStatusFofoType(activeOnly, fofoType, offset, limit).stream();
30219 tejbeer 1351
 
31734 tejbeer 1352
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1353
        return this.getFofoRetailers(storeIds);
1354
    }
30219 tejbeer 1355
 
34813 aman 1356
    @Override
1357
    public Map<String, Object> computeIncomeMap(int fofoId, int yearMonth) {
1358
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1359
        LocalDateTime endOfMonth = startOfMonth.plusMonths(1);
1360
        YearMonth monthYear = YearMonth.now();
1361
 
1362
 
1363
        // 3) Fetch brand-wise data (same as original)
1364
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1365
                .selectLastMonthPendingIncomeByFofoId(fofoId, startOfMonth, endOfMonth);
1366
 
1367
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1368
                .selectLastMonthPurchaseInMarginByFofoId(fofoId, startOfMonth, endOfMonth);
1369
 
1370
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1371
                .selectFrontIncomeByBrand(fofoId, startOfMonth, endOfMonth);
1372
 
1373
        List<LastMonthCreditedIncomeModel> lastMonthSaleMargins = schemeInOutRepository
1374
                .selectLastMonthCreditedIncomeByFofoId(fofoId, startOfMonth, endOfMonth);
1375
 
1376
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository
1377
                .getTotalPayoutsByPartnerPeriod(
1378
                        YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()),
1379
                        fofoId, null, null);
1380
 
1381
        // 4) Convert to maps for brand-wise access
1382
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap =
1383
                lastMonthPendingIncomeModels.stream()
1384
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1385
 
1386
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap =
1387
                lastMonthPurchaseInMargins.stream()
1388
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1389
 
1390
        Map<String, LastMonthCreditedIncomeModel> lastMonthFrontEndIncomeMap =
1391
                lastMonthFrontEndIncomes.stream()
1392
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1393
 
1394
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap =
1395
                lastMonthSaleMargins.stream()
1396
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1397
 
1398
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream()
1399
                .collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand,
1400
                        Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1401
 
1402
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream()
1403
                .collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand,
1404
                        Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
1405
 
1406
        // 5) Get all unique brands
1407
        Set<String> brandSet = new HashSet<>();
1408
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1409
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1410
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1411
        brandSet.addAll(additionalPurchasePayout.keySet());
1412
        brandSet.addAll(additionSalePayout.keySet());
1413
        brandSet.addAll(lastMonthFrontEndIncomeMap.keySet());
1414
 
1415
        // 6) Calculate total amount per brand (same logic as original)
1416
        Map<String, Float> totalAmountMap = new HashMap<>();
1417
        brandSet.forEach(brand -> {
1418
            float total =
1419
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1420
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1421
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1422
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).floatValue()) +
1423
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).floatValue()) +
1424
                            (lastMonthFrontEndIncomeMap.get(brand) == null ? 0 : lastMonthFrontEndIncomeMap.get(brand).getAmount());
1425
            totalAmountMap.put(brand, total);
1426
        });
1427
 
1428
        // 7) Calculate aggregated totals
1429
        float totalIncome = totalAmountMap.values().stream()
1430
                .reduce(0f, Float::sum);
1431
 
1432
        float pendingIncome = lastMonthPendingIncomeMap.values().stream()
1433
                .map(LastMonthCreditedIncomeModel::getAmount)
1434
                .reduce(0f, Float::sum);
1435
 
1436
        float creditedIncome = totalIncome - pendingIncome;
1437
 
1438
        // 8) Build month labels
1439
        Map<Integer, String> monthValueMap = new HashMap<>();
1440
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MMM''uu");
1441
        for (int i = 0; i <= 5; i++) {
1442
            LocalDateTime m = LocalDateTime.now()
1443
                    .withDayOfMonth(1)
1444
                    .minusMonths(i);
1445
            monthValueMap.put(i, m.format(fmt));
1446
        }
1447
 
1448
        // 9) Assemble result with all brand-wise data
1449
        Map<String, Object> result = new HashMap<>();
1450
        result.put("totalIncome", totalIncome);
1451
        result.put("creditedIncome", creditedIncome);
1452
        result.put("pendingIncome", pendingIncome);
1453
        result.put("monthIndex", yearMonth);
1454
        result.put("monthValueMap", monthValueMap);
1455
 
1456
        // Include brand-wise data for detailed analysis
1457
        result.put("brandSet", brandSet);
1458
        result.put("totalAmountMap", totalAmountMap);
1459
        result.put("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1460
        result.put("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1461
        result.put("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1462
        result.put("additionalPurchasePayoutMap", additionalPurchasePayout);
1463
        result.put("additionalSalePayoutMap", additionSalePayout);
1464
        result.put("lastMonthFrontEndIncomeMap", lastMonthFrontEndIncomeMap);
1465
 
1466
        return result;
1467
    }
1468
 
22980 ashik.ali 1469
}