Subversion Repositories SmartDukaan

Rev

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