Subversion Repositories SmartDukaan

Rev

Rev 32967 | Rev 33025 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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