Subversion Repositories SmartDukaan

Rev

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