Subversion Repositories SmartDukaan

Rev

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