Subversion Repositories SmartDukaan

Rev

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