Subversion Repositories SmartDukaan

Rev

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