Subversion Repositories SmartDukaan

Rev

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