Subversion Repositories SmartDukaan

Rev

Rev 31743 | Rev 32555 | 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);
485
        } catch (ProfitMandiBusinessException e) {
23955 govind 486
 
31734 tejbeer 487
        }
488
    }
23955 govind 489
 
31734 tejbeer 490
    private void createPrivateDealUser(User user, boolean fofo, String gstNumber, Retailer retailer, int retailerAddressId) {
491
        PrivateDealUser privateDealUser = null;
492
        try {
493
            privateDealUser = privateDealUserRepository.selectById(retailer.getId());
494
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
495
            LOGGER.error("PrivateDealUser not found");
496
        }
23955 govind 497
 
31734 tejbeer 498
        // = privateDealUserRepository.selectById(saholicUser.getId());
499
        if (privateDealUser == null) {
500
            Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
501
            try {
502
                this.createPrivateDealUser(retailer.getId(), counterId, fofo);
503
            } catch (Exception e) {
504
                LOGGER.error("ERROR : ", e);
505
            }
506
        } else {
507
            if (privateDealUser.getCounterId() == null) {
508
                Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
509
                privateDealUser.setCounterId(counterId);
510
                privateDealUser.setFofo(fofo);
511
                privateDealUserRepository.persist(privateDealUser);
512
            } else {
513
                Counter counter = null;
514
                try {
515
                    counter = counterRepository.selectById(privateDealUser.getCounterId());
516
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
517
                    LOGGER.error("Counter not found with id [{}]", privateDealUser.getCounterId());
518
                }
519
                if (counter == null) {
520
                    this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
521
                } else {
522
                    counter.setGstin(gstNumber);
523
                    counterRepository.persist(counter);
524
                }
525
                privateDealUser.setFofo(fofo);
526
                privateDealUserRepository.persist(privateDealUser);
527
            }
528
        }
23955 govind 529
 
31734 tejbeer 530
        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
531
        privateDealUserAddressMapping.setUserId(retailer.getId());
532
        privateDealUserAddressMapping.setAddressId(retailerAddressId);
533
        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
534
    }
23955 govind 535
 
31734 tejbeer 536
    // Specifically set isFofo to true that has to be used by old system
537
    private void createPrivateDealUser(int retailerId, int counterId, boolean fofo) {
538
        PrivateDealUser privateDealUser = new PrivateDealUser();
539
        privateDealUser.setActive(true);
540
        privateDealUser.setBulkShipmentAmountLimit(fofo ? 1000000 : 50000);
541
        privateDealUser.setId(retailerId);
542
        privateDealUser.setCounterId(counterId);
543
        privateDealUser.setFofo(fofo);
544
        privateDealUserRepository.persist(privateDealUser);
545
    }
23955 govind 546
 
31734 tejbeer 547
    private Integer createCounter(String emailId, String gstNumber, String mobileNumber, String name, int addressId) {
548
        if (gstNumber != null && !gstNumber.isEmpty()) {
549
            Counter counter = new Counter();
550
            counter.setEmailId(emailId);
551
            counter.setGstin(gstNumber);
552
            counter.setMobileNumber(mobileNumber);
553
            counter.setName(name);
554
            counter.setAddressId(addressId);
555
            counterRepository.persist(counter);
556
            return counter.getId();
557
        } else {
558
            return null;
559
        }
560
    }
23955 govind 561
 
31734 tejbeer 562
    private Address updateRetailerAddress(Address address, CustomAddress customAddress, int retailerId) throws ProfitMandiBusinessException {
563
        if (address == null) {
564
            address = new Address();
565
            address.setRetaierId(retailerId);
566
            this.updateAddress(address, customAddress);
567
            // addressRepository.persist(addressRetailer);
23955 govind 568
 
31734 tejbeer 569
            final RetailerRegisteredAddress retailerRegisteredAddress = new RetailerRegisteredAddress();
570
            retailerRegisteredAddress.setRetailerId(retailerId);
571
            retailerRegisteredAddress.setAddressId(address.getId());
572
            retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
573
        } else {
574
            this.updateAddress(address, customAddress);
575
            RetailerRegisteredAddress retailerRegisteredAddress = retailerRegisteredAddressRepository.selectByRetailerId(retailerId);
576
            retailerRegisteredAddress.setAddressId(address.getId());
577
            retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
578
        }
579
        return address;
580
    }
23955 govind 581
 
31734 tejbeer 582
    private void updateAddress(Address address, CustomAddress customAddress) throws ProfitMandiBusinessException {
583
        address.setName(customAddress.getName());
584
        address.setPhoneNumber(customAddress.getPhoneNumber());
585
        address.setLine1(customAddress.getLine1());
586
        address.setLine2(customAddress.getLine2());
587
        address.setCity(customAddress.getCity());
588
        address.setPinCode(customAddress.getPinCode());
589
        State state = stateRepository.selectByName(customAddress.getState());
590
        if (state == null) {
591
            throw new ProfitMandiBusinessException("State name", "Invalid State - Pls Contact Technology", "Invalid State - Pls Contact Technology");
592
        }
593
        address.setState(state.getName());
594
        addressRepository.persist(address);
595
        LOGGER.info("Address Updated" + address);
596
    }
23955 govind 597
 
31734 tejbeer 598
    private void updateRetailerShops(List<Shop> shops, Set<CustomShop> customShops, int retailerId, Address sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
599
        if (shops.isEmpty()) {
600
            for (CustomShop customShop : customShops) {
601
                Shop shop = new Shop();
602
                this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
603
                shops.add(shop);
604
            }
605
        } else {
606
            for (Shop shop : shops) {
607
                for (CustomShop customShop : customShops) {
608
                    if (shop.getId() == customShop.getShopId()) {
609
                        this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
610
                    }
611
                }
612
            }
613
            for (CustomShop customShop : customShops) {
614
                if (customShop.getShopId() == 0) {
615
                    Shop shop = new Shop();
616
                    this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
617
                    shops.add(shop);
618
                }
619
            }
620
        }
621
    }
23955 govind 622
 
31734 tejbeer 623
    private void createOrUpdateShop(Shop shop, CustomShop customShop, int retailerId, Address sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
624
        shop.setRetailerId(retailerId);
625
        shop.setName(customShop.getName());
626
        if (customShop.getDocumentId() > 0) {
627
            if (shop.getDocumentId() != null && shop.getDocumentId() != customShop.getDocumentId()) {
628
                try {
629
                    documentRepository.deleteById(shop.getDocumentId());
630
                } catch (Exception e) {
631
                    e.printStackTrace();
632
                }
633
            }
634
            shop.setDocumentId(customShop.getDocumentId());
635
            documentRepository.markDocumentAsPersisted(customShop.getDocumentId());
636
        }
637
        if (shop.getAddressId() == null) {
638
            Address address = null;
639
            if (customShop.isSameAsRetailerAddress()) {
640
                address = sameAsRetailerAddressValue;
641
            } else {
642
                // shop.setDocumentId(customShop.getDocumentId());
643
                address = new Address();
644
                this.updateAddress(address, customShop.getAddress());
645
            }
646
            shop.setAddressId(address.getId());
647
            shop.setAddress(address);
648
            shopRepository.persist(shop);
649
            ShopAddress shopAddress = null;
650
            try {
651
                shopAddress = shopAddressRepository.selectByShopId(shop.getId());
652
                shopAddress.setAddressId(address.getId());
653
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
654
                shopAddress = new ShopAddress();
655
                shopAddress.setAddressId(address.getId());
656
                shopAddress.setShopId(shop.getId());
657
            }
658
            shopAddressRepository.persist(shopAddress);
659
        } else {
660
            Address address = null;
661
            try {
662
                address = addressRepository.selectById(shop.getAddressId());
663
                CustomAddress customAddress = customShop.getAddress();
664
                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()))) {
665
                    address = new Address();
666
                    ShopAddress shopAddress = shopAddressRepository.selectByShopId(shop.getId());
667
                    this.updateAddress(address, customAddress);
668
                    shopAddress.setAddressId(address.getId());
669
                    shopAddressRepository.persist(shopAddress);
670
                    shop.setAddress(address);
671
                    shopRepository.persist(shop);
672
                }
673
            } catch (Exception e) {
674
                if (customShop.isSameAsRetailerAddress()) {
675
                    address = sameAsRetailerAddressValue;
676
                } else {
677
                    // shop.setDocumentId(customShop.getDocumentId());
678
                    address = new Address();
679
                    this.updateAddress(address, customShop.getAddress());
680
                }
681
                shop.setAddressId(address.getId());
682
                shop.setAddress(address);
683
                shopRepository.persist(shop);
684
                ShopAddress shopAddress = null;
685
                try {
686
                    shopAddress = shopAddressRepository.selectByShopId(shop.getId());
687
                    shopAddress.setAddressId(address.getId());
688
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
689
                    shopAddress = new ShopAddress();
690
                    shopAddress.setAddressId(address.getId());
691
                    shopAddress.setShopId(shop.getId());
692
                }
693
                shopAddressRepository.persist(shopAddress);
694
            }
23955 govind 695
 
31734 tejbeer 696
        }
23955 govind 697
 
31734 tejbeer 698
    }
23955 govind 699
 
31734 tejbeer 700
    private void addAddress(List<Shop> shops) {
701
        Set<Integer> shopIds = this.toShopIds(shops);
702
        if (shopIds.isEmpty()) {
703
            return;
704
        }
705
        List<ShopAddress> shopAddresses = shopAddressRepository.selectByShopIds(shopIds);
706
        Map<Integer, Address> addressIdAddressMap = this.toAddressIdAddressMap(shopAddresses);
23955 govind 707
 
31734 tejbeer 708
        for (Shop shop : shops) {
709
            shop.setAddress(addressIdAddressMap.get(shop.getAddressId()));
710
        }
711
    }
22980 ashik.ali 712
 
31734 tejbeer 713
    private Map<Integer, Address> toAddressIdAddressMap(List<ShopAddress> shopAddresses) {
714
        Map<Integer, Address> addressIdAddressMap = new HashMap<>();
715
        List<Integer> addressIds = this.toAddressIds(shopAddresses);
716
        List<Address> addresses = addressRepository.selectByIds(addressIds);
717
        for (Address address : addresses) {
718
            addressIdAddressMap.put(address.getId(), address);
719
        }
720
        return addressIdAddressMap;
721
    }
23955 govind 722
 
31734 tejbeer 723
    private List<Integer> toAddressIds(List<ShopAddress> shopAddresses) {
724
        Function<ShopAddress, Integer> shopAddressToAddressIdFunction = new Function<ShopAddress, Integer>() {
725
            @Override
726
            public Integer apply(ShopAddress shopAddress) {
727
                return shopAddress.getAddressId();
728
            }
729
        };
730
        return shopAddresses.stream().map(shopAddressToAddressIdFunction).collect(Collectors.toList());
731
    }
23955 govind 732
 
31734 tejbeer 733
    private Set<Integer> toShopIds(List<Shop> shops) {
734
        Function<Shop, Integer> shopToAddressIdFunction = new Function<Shop, Integer>() {
735
            @Override
736
            public Integer apply(Shop shop) {
737
                return shop.getId();
738
            }
739
        };
740
        return shops.stream().map(shopToAddressIdFunction).collect(Collectors.toSet());
741
    }
23955 govind 742
 
31734 tejbeer 743
    private String toString(List<UserRole> userRoles) {
744
        Set<Integer> roleIds = new HashSet<>();
745
        for (UserRole userRole : userRoles) {
746
            roleIds.add(userRole.getRoleId());
747
        }
748
        List<Role> roles = roleRepository.selectByIds(roleIds);
31735 amit.gupta 749
        Function<Role, String> roleToNameFunction = role -> String.valueOf(role.getName());
31734 tejbeer 750
        Set<String> userRoleStrings = roles.stream().map(roleToNameFunction).collect(Collectors.toSet());
751
        return String.join(", ", userRoleStrings);
752
    }
23955 govind 753
 
31734 tejbeer 754
    private FofoStore createFofoStoreCodeByRetailerId(int retailerId, String districtName, String stateName, UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
755
        FofoStore fofoStore = null;
756
        try {
757
            fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
758
            fofoStore.setActivationType(ActivationType.ACTIVE);
30097 tejbeer 759
 
31734 tejbeer 760
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
23955 govind 761
 
31734 tejbeer 762
        }
23955 govind 763
 
31734 tejbeer 764
        if (fofoStore != null) {
765
            fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
766
            fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
767
            fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
768
            fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
769
            fofoStore.setFofoType(updateRetailerRequest.getFofoType());
23955 govind 770
 
31734 tejbeer 771
        } else {
772
            int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailerId);
773
            Address retailerAddress = addressRepository.selectById(retailerAddressId);
23955 govind 774
 
31734 tejbeer 775
            // StateInfo stateInfo = null;
776
            State stateInfo = null;
777
            try {
30527 tejbeer 778
 
31734 tejbeer 779
                stateInfo = stateRepository.selectByName(retailerAddress.getState());
780
                // stateInfo = Utils.getStateInfo(retailerAddress.getState());
781
            } catch (Exception e) {
782
                // TODO Auto-generated catch block
783
                e.printStackTrace();
784
                // throw new ProfitMandiBusinessException();
785
            }
786
            DistrictMaster districtMaster = districtMasterRepository.selectByNameAndStateShortName(districtName, stateInfo.getShortName());
23955 govind 787
 
31734 tejbeer 788
            fofoStore = new FofoStore();
789
            fofoStore.setId(retailerId);
790
            fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
791
            fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
31730 tejbeer 792
 
31734 tejbeer 793
            fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
794
            fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
795
            String latestStoreCode = fofoStoreRepository.selectLatestStore().getCode();
796
            int latestCodeCounter = Integer.parseInt(latestStoreCode.replaceAll("[A-Z]", ""));
797
            String fofoStoreCode = StringUtils.generateFofoStoreSequence(
798
                    districtMaster.getStateShortName() + districtMaster.getShortName(), latestCodeCounter + 1);
799
            fofoStore.setCode(fofoStoreCode);
800
            fofoStore.setBagsLastCredited(LocalDateTime.now());
801
            fofoStore.setFofoType(updateRetailerRequest.getFofoType());
802
            fofoStore.setActivationType(ActivationType.ACTIVE);
803
            fofoStoreRepository.persist(fofoStore);
28908 tejbeer 804
 
31734 tejbeer 805
            // Auto fill in onboarding Panel
806
            PartnerOnBoardingPanel pobp = partnerOnBoardingPanelRepository.selectByPhoneNumber(Long.parseLong(retailerAddress.getPhoneNumber()));
807
            if (pobp != null) {
28908 tejbeer 808
 
31734 tejbeer 809
                PartnerVerificationpanel partnerVerificationpanel = partnerOnboardingVerificationRepository.selectByOnboardingId(pobp.getId());
29042 tejbeer 810
 
31734 tejbeer 811
                if (partnerVerificationpanel != null) {
812
                    if (partnerVerificationpanel.getApproval().equals(PartnerVerificationApprovalStatus.YES)) {
813
                        pobp.setCode(fofoStore.getCode());
29042 tejbeer 814
 
31734 tejbeer 815
                        storeTimelineTatService.onCodeCreated(pobp.getId());
29042 tejbeer 816
 
31734 tejbeer 817
                    }
29042 tejbeer 818
 
31734 tejbeer 819
                }
29042 tejbeer 820
 
31734 tejbeer 821
            }
30719 tejbeer 822
 
31734 tejbeer 823
            PincodePartner pincodePartner = pincodePartnerRepository.selectPartnerByPincode(retailerAddress.getPinCode(), fofoStore.getId());
824
            if (pincodePartner == null) {
825
                PincodePartner pinPartner = new PincodePartner();
826
                pinPartner.setFofoId(fofoStore.getId());
827
                pinPartner.setPincode(retailerAddress.getPinCode());
828
                pincodePartnerRepository.perist(pinPartner);
829
            }
830
        }
23955 govind 831
 
31734 tejbeer 832
        return fofoStore;
833
    }
23955 govind 834
 
31734 tejbeer 835
    @Override
836
    public FofoStore createFofoStoreCodeByUserId(int userId, String districtName, String stateName, UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
837
        User user = userRepository.selectById(userId);
838
        // = userAccountRepository.selectRetailerIdByUserId(user.getId());
839
        UserAccount userAccounts = userAccountRepository.selectSaholicByUserId(user.getId());
840
        Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
841
        Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
842
        try {
843
            userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleFofo.getId());
844
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
845
            throw new ProfitMandiBusinessException(ProfitMandiConstants.USER_ID, user.getId(), "USR_1013");
846
        }
847
        return this.createFofoStoreCodeByRetailerId(retailer.getId(), districtName, stateName, updateRetailerRequest);
23955 govind 848
 
31734 tejbeer 849
    }
23955 govind 850
 
31734 tejbeer 851
    @Override
852
    public List<DistrictMaster> getAllDistrictMaster(String stateName) {
853
        // StateInfo stateInfo = null;
854
        State stateInfo = null;
855
        try {
856
            // stateInfo = Utils.getStateInfo(stateName);
30525 tejbeer 857
 
31734 tejbeer 858
            stateInfo = stateRepository.selectByName(stateName);
859
        } catch (Exception e) {
860
            e.printStackTrace();
861
            // throw new ProfitMandiBusinessException();
862
        }
863
        return districtMasterRepository.selectByStateShortName(stateInfo.getShortName());
864
    }
22980 ashik.ali 865
 
31734 tejbeer 866
    @Override
867
    public Map<Integer, CustomRetailer> getFofoRetailers(List<Integer> fofoIds) {
868
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
869
        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));
870
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
871
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
872
        for (Address address : addresses) {
873
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
874
            CustomRetailer customRetailer = new CustomRetailer();
875
            customRetailer.setEmail(user.getEmailId());
876
            customRetailer.setBusinessName(address.getName());
877
            customRetailer.setMobileNumber(address.getPhoneNumber());
878
            try {
879
                FofoStore fs = fofoStoreRepository.selectByRetailerId(address.getRetaierId());
880
                customRetailer.setCode(fs.getCode());
881
                customRetailer.setActivationType(fs.getActivationType());
882
                customRetailer.setCounterSize(fs.getCounterSize());
31180 tejbeer 883
 
31743 tejbeer 884
 
885
                customRetailer.setCounterPotential(fs.getCounterPotential());
886
 
31734 tejbeer 887
                customRetailer.setWarehouseId(fs.getWarehouseId());
888
                customRetailer.setPartnerId(fs.getId());
889
                customRetailer.setFofoType(fs.getFofoType());
890
            } catch (Exception e) {
891
                continue;
892
            }
893
            try {
894
                customRetailer.setCartId(user.getActiveCartId());
895
                PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
896
                Counter counter = counterRepository.selectById(pdu.getCounterId());
897
                customRetailer.setGstNumber(counter.getGstin());
898
            } catch (Exception e) {
899
                customRetailer.setGstNumber(null);
900
            }
901
            CustomAddress address1 = new CustomAddress();
902
            address1.setCity(address.getCity());
903
            address1.setState(address.getState());
904
            address1.setLine1(address.getLine1());
905
            address1.setLine2(address.getLine2());
906
            address1.setPinCode(address.getPinCode());
907
            address1.setName(address.getName());
908
            customRetailer.setAddress(address1);
909
            customRetailer.setDisplayName(
910
                    customRetailer.getBusinessName() + "-" + customRetailer.getCode() + "- " + address1.getCity());
911
            customRetailersMap.put(customRetailer.getPartnerId(), customRetailer);
912
        }
913
        return customRetailersMap;
914
    }
25295 amit.gupta 915
 
31734 tejbeer 916
    @Override
917
    @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
918
    public CustomRetailer getFofoRetailer(int fofoId) throws ProfitMandiBusinessException {
919
        com.spice.profitmandi.dao.entity.user.User saholicUser = userUserRepository.selectById(fofoId);
31862 tejbeer 920
 
921
        User dtrUser = userRepository.selectByEmailId(saholicUser.getEmailId());
31734 tejbeer 922
        FofoStore store = fofoStoreRepository.selectByRetailerId(fofoId);
923
        Address address = null;
924
        try {
925
            address = addressRepository.selectById(saholicUser.getAddressId());
926
        } catch (ProfitMandiBusinessException e1) {
927
            // TODO Auto-generated catch block
928
            e1.printStackTrace();
929
        }
930
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
931
        CustomRetailer customRetailer = new CustomRetailer();
932
        customRetailer.setEmail(saholicUser.getEmailId());
933
        customRetailer.setBusinessName(address.getName());
934
        customRetailer.setMobileNumber(address.getPhoneNumber());
31862 tejbeer 935
        customRetailer.setFirstName(dtrUser.getFirstName());
936
        customRetailer.setLastName(dtrUser.getLastName());
31734 tejbeer 937
        try {
938
            customRetailer.setCartId(saholicUser.getActiveCartId());
939
            PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
940
            Counter counter = counterRepository.selectById(pdu.getCounterId());
941
            customRetailer.setGstNumber(counter.getGstin());
942
        } catch (Exception e) {
943
            customRetailer.setGstNumber(null);
944
        }
945
        CustomAddress address1 = new CustomAddress();
946
        address1.setCity(address.getCity());
947
        address1.setState(address.getState());
948
        address1.setLine1(address.getLine1());
949
        address1.setLine2(address.getLine2());
950
        address1.setPinCode(address.getPinCode());
951
        address1.setPhoneNumber(address.getPhoneNumber());
952
        address1.setName(address.getName());
953
        customRetailer.setDisplayName(address.getName() + " - " + address.getCity());
954
        customRetailer.setAddress(address1);
955
        customRetailer.setPartnerId(address.getRetaierId());
956
        customRetailer.setCode(store.getCode());
957
        customRetailer.setActivationType(store.getActivationType());
958
        customRetailer.setWarehouseId(store.getWarehouseId());
959
        customRetailersMap.put(address.getRetaierId(), customRetailer);
960
        return customRetailer;
25295 amit.gupta 961
 
31734 tejbeer 962
    }
26125 amit.gupta 963
 
31734 tejbeer 964
    @Override
965
    public Map<Integer, CustomRetailer> getFofoRetailerUserId(List<Integer> fofoIds) {
966
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
967
        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));
968
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
969
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
970
        for (Address address : addresses) {
971
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
972
            CustomRetailer customRetailer = new CustomRetailer();
973
            customRetailer.setEmail(user.getEmailId());
974
            customRetailer.setBusinessName(address.getName());
975
            customRetailer.setMobileNumber(address.getPhoneNumber());
976
            int userId = 0;
977
            try {
978
                userId = userAccountRepository.selectUserIdByRetailerId(user.getId());
979
            } catch (ProfitMandiBusinessException e) {
980
                continue;
981
            }
982
            try {
983
                customRetailer.setCartId(user.getActiveCartId());
984
                PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
985
                Counter counter = counterRepository.selectById(pdu.getCounterId());
986
                customRetailer.setGstNumber(counter.getGstin());
987
            } catch (Exception e) {
988
                customRetailer.setGstNumber(null);
989
            }
990
            CustomAddress address1 = new CustomAddress();
991
            address1.setCity(address.getCity());
992
            address1.setState(address.getState());
993
            address1.setLine1(address.getLine1());
994
            address1.setLine2(address.getLine2());
995
            address1.setPinCode(address.getPinCode());
996
            address1.setName(address.getName());
997
            customRetailer.setAddress(address1);
998
            customRetailer.setPartnerId(address.getRetaierId());
999
            customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + address1.getCity());
1000
            customRetailersMap.put(userId, customRetailer);
1001
        }
1002
        return customRetailersMap;
1003
    }
25295 amit.gupta 1004
 
31734 tejbeer 1005
    @Override
1006
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap() {
1007
        Role roleFofo = null;
1008
        try {
1009
            roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
1010
        } catch (ProfitMandiBusinessException e) {
1011
            // TODO Auto-generated catch block
1012
            e.printStackTrace();
1013
        }
1014
        Role roleRetailer = null;
1015
        try {
1016
            roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
1017
        } catch (ProfitMandiBusinessException e) {
1018
            // TODO Auto-generated catch block
1019
            e.printStackTrace();
1020
        }
1021
        Set<Integer> roleIds = new HashSet<>();
1022
        roleIds.add(roleFofo.getId());
1023
        roleIds.add(roleRetailer.getId());
1024
        List<Integer> userIds = userRoleRepository.selectUserIdsByRoleIds(roleIds);
1025
        List<User> users = userRepository.selectAllByIds(new HashSet<>(userIds));
1026
        Map<Integer, Integer> userIdRetailerIdMap = this.getUserIdRetailerIdMap(userIds);
1027
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1028
        for (User user : users) {
1029
            retailerIdEmailIdMap.put(userIdRetailerIdMap.get(user.getId()), user.getEmailId());
1030
        }
1031
        return retailerIdEmailIdMap;
1032
    }
23955 govind 1033
 
31734 tejbeer 1034
    private Map<Integer, Integer> getUserIdRetailerIdMap(List<Integer> userIds) {
1035
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByUserIds(new HashSet<>(userIds));
1036
        Map<Integer, Integer> userIdRetailerIdMap = new HashMap<>();
1037
        for (UserAccount userAccount : userAccounts) {
1038
            userIdRetailerIdMap.put(userAccount.getUserId(), userAccount.getAccountKey());
1039
        }
1040
        return userIdRetailerIdMap;
1041
    }
25295 amit.gupta 1042
 
31734 tejbeer 1043
    private Map<Integer, String> getUserIdEmailIdMap(Set<Integer> userIds) {
1044
        List<User> users = userRepository.selectAllByIds(userIds);
1045
        Map<Integer, String> userIdEmailIdMap = new HashMap<>();
1046
        for (User user : users) {
1047
            userIdEmailIdMap.put(user.getId(), user.getEmailId());
1048
        }
1049
        return userIdEmailIdMap;
1050
    }
23509 amit.gupta 1051
 
31734 tejbeer 1052
    @Override
1053
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap(Set<Integer> retailerIds) {
1054
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1055
        Set<Integer> userIds = new HashSet<>();
1056
        for (UserAccount userAccount : userAccounts) {
1057
            userIds.add(userAccount.getUserId());
1058
        }
1059
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1060
        Map<Integer, String> userIdEmailIdMap = this.getUserIdEmailIdMap(userIds);
1061
        for (UserAccount userAccount : userAccounts) {
1062
            retailerIdEmailIdMap.put(userAccount.getAccountKey(), userIdEmailIdMap.get(userAccount.getUserId()));
1063
        }
1064
        return retailerIdEmailIdMap;
1065
    }
25295 amit.gupta 1066
 
31734 tejbeer 1067
    @Override
1068
    public Map<Integer, String> getAllFofoRetailerIdNameMap(List<Integer> storeIds) {
1069
        Map<Integer, CustomRetailer> retailersMap = this.getFofoRetailers(storeIds);
1070
        Map<Integer, String> retailerIdNameMap = new HashMap<>();
1071
        for (Map.Entry<Integer, CustomRetailer> entry : retailersMap.entrySet()) {
1072
            retailerIdNameMap.put(entry.getKey(), entry.getValue().getBusinessName() + "-" + entry.getValue().getAddress().getCity());
1073
        }
1074
        return retailerIdNameMap;
1075
    }
24168 amit.gupta 1076
 
31734 tejbeer 1077
    @Override
1078
    @Cacheable(value = "FofoRetailerIdNameMap", cacheManager = "thirtyMinsTimeOutCacheManager")
1079
    public Map<Integer, String> getAllFofoRetailerIdNameMap() {
1080
        List<FofoStore> stores = fofoStoreRepository.selectAll();
1081
        List<Integer> storeIds = stores.stream().map(x -> x.getId()).collect(Collectors.toList());
1082
        return this.getAllFofoRetailerIdNameMap(storeIds);
1083
    }
24349 amit.gupta 1084
 
31734 tejbeer 1085
    @Override
1086
    public List<MapWrapper<Integer, String>> getAllFofoRetailerIdNameList() {
1087
        List<MapWrapper<Integer, String>> mapWrappers = new ArrayList<>();
1088
        // TODO Auto-generated method stub
1089
        Map<Integer, String> fofoIdNameMap = this.getAllFofoRetailerIdNameMap();
1090
        fofoIdNameMap.forEach((fofoId, name) -> {
1091
            MapWrapper<Integer, String> idWrapper = new MapWrapper<>();
1092
            idWrapper.setKey(fofoId);
1093
            idWrapper.setValue(name);
1094
            mapWrappers.add(idWrapper);
1095
        });
1096
        return mapWrappers;
1097
    }
24349 amit.gupta 1098
 
31734 tejbeer 1099
    @Override
1100
    @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
1101
    public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly) {
1102
        // TODO Auto-generated method stub
1103
        Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream().filter(x -> !x.isInternal());
1104
        if (activeOnly) {
1105
            storeStream = storeStream.filter(x -> x.isActive());
1106
        }
1107
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1108
        return this.getFofoRetailers(storeIds);
1109
    }
25295 amit.gupta 1110
 
31734 tejbeer 1111
    @Override
1112
    @Cacheable(value = "allFofoRetailers", cacheManager = "thirtyMinsTimeOutCacheManager")
1113
    public Map<Integer, CustomRetailer> getAllFofoRetailers() {
1114
        // TODO Auto-generated method stub
1115
        Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream();
27861 tejbeer 1116
 
31734 tejbeer 1117
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1118
        return this.getFofoRetailers(storeIds);
1119
    }
27861 tejbeer 1120
 
31734 tejbeer 1121
    @Override
1122
    public LoginRequestResponseModel registerWebUser(LoginRequestResponseModel loginRequestModel) throws ProfitMandiBusinessException {
26522 amit.gupta 1123
 
31734 tejbeer 1124
        com.spice.profitmandi.dao.entity.user.User saholicUser = this.createSaholicUser(loginRequestModel);
1125
        loginRequestModel.setUserId(saholicUser.getId());
26522 amit.gupta 1126
 
31734 tejbeer 1127
        this.createRetailerAddress(loginRequestModel);
26522 amit.gupta 1128
 
31734 tejbeer 1129
        this.createPrivateDealUser(loginRequestModel);
1130
        this.updateSaholicUser(saholicUser.getId(), loginRequestModel.getBusinessAddress().getId());
26522 amit.gupta 1131
 
31734 tejbeer 1132
        return loginRequestModel;
26522 amit.gupta 1133
 
31734 tejbeer 1134
    }
26522 amit.gupta 1135
 
31734 tejbeer 1136
    private void createPrivateDealUser(LoginRequestResponseModel loginRequestModel) {
26522 amit.gupta 1137
 
31734 tejbeer 1138
        Integer counterId = this.createCounter(loginRequestModel.getEmail(), loginRequestModel.getGstNumber(), loginRequestModel.getBusinessAddress().getPhoneNumber(), loginRequestModel.getBusinessAddress().getName(), loginRequestModel.getBusinessAddress().getId());
1139
        try {
1140
            this.createPrivateDealUser(loginRequestModel.getUserId(), counterId, false);
1141
        } catch (Exception e) {
1142
            LOGGER.error("ERROR : ", e);
1143
        }
26522 amit.gupta 1144
 
31734 tejbeer 1145
        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
1146
        privateDealUserAddressMapping.setUserId(loginRequestModel.getUserId());
1147
        privateDealUserAddressMapping.setAddressId(loginRequestModel.getBusinessAddress().getId());
1148
        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
26522 amit.gupta 1149
 
31734 tejbeer 1150
    }
26522 amit.gupta 1151
 
31734 tejbeer 1152
    private void createRetailerAddress(LoginRequestResponseModel loginRequestResponseModel) throws ProfitMandiBusinessException {
1153
        Address businessAddress = loginRequestResponseModel.getBusinessAddress();
1154
        businessAddress.setRetaierId(loginRequestResponseModel.getUserId());
1155
        addressRepository.persist(businessAddress);
1156
    }
26536 amit.gupta 1157
 
31734 tejbeer 1158
    private String getHash256(String originalString) {
1159
        String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
1160
        LOGGER.info("Hash String {}", hashString);
1161
        return hashString;
1162
    }
26533 amit.gupta 1163
 
31734 tejbeer 1164
    @Override
1165
    @Cacheable(value = "fofoIdUrl", cacheManager = "thirtyMinsTimeOutCacheManager")
1166
    public Map<Integer, String> getAllFofoRetailerIdUrlMap() {
1167
        Map<Integer, String> fofoRetailerUrlMap = new HashMap<>();
1168
        List<FofoStore> stores = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive()).collect(Collectors.toList());
1169
        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));
1170
        for (FofoStore store : stores) {
1171
            LOGGER.info("Store is {}", store);
1172
            String districtShortName = store.getCode().replaceAll("\\d+", "").substring(2);
1173
            String stateShortName = store.getCode().replaceAll("\\d+", "").substring(0, 2);
1174
            DistrictMaster districtMaster = null;
1175
            LOGGER.info("Store shortname is {}", districtShortName);
1176
            districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName(districtShortName, stateShortName);
1177
            if (districtMaster == null) {
1178
                districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName("FB", "HR");
1179
            }
1180
            LOGGER.info("Store id - {}", store.getId());
1181
            // com.spice.profitmandi.dao.entity.user.User user = userMap.get(store.getId());
1182
            String urlString = districtMaster.getStateShortName() + "/" + Utils.getHyphenatedString(districtMaster.getName()) + "/" + store.getCode();
1183
            fofoRetailerUrlMap.put(store.getId(), urlString.toLowerCase());
1184
            LOGGER.info("Store is {} end", store);
26536 amit.gupta 1185
 
31734 tejbeer 1186
        }
1187
        return fofoRetailerUrlMap;
1188
    }
26533 amit.gupta 1189
 
31734 tejbeer 1190
    @Override
1191
    @Cacheable(value = "storeCodeRetailerMap", cacheManager = "thirtyMinsTimeOutCacheManager")
1192
    public Map<String, Integer> getStoreCodeRetailerMap() {
1193
        Map<Integer, String> map = this.getAllFofoRetailerIdUrlMap();
1194
        Map<String, Integer> returnMap = map.entrySet().stream().collect(Collectors.toMap(x -> {
1195
            String[] splitString = x.getValue().split("/");
1196
            return splitString[splitString.length - 1];
1197
        }, x -> x.getKey()));
1198
        LOGGER.info("returnMap {}", returnMap);
1199
        return returnMap;
1200
    }
27877 amit.gupta 1201
 
31734 tejbeer 1202
    @Override
1203
    public String getPartnerCriteriaString(PartnerCriteria partnerCriteria) {
27877 amit.gupta 1204
 
31734 tejbeer 1205
        StringBuilder sb = new StringBuilder();
1206
        if (partnerCriteria.getFofoIds().size() > 0) {
1207
            List<Integer> fofoIds = partnerCriteria.getFofoIds();
1208
            Map<Integer, CustomRetailer> customRetailers = this.getFofoRetailerUserId(fofoIds);
1209
            List<String> businessNames = customRetailers.values().stream().map(x -> x.getBusinessName()).collect(Collectors.toList());
1210
            sb.append(String.join(", ", businessNames));
27877 amit.gupta 1211
 
31734 tejbeer 1212
        } else {
1213
            sb.append("All");
1214
            if (partnerCriteria.getPartnerTypes().size() > 0) {
1215
                sb.append(" ").append(String.join(", ", partnerCriteria.getPartnerTypes().stream().map(x -> x.getValue()).collect(Collectors.toList())));
1216
            }
1217
            sb.append(" partners ");
1218
            if (partnerCriteria.getRegionIds().size() > 0) {
1219
                sb.append("from ");
1220
                sb.append(String.join(", ", partnerCriteria.getRegionIds().stream().map(x -> ProfitMandiConstants.WAREHOUSE_MAP.get(x)).collect(Collectors.toList())));
1221
            }
1222
            if (partnerCriteria.getExcludeFofoIds() != null && partnerCriteria.getExcludeFofoIds().size() > 0) {
1223
                sb.append("excluding ");
1224
                Map<Integer, CustomRetailer> customRetailers = this.getFofoRetailerUserId(partnerCriteria.getExcludeFofoIds());
1225
                List<String> businessNames = customRetailers.values().stream().map(x -> x.getBusinessName()).collect(Collectors.toList());
1226
                sb.append(String.join(", ", businessNames));
1227
            }
1228
        }
1229
        return sb.toString();
1230
    }
30097 tejbeer 1231
 
31734 tejbeer 1232
    @Override
1233
    public Map<Integer, CustomRetailer> getFofoRetailersPaginated(boolean activeOnly, int offset, int limit, FofoType fofoType) {
30097 tejbeer 1234
 
31734 tejbeer 1235
        Stream<FofoStore> storeStream = fofoStoreRepository.selectByStatusFofoType(activeOnly, fofoType, offset, limit).stream();
30219 tejbeer 1236
 
31734 tejbeer 1237
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1238
        return this.getFofoRetailers(storeIds);
1239
    }
30219 tejbeer 1240
 
22980 ashik.ali 1241
}