Subversion Repositories SmartDukaan

Rev

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