Subversion Repositories SmartDukaan

Rev

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

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