Subversion Repositories SmartDukaan

Rev

Rev 35440 | Rev 35956 | 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
 
35289 amit 3
import com.fasterxml.jackson.databind.ObjectMapper;
26528 amit.gupta 4
import com.google.common.hash.Hashing;
35289 amit 5
import com.google.gson.Gson;
30097 tejbeer 6
import com.spice.profitmandi.common.enumuration.ActivationType;
7
import com.spice.profitmandi.common.enumuration.FofoType;
22980 ashik.ali 8
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30017 amit.gupta 9
import com.spice.profitmandi.common.model.*;
23329 ashik.ali 10
import com.spice.profitmandi.common.util.StringUtils;
11
import com.spice.profitmandi.common.util.Utils;
35418 aman 12
import com.spice.profitmandi.dao.entity.catalog.BrandCatalog;
35203 amit 13
import com.spice.profitmandi.dao.entity.dtr.*;
22980 ashik.ali 14
import com.spice.profitmandi.dao.entity.dtr.User;
30017 amit.gupta 15
import com.spice.profitmandi.dao.entity.fofo.*;
24349 amit.gupta 16
import com.spice.profitmandi.dao.entity.inventory.State;
33124 ranu 17
import com.spice.profitmandi.dao.entity.logistics.AST;
18
import com.spice.profitmandi.dao.entity.logistics.ASTRepository;
30017 amit.gupta 19
import com.spice.profitmandi.dao.entity.user.*;
23063 ashik.ali 20
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
23106 ashik.ali 21
import com.spice.profitmandi.dao.enumuration.dtr.RetailerType;
23136 ashik.ali 22
import com.spice.profitmandi.dao.enumuration.dtr.RoleType;
23365 ashik.ali 23
import com.spice.profitmandi.dao.enumuration.fofo.PaymentOptionType;
29042 tejbeer 24
import com.spice.profitmandi.dao.enumuration.transaction.PartnerVerificationApprovalStatus;
34813 aman 25
import com.spice.profitmandi.dao.model.LastMonthCreditedIncomeModel;
35203 amit 26
import com.spice.profitmandi.dao.repository.dtr.*;
22980 ashik.ali 27
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
34813 aman 28
import com.spice.profitmandi.dao.repository.fofo.*;
24349 amit.gupta 29
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
35289 amit 30
import com.spice.profitmandi.dao.repository.trialOnboarding.TrialFormRepository;
30017 amit.gupta 31
import com.spice.profitmandi.dao.repository.user.*;
33124 ranu 32
import com.spice.profitmandi.service.PostOfficeService;
35203 amit 33
import com.spice.profitmandi.service.catalog.BrandsService;
23043 ashik.ali 34
import in.shop2020.model.v1.user.CartStatus;
30017 amit.gupta 35
import org.apache.logging.log4j.LogManager;
36
import org.apache.logging.log4j.Logger;
37
import org.springframework.beans.factory.annotation.Autowired;
38
import org.springframework.beans.factory.annotation.Qualifier;
39
import org.springframework.cache.annotation.Cacheable;
35289 amit 40
import org.springframework.mail.javamail.JavaMailSender;
30017 amit.gupta 41
import org.springframework.stereotype.Component;
23043 ashik.ali 42
 
30017 amit.gupta 43
import java.nio.charset.StandardCharsets;
34813 aman 44
import java.time.LocalDate;
30017 amit.gupta 45
import java.time.LocalDateTime;
34813 aman 46
import java.time.YearMonth;
47
import java.time.format.DateTimeFormatter;
30017 amit.gupta 48
import java.util.*;
49
import java.util.function.Function;
50
import java.util.stream.Collectors;
51
import java.util.stream.Stream;
52
 
22980 ashik.ali 53
@Component
54
public class RetailerServiceImpl implements RetailerService {
23955 govind 55
 
31734 tejbeer 56
    private static final Logger LOGGER = LogManager.getLogger(RetailerServiceImpl.class);
35289 amit 57
    private static final String[] TRIAL_CODE_CREATION_AUDIENCE = new String[]{"amit.gupta@smartdukaan.com"};
58
    //private static final String [] TRIAL_CODE_CREATION_AUDIENCE = new String[]{};
23955 govind 59
 
31734 tejbeer 60
    @Autowired
61
    private RetailerRepository retailerRepository;
23955 govind 62
 
31734 tejbeer 63
    @Autowired
64
    private RetailerBlockBrandsRepository retailerBlockBrandsRepository;
28024 tejbeer 65
 
31734 tejbeer 66
    @Autowired
67
    private UserAccountRepository userAccountRepository;
23955 govind 68
 
31734 tejbeer 69
    @Autowired
70
    private Mongo mongoClient;
28024 tejbeer 71
 
31734 tejbeer 72
    @Autowired
35289 amit 73
    Gson gson;
74
 
75
    @Autowired
31734 tejbeer 76
    private UserRepository userRepository;
35289 amit 77
    @Autowired
78
    ObjectMapper objectMapper;
23955 govind 79
 
35289 amit 80
 
31734 tejbeer 81
    @Autowired
82
    private CartRepository cartRepository;
23955 govind 83
 
31734 tejbeer 84
    @Autowired
85
    private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
23955 govind 86
 
31734 tejbeer 87
    @Autowired
88
    private AddressRepository addressRepository;
23955 govind 89
 
31734 tejbeer 90
    @Autowired
91
    private ShopRepository shopRepository;
23955 govind 92
 
31734 tejbeer 93
    @Autowired
94
    private ShopAddressRepository shopAddressRepository;
23955 govind 95
 
31734 tejbeer 96
    @Autowired
97
    private UserRoleRepository userRoleRepository;
23955 govind 98
 
31734 tejbeer 99
    @Autowired
100
    private DocumentRepository documentRepository;
23955 govind 101
 
31734 tejbeer 102
    @Autowired
103
    private PrivateDealUserRepository privateDealUserRepository;
23955 govind 104
 
31734 tejbeer 105
    @Autowired
32737 amit.gupta 106
    private RetailerContactRepository retailerContactRepository;
107
 
108
    @Autowired
31734 tejbeer 109
    private PrivateDealUserAddressMappingRepository privateDealUserAddressMappingRepository;
23955 govind 110
 
31734 tejbeer 111
    @Autowired
112
    private CounterRepository counterRepository;
25295 amit.gupta 113
 
31734 tejbeer 114
    @Autowired
115
    private StateRepository stateRepository;
35289 amit 116
    @Autowired
117
    private TrialFormRepository trialFormRepository;
23955 govind 118
 
31734 tejbeer 119
    @Autowired
120
    @Qualifier("userUserRepository")
121
    private com.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;
23955 govind 122
 
31734 tejbeer 123
    @Autowired
124
    private DistrictMasterRepository districtMasterRepository;
23955 govind 125
 
31734 tejbeer 126
    @Autowired
127
    private FofoStoreRepository fofoStoreRepository;
23955 govind 128
 
31734 tejbeer 129
    @Autowired
33124 ranu 130
    private ASTRepository aSTRepository;
131
 
132
    @Autowired
133
    private PostOfficeService postOfficeService;
134
 
135
    @Autowired
31734 tejbeer 136
    private PaymentOptionRepository paymentOptionRepository;
23955 govind 137
 
31734 tejbeer 138
    @Autowired
139
    private FofoPartnerPaymentOptionRepository fofoPartnerPaymentOptionRepository;
23955 govind 140
 
31734 tejbeer 141
    @Autowired
142
    private RoleRepository roleRepository;
23955 govind 143
 
31734 tejbeer 144
    @Autowired
145
    private StoreTimelineTatService storeTimelineTatService;
28908 tejbeer 146
 
31734 tejbeer 147
    @Autowired
148
    private PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
28908 tejbeer 149
 
31734 tejbeer 150
    @Autowired
151
    private PartnerOnboardingVerificationRepository partnerOnboardingVerificationRepository;
29042 tejbeer 152
 
31734 tejbeer 153
    @Autowired
154
    private PincodePartnerRepository pincodePartnerRepository;
30719 tejbeer 155
 
34813 aman 156
    @Autowired
157
    SchemeInOutRepository schemeInOutRepository;
158
 
159
    @Autowired
160
    OfferPayoutRepository offerPayoutRepository;
161
 
162
    @Autowired
163
    PartnerTypeChangeService partnerTypeChangeService;
164
 
35203 amit 165
    @Autowired
166
    BrandsService brandsService;
35289 amit 167
    @Autowired
168
    private JavaMailSender googleMailSender;
35203 amit 169
 
31734 tejbeer 170
    @Override
171
    public Map<String, Object> getByEmailIdOrMobileNumber(String emailIdOrMobileNumber) throws ProfitMandiBusinessException {
172
        User user = null;
173
        int fofoId = Utils.SYSTEM_PARTNER_ID;
28024 tejbeer 174
 
31734 tejbeer 175
        try {
176
            user = userRepository.selectByEmailIdOrMobileNumber(emailIdOrMobileNumber);
177
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
23955 govind 178
 
31734 tejbeer 179
        }
180
        if (user == null) {
181
            try {
182
                user = userRepository.selectBySecondryEmailId(emailIdOrMobileNumber);
183
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
23955 govind 184
 
31734 tejbeer 185
            }
186
        }
187
        Map<String, Object> map = new HashMap<>();
35394 amit 188
        map.put("stateNames", stateRepository.selectAll().stream().map(State::getName).collect(Collectors.toList()));
35289 amit 189
        LOGGER.info("user - {}", user);
31734 tejbeer 190
        if (user != null) {
23955 govind 191
 
31734 tejbeer 192
            List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
23955 govind 193
 
31734 tejbeer 194
            Role role = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 195
 
31734 tejbeer 196
            map.put("userRoles", userRoles);
197
            map.put("user", user);
198
            // map.put("retailer", retailer);
199
            map.put("fofoRole", this.containsRoleType(userRoles, role.getId()));
23955 govind 200
 
31734 tejbeer 201
            map.put("userRoleNames", this.toString(userRoles));
202
            try {
203
                int retailerId = userAccountRepository.selectRetailerIdByUserId(user.getId());
204
                Retailer retailer = retailerRepository.selectById(retailerId);
23955 govind 205
 
31734 tejbeer 206
                map.put("retailer", retailer);
23955 govind 207
 
31734 tejbeer 208
                List<String> retailerBlockBrands = null;
209
                Set<String> brands = null;
210
                if (retailer.getId() != fofoId) {
35394 amit 211
                    brands = brandsService.getBrands(retailer.getId(), null, 3).stream().map(BrandCatalog::getName).collect(Collectors.toSet());
35203 amit 212
                    retailerBlockBrands = brandsService.partnerIneligibleBrands(fofoId);
28189 tejbeer 213
 
31734 tejbeer 214
                } else {
215
                    LOGGER.info("fofoId" + fofoId);
35394 amit 216
                    brands = brandsService.getBrands(fofoId, null, 3).stream().map(BrandCatalog::getName).collect(Collectors.toSet());
31734 tejbeer 217
                }
218
                map.put("brands", brands);
219
                map.put("retailerBlockBrands", retailerBlockBrands);
23955 govind 220
 
31734 tejbeer 221
                try {
35896 amit 222
                    FofoStore gstStore = fofoStoreRepository.selectByRetailerId(retailer.getId());
223
                    map.put("gstNumber", gstStore != null ? gstStore.getGstNumber() : null);
224
                } catch (ProfitMandiBusinessException e) {
225
                    LOGGER.error("FofoStore not found for GST lookup");
31734 tejbeer 226
                }
227
                try {
228
                    int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId());
229
                    Address retailerAddress = addressRepository.selectById(retailerAddressId);
230
                    map.put("retailerAddress", retailerAddress);
231
                    State state = stateRepository.selectByName(retailerAddress.getState());
232
                    // LOGGER.info("retailerAddress.." + retailerAddress);
233
                    List<DistrictMaster> districtMasters = districtMasterRepository.selectByStateShortName(state.getShortName());
234
                    map.put("districtMasters", districtMasters);
235
                    // LOGGER.info("districtMasters" + districtMasters);
236
                    List<Shop> shops = shopRepository.selectByRetailerId(retailer.getId());
237
                    map.put("shops", shops);
238
                    this.addAddress(shops);
33128 amit.gupta 239
 
240
                    if (this.containsRoleType(userRoles, role.getId())) {
241
                        try {
242
                            FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
243
                            map.put("fofoStore", fofoStore);
244
                            List<AST> astDetail = postOfficeService.getAreasAndTerritoriesByStateName(retailerAddress.getState());
245
                            LOGGER.info("astDetail {}", astDetail);
246
                            map.put("astDetail", astDetail);
247
 
248
 
249
                            // map.put("counterSize", fofoStore.getCounterSize().toString());
250
                            // LOGGER.info("fofoStore" + fofoStore);
251
                        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
252
                            LOGGER.error("FofoStore code not found");
253
                        }
254
                    }
31734 tejbeer 255
                    // LOGGER.info("shops" + shops);
256
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
257
                    LOGGER.error("Retailer Registered Address not found");
258
                }
259
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
260
                LOGGER.error("Retailer not found in user_account");
261
            }
35289 amit 262
        } else {
263
            try {
264
                TrialForm trialForm = trialFormRepository.selectByEmailOrMobile(emailIdOrMobileNumber);
35372 aman 265
                LOGGER.info("trialForm - {}", trialForm);
35289 amit 266
                map.put("trialForm", gson.toJson(trialForm));
267
            } catch (Exception e) {
268
                LOGGER.error("Retailer not found in user_account");
269
            }
31734 tejbeer 270
        }
23955 govind 271
 
31734 tejbeer 272
        return map;
273
    }
23955 govind 274
 
31734 tejbeer 275
    private boolean containsRoleType(List<UserRole> userRoles, int roleId) {
35394 amit 276
        return userRoles != null && userRoles.stream().anyMatch(ur -> ur.getRoleId() == roleId);
31734 tejbeer 277
    }
23955 govind 278
 
31734 tejbeer 279
    private List<UserRole> addRole(List<UserRole> userRoles, int userId, int roleId) {
280
        if (userRoles == null) {
281
            userRoles = new ArrayList<>();
282
        }
283
        if (!this.containsRoleType(userRoles, roleId)) {
284
            UserRole userRole = new UserRole();
285
            userRole.setUserId(userId);
286
            userRole.setRoleId(roleId);
287
            try {
288
                userRoleRepository.persist(userRole);
289
            } catch (ProfitMandiBusinessException e) {
290
                LOGGER.error("UserRole is already exist");
291
            }
292
            userRoles.add(userRole);
293
        }
294
        return userRoles;
23955 govind 295
 
31734 tejbeer 296
    }
23955 govind 297
 
31734 tejbeer 298
    private List<UserRole> removeRole(List<UserRole> userRoles, int userId, int roleId) {
299
        if (userRoles == null) {
300
            userRoles = new ArrayList<>();
301
            return userRoles;
302
        }
303
        try {
304
            userRoles.remove(userRoleRepository.deleteByRoleUserId(userId, roleId));
305
        } catch (Exception e) {
25295 amit.gupta 306
 
31734 tejbeer 307
        }
308
        return userRoles;
25295 amit.gupta 309
 
31734 tejbeer 310
    }
25295 amit.gupta 311
 
31734 tejbeer 312
    @SuppressWarnings("unchecked")
313
    @Override
33128 amit.gupta 314
    public Map<String, Object> updateRetailerDetails(UpdateRetailerRequest updateRetailerRequest) throws
315
            ProfitMandiBusinessException {
31734 tejbeer 316
        Map<String, Object> map = this.getByEmailIdOrMobileNumber(updateRetailerRequest.getEmailIdOrMobileNumber());
32953 amit.gupta 317
        User dtrUser = (User) map.get("user");
28024 tejbeer 318
 
32953 amit.gupta 319
        dtrUser = this.createUser(dtrUser, updateRetailerRequest);
28024 tejbeer 320
 
32953 amit.gupta 321
        map.put("user", dtrUser);
31734 tejbeer 322
        List<UserRole> userRoles = (List<UserRole>) map.get("userRoles");
323
        Role roleUser = roleRepository.selectByName(RoleType.USER.toString());
32953 amit.gupta 324
        userRoles = this.addRole(userRoles, dtrUser.getId(), roleUser.getId());
31734 tejbeer 325
        Retailer retailer = (Retailer) map.get("retailer");
32953 amit.gupta 326
        retailer = this.updateRetailer(dtrUser, retailer, updateRetailerRequest);
28024 tejbeer 327
 
31734 tejbeer 328
        map.put("retailer", retailer);
23955 govind 329
 
31734 tejbeer 330
        List<String> retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream().map(x -> x.getBlockBrands()).collect(Collectors.toList());
28024 tejbeer 331
 
31734 tejbeer 332
        LOGGER.info("retailerBlockBrands" + retailerBlockBrands);
28189 tejbeer 333
 
31734 tejbeer 334
        if (!retailerBlockBrands.isEmpty()) {
335
            retailerBlockBrandsRepository.deleteBrands(retailer.getId());
336
        }
28024 tejbeer 337
 
31734 tejbeer 338
        for (String blockBrand : updateRetailerRequest.getBlocksBrands()) {
339
            RetailerBlockBrands retailerBlockBrand = new RetailerBlockBrands();
28024 tejbeer 340
 
31734 tejbeer 341
            retailerBlockBrand.setFofoId(retailer.getId());
342
            retailerBlockBrand.setBlockBrands(blockBrand);
343
            retailerBlockBrandsRepository.persist(retailerBlockBrand);
28024 tejbeer 344
 
31734 tejbeer 345
        }
346
        map.put("retailerBlockBrands", retailerBlockBrands);
28024 tejbeer 347
 
31734 tejbeer 348
        Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
23955 govind 349
 
32953 amit.gupta 350
        userRoles = this.addRole(userRoles, dtrUser.getId(), roleRetailer.getId());
23955 govind 351
 
31734 tejbeer 352
        Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 353
 
31734 tejbeer 354
        if (updateRetailerRequest.isFofo()) {
32953 amit.gupta 355
            userRoles = this.addRole(userRoles, dtrUser.getId(), roleFofo.getId());
31734 tejbeer 356
        } else {
32953 amit.gupta 357
            userRoles = this.removeRole(userRoles, dtrUser.getId(), roleFofo.getId());
31734 tejbeer 358
        }
359
        map.put("fofoRole", this.containsRoleType(userRoles, roleFofo.getId()));
23955 govind 360
 
31734 tejbeer 361
        if (this.containsRoleType(userRoles, roleFofo.getId())) {
362
            this.createDefaultPaymentOption(retailer.getId());
363
        }
23955 govind 364
 
31734 tejbeer 365
        map.put("userRoles", userRoles);
366
        map.put("userRoleNames", this.toString(userRoles));
23955 govind 367
 
31734 tejbeer 368
        Address retailerAddress = (Address) map.get("retailerAddress");
369
        retailerAddress = this.updateRetailerAddress(retailerAddress, updateRetailerRequest.getAddress(), retailer.getId());
370
        map.put("retailerAddress", retailerAddress);
23955 govind 371
 
31734 tejbeer 372
        if (updateRetailerRequest.isFofo()) {
373
            FofoStore fofoStore = this.createFofoStoreCodeByRetailerId(retailer.getId(), updateRetailerRequest.getDistrictName(), retailerAddress.getState(), updateRetailerRequest);
374
            map.put("fofoStore", fofoStore);
375
            fofoStore.setActive(updateRetailerRequest.isActive());
33131 ranu 376
            List<AST> astDetail = postOfficeService.getAreasAndTerritoriesByStateName(retailerAddress.getState());
377
            map.put("astDetail", astDetail);
31734 tejbeer 378
        }
23955 govind 379
 
32953 amit.gupta 380
        this.createPrivateDealUser(dtrUser, updateRetailerRequest.isFofo(), updateRetailerRequest.getGstNumber(), retailer, retailerAddress.getId());
31734 tejbeer 381
        map.put("gstNumber", updateRetailerRequest.getGstNumber());
382
        this.updateSaholicUser(retailer.getId(), retailerAddress.getId());
23955 govind 383
 
31734 tejbeer 384
        List<Shop> shops = (List<Shop>) map.get("shops");
385
        if (shops == null) {
386
            shops = new ArrayList<>();
387
            map.put("shops", shops);
388
        }
389
        this.updateRetailerShops(shops, updateRetailerRequest.getShops(), retailer.getId(), retailerAddress);
23955 govind 390
 
31734 tejbeer 391
        return map;
23955 govind 392
 
31734 tejbeer 393
    }
23955 govind 394
 
31734 tejbeer 395
    private void createDefaultPaymentOption(int fofoId) {
396
        List<Integer> paymentOptionIds = fofoPartnerPaymentOptionRepository.selectPaymentOptionIdsByFofoId(fofoId);
397
        if (paymentOptionIds.isEmpty()) {
398
            PaymentOption paymentOption = null;
399
            try {
400
                paymentOption = paymentOptionRepository.selectByName(PaymentOptionType.CASH.toString());
401
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
402
                paymentOption = new PaymentOption();
403
                paymentOption.setName(PaymentOptionType.CASH.toString());
404
                paymentOptionRepository.persist(paymentOption);
405
            }
406
            FofoPartnerPaymentOption fofoPartnerPaymentOption = new FofoPartnerPaymentOption();
407
            fofoPartnerPaymentOption.setFofoId(fofoId);
408
            fofoPartnerPaymentOption.setPaymentOptionId(paymentOption.getId());
409
            fofoPartnerPaymentOptionRepository.persist(fofoPartnerPaymentOption);
410
        }
23955 govind 411
 
31734 tejbeer 412
    }
23955 govind 413
 
33128 amit.gupta 414
    private User createUser(User user, UpdateRetailerRequest updateRetailerRequest) throws
415
            ProfitMandiBusinessException {
32965 amit.gupta 416
 
417
        User dtrUser = null;
418
        try {
419
            dtrUser = userRepository.selectByMobileNumber(updateRetailerRequest.getUserMobileNumber());
420
        } catch (ProfitMandiBusinessException e) {
421
            //Ignore the exception
422
        }
33140 ranu 423
        if (dtrUser != null && (user == null || user.getId() != dtrUser.getId()))
424
            throw new ProfitMandiBusinessException("Mobile already exist", updateRetailerRequest.getUserMobileNumber(), dtrUser.getEmailId());
32966 amit.gupta 425
 
426
        User dtrUserByEmail = null;
427
        try {
428
            dtrUserByEmail = userRepository.selectByEmailId(updateRetailerRequest.getUserEmailId());
429
        } catch (ProfitMandiBusinessException e) {
430
            //ignore the exception
431
        }
33025 amit.gupta 432
        if (user != null && dtrUserByEmail != null && user.getId() != dtrUserByEmail.getId())
32965 amit.gupta 433
            throw new ProfitMandiBusinessException("Email already exist", updateRetailerRequest.getUserEmailId(), "");
32953 amit.gupta 434
 
435
 
31734 tejbeer 436
        if (user == null) {
437
            user = new User();
438
            user.setCity("");
439
            user.setPinCode(0);
440
            user.setState("");
441
            user.setPassword("");
442
            user.setMobile_verified(false);
443
            user.setReferral_url("");
444
            user.setGroup_id(1);
445
            user.setStatus(1);
446
            user.setActivated(true);
447
            user.setCreateTimestamp(LocalDateTime.now());
448
        }
449
        user.setActivated(updateRetailerRequest.isActive());
450
        user.setFirstName(updateRetailerRequest.getUserFirstName());
451
        user.setLastName(updateRetailerRequest.getUserLastName());
452
        user.setMobileNumber(updateRetailerRequest.getUserMobileNumber());
453
        user.setEmailId(updateRetailerRequest.getUserEmailId());
454
        user.setUsername(updateRetailerRequest.getUserEmailId());
455
        user.setUpdateTimestamp(LocalDateTime.now());
456
        userRepository.persist(user);
457
        return user;
23955 govind 458
 
31734 tejbeer 459
    }
23955 govind 460
 
31734 tejbeer 461
    private int createSaholicUser(User user, String retailerName) {
462
        com.spice.profitmandi.dao.entity.user.User saholicUser = null;
463
        try {
464
            saholicUser = userUserRepository.selectByEmailId(user.getEmailId());
465
        } catch (ProfitMandiBusinessException e) {
466
            LOGGER.info("User doesnt exist in old system");
467
        }
468
        if (saholicUser == null) {
469
            Cart cart = new Cart();
470
            cart.setCartStatus(CartStatus.ACTIVE);
471
            cartRepository.persist(cart);
472
            saholicUser = new com.spice.profitmandi.dao.entity.user.User();
473
            saholicUser.setEmailId(user.getEmailId());
474
            saholicUser.setName(retailerName);
475
            saholicUser.setActiveCartId(cart.getId());
476
            saholicUser.setCreateTimestamp(LocalDateTime.now());
477
            userUserRepository.persist(saholicUser);
23955 govind 478
 
31734 tejbeer 479
            UserAccount ua = new UserAccount();
480
            ua.setAccountKey(saholicUser.getId());
481
            ua.setUserId(user.getId());
482
            ua.setType(AccountType.saholic);
483
            userAccountRepository.persist(ua);
23063 ashik.ali 484
 
31734 tejbeer 485
            UserAccount ua2 = new UserAccount();
486
            ua2.setAccountKey(saholicUser.getActiveCartId());
487
            ua2.setUserId(user.getId());
488
            ua2.setType(AccountType.cartId);
489
            userAccountRepository.persist(ua2);
490
            LOGGER.info("created....");
491
        }
492
        return saholicUser.getId();
493
    }
23955 govind 494
 
31734 tejbeer 495
    private com.spice.profitmandi.dao.entity.user.User createSaholicUser(
32953 amit.gupta 496
            LoginRequestResponseModel loginRequestResponseModel) {
31734 tejbeer 497
        com.spice.profitmandi.dao.entity.user.User saholicUser = null;
498
        try {
499
            saholicUser = userUserRepository.selectByEmailId(loginRequestResponseModel.getEmail());
500
            saholicUser.setCreateTimestamp(LocalDateTime.now());
501
        } catch (ProfitMandiBusinessException e) {
502
            LOGGER.info("User doesnt exist in old system");
503
        }
504
        if (saholicUser == null) {
505
            Cart cart = new Cart();
506
            cart.setCartStatus(CartStatus.ACTIVE);
507
            cartRepository.persist(cart);
508
            saholicUser = new com.spice.profitmandi.dao.entity.user.User();
509
            saholicUser.setPassword(getHash256(loginRequestResponseModel.getPassword()));
510
            saholicUser.setEmailId(loginRequestResponseModel.getEmail());
511
            saholicUser.setName(loginRequestResponseModel.getCustomerName());
512
            saholicUser.setActiveCartId(cart.getId());
513
            saholicUser.setCreateTimestamp(LocalDateTime.now());
514
            loginRequestResponseModel.setPassword(null);
515
            userUserRepository.persist(saholicUser);
516
        }
517
        return saholicUser;
518
    }
26522 amit.gupta 519
 
33128 amit.gupta 520
    private Retailer updateRetailer(User user, Retailer retailer, UpdateRetailerRequest updateRetailerRequest) throws
521
            ProfitMandiBusinessException {
31734 tejbeer 522
        if (retailer == null) {
523
            LOGGER.info("createSaholicUser.....");
524
            int saholicUserId = this.createSaholicUser(user, updateRetailerRequest.getName());
525
            retailer = new Retailer();
526
            retailer.setId(saholicUserId);
527
        }
528
        retailer.setActive(updateRetailerRequest.isActive());
529
        user.setActivated(updateRetailerRequest.isActive());//
530
        // this.createRole(user.getId(), RoleType.RETAILER);
531
        retailer.setName(updateRetailerRequest.getName());
532
        retailer.setNumber(updateRetailerRequest.getNumber());
533
        if (updateRetailerRequest.getNumber() == null || updateRetailerRequest.getNumber().isEmpty()) {
534
            retailer.setType(RetailerType.UNREGISTERED_SHOP);
535
        } else {
536
            retailer.setType(RetailerType.GSTIN);
537
        }
538
        if (updateRetailerRequest.getDocumentId() > 0) {
539
            if (retailer.getDocumentId() != null && retailer.getDocumentId() != updateRetailerRequest.getDocumentId()) {
540
                try {
541
                    documentRepository.deleteById(retailer.getDocumentId());
542
                } catch (Exception e) {
543
                    e.printStackTrace();
544
                }
545
            }
546
            retailer.setDocumentId(updateRetailerRequest.getDocumentId());
547
            documentRepository.markDocumentAsPersisted(updateRetailerRequest.getDocumentId());
548
        }
549
        retailerRepository.persist(retailer);
550
        return retailer;
551
    }
23955 govind 552
 
31734 tejbeer 553
    private void updateSaholicUser(int retailerId, int retailerAddressId) {
554
        try {
555
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(retailerId);
556
            user.setAddressId(retailerAddressId);
32555 amit.gupta 557
            Cart cart = cartRepository.selectById(user.getActiveCartId());
558
            cart.setAddressId(retailerAddressId);
31734 tejbeer 559
        } catch (ProfitMandiBusinessException e) {
23955 govind 560
 
31734 tejbeer 561
        }
562
    }
23955 govind 563
 
33128 amit.gupta 564
    private void createPrivateDealUser(User user, boolean fofo, String gstNumber, Retailer retailer,
565
                                       int retailerAddressId) {
31734 tejbeer 566
        PrivateDealUser privateDealUser = null;
567
        try {
568
            privateDealUser = privateDealUserRepository.selectById(retailer.getId());
569
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
570
            LOGGER.error("PrivateDealUser not found");
571
        }
23955 govind 572
 
31734 tejbeer 573
        // = privateDealUserRepository.selectById(saholicUser.getId());
574
        if (privateDealUser == null) {
575
            Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
576
            try {
577
                this.createPrivateDealUser(retailer.getId(), counterId, fofo);
578
            } catch (Exception e) {
579
                LOGGER.error("ERROR : ", e);
580
            }
581
        } else {
582
            if (privateDealUser.getCounterId() == null) {
583
                Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
584
                privateDealUser.setCounterId(counterId);
585
                privateDealUser.setFofo(fofo);
586
                privateDealUserRepository.persist(privateDealUser);
587
            } else {
588
                Counter counter = null;
589
                try {
590
                    counter = counterRepository.selectById(privateDealUser.getCounterId());
591
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
592
                    LOGGER.error("Counter not found with id [{}]", privateDealUser.getCounterId());
593
                }
594
                if (counter == null) {
595
                    this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
596
                } else {
597
                    counter.setGstin(gstNumber);
598
                    counterRepository.persist(counter);
599
                }
600
                privateDealUser.setFofo(fofo);
601
                privateDealUserRepository.persist(privateDealUser);
602
            }
603
        }
23955 govind 604
 
31734 tejbeer 605
        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
606
        privateDealUserAddressMapping.setUserId(retailer.getId());
607
        privateDealUserAddressMapping.setAddressId(retailerAddressId);
608
        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
609
    }
23955 govind 610
 
31734 tejbeer 611
    // Specifically set isFofo to true that has to be used by old system
612
    private void createPrivateDealUser(int retailerId, int counterId, boolean fofo) {
613
        PrivateDealUser privateDealUser = new PrivateDealUser();
614
        privateDealUser.setActive(true);
615
        privateDealUser.setBulkShipmentAmountLimit(fofo ? 1000000 : 50000);
616
        privateDealUser.setId(retailerId);
617
        privateDealUser.setCounterId(counterId);
618
        privateDealUser.setFofo(fofo);
619
        privateDealUserRepository.persist(privateDealUser);
620
    }
23955 govind 621
 
31734 tejbeer 622
    private Integer createCounter(String emailId, String gstNumber, String mobileNumber, String name, int addressId) {
623
        if (gstNumber != null && !gstNumber.isEmpty()) {
624
            Counter counter = new Counter();
625
            counter.setEmailId(emailId);
626
            counter.setGstin(gstNumber);
627
            counter.setMobileNumber(mobileNumber);
628
            counter.setName(name);
629
            counter.setAddressId(addressId);
630
            counterRepository.persist(counter);
631
            return counter.getId();
632
        } else {
633
            return null;
634
        }
635
    }
23955 govind 636
 
33128 amit.gupta 637
    private Address updateRetailerAddress(Address address, CustomAddress customAddress, int retailerId) throws
638
            ProfitMandiBusinessException {
31734 tejbeer 639
        if (address == null) {
640
            address = new Address();
641
            address.setRetaierId(retailerId);
642
            this.updateAddress(address, customAddress);
643
            // addressRepository.persist(addressRetailer);
23955 govind 644
 
31734 tejbeer 645
            final RetailerRegisteredAddress retailerRegisteredAddress = new RetailerRegisteredAddress();
646
            retailerRegisteredAddress.setRetailerId(retailerId);
647
            retailerRegisteredAddress.setAddressId(address.getId());
648
            retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
649
        } else {
650
            this.updateAddress(address, customAddress);
651
            RetailerRegisteredAddress retailerRegisteredAddress = retailerRegisteredAddressRepository.selectByRetailerId(retailerId);
652
            retailerRegisteredAddress.setAddressId(address.getId());
653
            retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
654
        }
655
        return address;
656
    }
23955 govind 657
 
31734 tejbeer 658
    private void updateAddress(Address address, CustomAddress customAddress) throws ProfitMandiBusinessException {
659
        address.setName(customAddress.getName());
660
        address.setPhoneNumber(customAddress.getPhoneNumber());
661
        address.setLine1(customAddress.getLine1());
662
        address.setLine2(customAddress.getLine2());
663
        address.setCity(customAddress.getCity());
664
        address.setPinCode(customAddress.getPinCode());
665
        State state = stateRepository.selectByName(customAddress.getState());
666
        if (state == null) {
667
            throw new ProfitMandiBusinessException("State name", "Invalid State - Pls Contact Technology", "Invalid State - Pls Contact Technology");
668
        }
669
        address.setState(state.getName());
670
        addressRepository.persist(address);
671
        LOGGER.info("Address Updated" + address);
672
    }
23955 govind 673
 
33128 amit.gupta 674
    private void updateRetailerShops(List<Shop> shops, Set<CustomShop> customShops, int retailerId, Address
675
            sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
31734 tejbeer 676
        if (shops.isEmpty()) {
677
            for (CustomShop customShop : customShops) {
678
                Shop shop = new Shop();
679
                this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
680
                shops.add(shop);
681
            }
682
        } else {
683
            for (Shop shop : shops) {
684
                for (CustomShop customShop : customShops) {
685
                    if (shop.getId() == customShop.getShopId()) {
686
                        this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
687
                    }
688
                }
689
            }
690
            for (CustomShop customShop : customShops) {
691
                if (customShop.getShopId() == 0) {
692
                    Shop shop = new Shop();
693
                    this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
694
                    shops.add(shop);
695
                }
696
            }
697
        }
698
    }
23955 govind 699
 
33128 amit.gupta 700
    private void createOrUpdateShop(Shop shop, CustomShop customShop, int retailerId, Address
701
            sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
31734 tejbeer 702
        shop.setRetailerId(retailerId);
703
        shop.setName(customShop.getName());
704
        if (customShop.getDocumentId() > 0) {
705
            if (shop.getDocumentId() != null && shop.getDocumentId() != customShop.getDocumentId()) {
706
                try {
707
                    documentRepository.deleteById(shop.getDocumentId());
708
                } catch (Exception e) {
709
                    e.printStackTrace();
710
                }
711
            }
712
            shop.setDocumentId(customShop.getDocumentId());
713
            documentRepository.markDocumentAsPersisted(customShop.getDocumentId());
714
        }
715
        if (shop.getAddressId() == null) {
716
            Address address = null;
717
            if (customShop.isSameAsRetailerAddress()) {
718
                address = sameAsRetailerAddressValue;
719
            } else {
720
                // shop.setDocumentId(customShop.getDocumentId());
721
                address = new Address();
722
                this.updateAddress(address, customShop.getAddress());
723
            }
724
            shop.setAddressId(address.getId());
725
            shop.setAddress(address);
726
            shopRepository.persist(shop);
727
            ShopAddress shopAddress = null;
728
            try {
729
                shopAddress = shopAddressRepository.selectByShopId(shop.getId());
730
                shopAddress.setAddressId(address.getId());
731
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
732
                shopAddress = new ShopAddress();
733
                shopAddress.setAddressId(address.getId());
734
                shopAddress.setShopId(shop.getId());
735
            }
736
            shopAddressRepository.persist(shopAddress);
737
        } else {
738
            Address address = null;
739
            try {
740
                address = addressRepository.selectById(shop.getAddressId());
741
                CustomAddress customAddress = customShop.getAddress();
742
                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()))) {
743
                    address = new Address();
744
                    ShopAddress shopAddress = shopAddressRepository.selectByShopId(shop.getId());
745
                    this.updateAddress(address, customAddress);
746
                    shopAddress.setAddressId(address.getId());
747
                    shopAddressRepository.persist(shopAddress);
748
                    shop.setAddress(address);
749
                    shopRepository.persist(shop);
750
                }
751
            } catch (Exception e) {
752
                if (customShop.isSameAsRetailerAddress()) {
753
                    address = sameAsRetailerAddressValue;
754
                } else {
755
                    // shop.setDocumentId(customShop.getDocumentId());
756
                    address = new Address();
757
                    this.updateAddress(address, customShop.getAddress());
758
                }
759
                shop.setAddressId(address.getId());
760
                shop.setAddress(address);
761
                shopRepository.persist(shop);
762
                ShopAddress shopAddress = null;
763
                try {
764
                    shopAddress = shopAddressRepository.selectByShopId(shop.getId());
765
                    shopAddress.setAddressId(address.getId());
766
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
767
                    shopAddress = new ShopAddress();
768
                    shopAddress.setAddressId(address.getId());
769
                    shopAddress.setShopId(shop.getId());
770
                }
771
                shopAddressRepository.persist(shopAddress);
772
            }
23955 govind 773
 
31734 tejbeer 774
        }
23955 govind 775
 
31734 tejbeer 776
    }
23955 govind 777
 
33247 ranu 778
    private void addAddress(List<Shop> shops) throws ProfitMandiBusinessException {
31734 tejbeer 779
        Set<Integer> shopIds = this.toShopIds(shops);
780
        if (shopIds.isEmpty()) {
781
            return;
782
        }
783
        List<ShopAddress> shopAddresses = shopAddressRepository.selectByShopIds(shopIds);
784
        Map<Integer, Address> addressIdAddressMap = this.toAddressIdAddressMap(shopAddresses);
23955 govind 785
 
31734 tejbeer 786
        for (Shop shop : shops) {
787
            shop.setAddress(addressIdAddressMap.get(shop.getAddressId()));
788
        }
789
    }
22980 ashik.ali 790
 
33247 ranu 791
    private Map<Integer, Address> toAddressIdAddressMap(List<ShopAddress> shopAddresses) throws ProfitMandiBusinessException {
31734 tejbeer 792
        Map<Integer, Address> addressIdAddressMap = new HashMap<>();
793
        List<Integer> addressIds = this.toAddressIds(shopAddresses);
794
        List<Address> addresses = addressRepository.selectByIds(addressIds);
795
        for (Address address : addresses) {
796
            addressIdAddressMap.put(address.getId(), address);
797
        }
798
        return addressIdAddressMap;
799
    }
23955 govind 800
 
31734 tejbeer 801
    private List<Integer> toAddressIds(List<ShopAddress> shopAddresses) {
35394 amit 802
        return shopAddresses.stream()
803
                .map(ShopAddress::getAddressId)
804
                .collect(Collectors.toList());
31734 tejbeer 805
    }
23955 govind 806
 
31734 tejbeer 807
    private Set<Integer> toShopIds(List<Shop> shops) {
35394 amit 808
        return shops.stream()
809
                .map(Shop::getId)
810
                .collect(Collectors.toSet());
31734 tejbeer 811
    }
23955 govind 812
 
33247 ranu 813
    private String toString(List<UserRole> userRoles) throws ProfitMandiBusinessException {
31734 tejbeer 814
        Set<Integer> roleIds = new HashSet<>();
815
        for (UserRole userRole : userRoles) {
816
            roleIds.add(userRole.getRoleId());
817
        }
818
        List<Role> roles = roleRepository.selectByIds(roleIds);
31735 amit.gupta 819
        Function<Role, String> roleToNameFunction = role -> String.valueOf(role.getName());
31734 tejbeer 820
        Set<String> userRoleStrings = roles.stream().map(roleToNameFunction).collect(Collectors.toSet());
821
        return String.join(", ", userRoleStrings);
822
    }
23955 govind 823
 
33128 amit.gupta 824
    private FofoStore createFofoStoreCodeByRetailerId(int retailerId, String districtName, String
825
            stateName, UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
31734 tejbeer 826
        FofoStore fofoStore = null;
827
        try {
828
            fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
829
            fofoStore.setActivationType(ActivationType.ACTIVE);
30097 tejbeer 830
 
31734 tejbeer 831
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
23955 govind 832
 
31734 tejbeer 833
        }
23955 govind 834
 
31734 tejbeer 835
        if (fofoStore != null) {
836
            fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
33124 ranu 837
            fofoStore.setAstId(updateRetailerRequest.getAstId());
31734 tejbeer 838
            fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
839
            fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
840
            fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
841
            fofoStore.setFofoType(updateRetailerRequest.getFofoType());
35896 amit 842
            fofoStore.setGstNumber(updateRetailerRequest.getGstNumber());
31734 tejbeer 843
        } else {
844
            int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailerId);
845
            Address retailerAddress = addressRepository.selectById(retailerAddressId);
23955 govind 846
 
31734 tejbeer 847
            // StateInfo stateInfo = null;
848
            State stateInfo = null;
849
            try {
30527 tejbeer 850
 
31734 tejbeer 851
                stateInfo = stateRepository.selectByName(retailerAddress.getState());
852
                // stateInfo = Utils.getStateInfo(retailerAddress.getState());
853
            } catch (Exception e) {
854
                // TODO Auto-generated catch block
855
                e.printStackTrace();
856
                // throw new ProfitMandiBusinessException();
857
            }
858
            DistrictMaster districtMaster = districtMasterRepository.selectByNameAndStateShortName(districtName, stateInfo.getShortName());
23955 govind 859
 
31734 tejbeer 860
            fofoStore = new FofoStore();
861
            fofoStore.setId(retailerId);
862
            fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
863
            fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
31730 tejbeer 864
 
31734 tejbeer 865
            fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
866
            fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
35289 amit 867
 
868
            //Check for Trial users here
32615 raveendra. 869
            int nextStoreCodeInt = fofoStoreRepository.selectLatestStore().getCodeInt() + 1;
870
 
31734 tejbeer 871
            String fofoStoreCode = StringUtils.generateFofoStoreSequence(
32615 raveendra. 872
                    districtMaster.getStateShortName() + districtMaster.getShortName(), nextStoreCodeInt);
35306 amit 873
            try {
874
                TrialForm trialForm = trialFormRepository.selectByEmailOrMobile(updateRetailerRequest.getUserMobileNumber());
875
                if (trialForm != null) {
876
                    fofoStoreCode = "T-" + fofoStoreCode;
877
                    fofoStore.setTrial(true);
878
                    fofoStore.setTrialStart(LocalDate.now());
879
                    fofoStore.setTrialEnd(LocalDate.now().plusDays(31));
35360 aman 880
                    trialForm.setStatus(ProfitMandiConstants.Status.TMP_STORE_CODE_CREATED);
35306 amit 881
                    //TODO:Amit G, Send store code notification to retailer.
882
                }
883
            } catch (ProfitMandiBusinessException e) {
35289 amit 884
            }
31734 tejbeer 885
            fofoStore.setCode(fofoStoreCode);
32615 raveendra. 886
            fofoStore.setCodeInt(nextStoreCodeInt);
31734 tejbeer 887
            fofoStore.setBagsLastCredited(LocalDateTime.now());
35203 amit 888
            if (retailerAddress.getName().contains(ProfitMandiConstants.COMPANY_NAME) || retailerAddress.getName().contains(ProfitMandiConstants.COMPANY_SHORT_NAME)) {
889
                fofoStore.setInternal(true);
890
            } else {
891
                fofoStore.setInternal(false);
892
            }
893
            fofoStore.setFofoType(FofoType.FRANCHISE);
31734 tejbeer 894
            fofoStore.setFofoType(updateRetailerRequest.getFofoType());
895
            fofoStore.setActivationType(ActivationType.ACTIVE);
35896 amit 896
            fofoStore.setGstNumber(updateRetailerRequest.getGstNumber());
31734 tejbeer 897
            fofoStoreRepository.persist(fofoStore);
28908 tejbeer 898
 
31734 tejbeer 899
            // Auto fill in onboarding Panel
900
            PartnerOnBoardingPanel pobp = partnerOnBoardingPanelRepository.selectByPhoneNumber(Long.parseLong(retailerAddress.getPhoneNumber()));
901
            if (pobp != null) {
28908 tejbeer 902
 
31734 tejbeer 903
                PartnerVerificationpanel partnerVerificationpanel = partnerOnboardingVerificationRepository.selectByOnboardingId(pobp.getId());
29042 tejbeer 904
 
31734 tejbeer 905
                if (partnerVerificationpanel != null) {
906
                    if (partnerVerificationpanel.getApproval().equals(PartnerVerificationApprovalStatus.YES)) {
907
                        pobp.setCode(fofoStore.getCode());
29042 tejbeer 908
 
31734 tejbeer 909
                        storeTimelineTatService.onCodeCreated(pobp.getId());
29042 tejbeer 910
 
31734 tejbeer 911
                    }
29042 tejbeer 912
 
31734 tejbeer 913
                }
29042 tejbeer 914
 
31734 tejbeer 915
            }
30719 tejbeer 916
 
31734 tejbeer 917
            PincodePartner pincodePartner = pincodePartnerRepository.selectPartnerByPincode(retailerAddress.getPinCode(), fofoStore.getId());
918
            if (pincodePartner == null) {
919
                PincodePartner pinPartner = new PincodePartner();
920
                pinPartner.setFofoId(fofoStore.getId());
921
                pinPartner.setPincode(retailerAddress.getPinCode());
922
                pincodePartnerRepository.perist(pinPartner);
923
            }
924
        }
23955 govind 925
 
35289 amit 926
        if (fofoStore.isTrial()) {
35418 aman 927
 
35425 aman 928
            storeTimelineTatService.sendTrialStoreCreationMail(fofoStore, updateRetailerRequest);
929
            storeTimelineTatService.sendTrialActivationMail(fofoStore, updateRetailerRequest);
35418 aman 930
 
35289 amit 931
        }
932
 
31734 tejbeer 933
        return fofoStore;
934
    }
23955 govind 935
 
31734 tejbeer 936
    @Override
33128 amit.gupta 937
    public FofoStore createFofoStoreCodeByUserId(int userId, String districtName, String
938
            stateName, UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
31734 tejbeer 939
        User user = userRepository.selectById(userId);
940
        // = userAccountRepository.selectRetailerIdByUserId(user.getId());
941
        UserAccount userAccounts = userAccountRepository.selectSaholicByUserId(user.getId());
942
        Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
943
        Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
944
        try {
945
            userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleFofo.getId());
946
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
947
            throw new ProfitMandiBusinessException(ProfitMandiConstants.USER_ID, user.getId(), "USR_1013");
948
        }
949
        return this.createFofoStoreCodeByRetailerId(retailer.getId(), districtName, stateName, updateRetailerRequest);
23955 govind 950
 
31734 tejbeer 951
    }
23955 govind 952
 
31734 tejbeer 953
    @Override
954
    public List<DistrictMaster> getAllDistrictMaster(String stateName) {
955
        // StateInfo stateInfo = null;
956
        State stateInfo = null;
957
        try {
958
            // stateInfo = Utils.getStateInfo(stateName);
30525 tejbeer 959
 
31734 tejbeer 960
            stateInfo = stateRepository.selectByName(stateName);
961
        } catch (Exception e) {
962
            e.printStackTrace();
963
            // throw new ProfitMandiBusinessException();
964
        }
965
        return districtMasterRepository.selectByStateShortName(stateInfo.getShortName());
966
    }
22980 ashik.ali 967
 
31734 tejbeer 968
    @Override
34149 tejus.loha 969
    @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 970
    public Map<Integer, CustomRetailer> getFofoRetailers(List<Integer> fofoIds) throws ProfitMandiBusinessException {
35394 amit 971
        if (fofoIds == null || fofoIds.isEmpty()) {
972
            return new HashMap<>();
973
        }
974
 
31734 tejbeer 975
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
35440 amit 976
 
977
        // Check for saholicUsers without corresponding dtrUser
978
        List<String> saholicEmails = saholicUsers.stream()
979
                .map(com.spice.profitmandi.dao.entity.user.User::getEmailId)
980
                .filter(email -> email != null)
981
                .collect(Collectors.toList());
982
        Set<String> dtrUserEmails = userRepository.selectAllByEmailIds(saholicEmails).stream()
983
                .map(User::getEmailId)
984
                .collect(Collectors.toSet());
985
        for (com.spice.profitmandi.dao.entity.user.User saholicUser : saholicUsers) {
986
            if (saholicUser.getEmailId() != null && !dtrUserEmails.contains(saholicUser.getEmailId())) {
987
                LOGGER.warn("dtrUser not found for saholicUser - id: {}, email: {}", saholicUser.getId(), saholicUser.getEmailId());
988
            }
989
        }
990
 
35394 amit 991
        Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
992
                .filter(x -> x.getAddressId() != null)
993
                .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.user.User::getAddressId, x -> x));
31734 tejbeer 994
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
35394 amit 995
 
996
        // Batch fetch all FofoStores to avoid N+1 queries
997
        Set<Integer> retailerIds = addresses.stream().map(Address::getRetaierId).collect(Collectors.toSet());
998
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(retailerIds))
999
                .stream().collect(Collectors.toMap(FofoStore::getId, fs -> fs));
1000
 
31734 tejbeer 1001
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
1002
        for (Address address : addresses) {
1003
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
35394 amit 1004
            FofoStore fs = fofoStoreMap.get(address.getRetaierId());
1005
            if (fs == null) {
31734 tejbeer 1006
                continue;
1007
            }
35394 amit 1008
 
35896 amit 1009
            CustomRetailer customRetailer = buildCustomRetailer(user, address, fs);
31734 tejbeer 1010
            customRetailersMap.put(customRetailer.getPartnerId(), customRetailer);
1011
        }
1012
        return customRetailersMap;
1013
    }
25295 amit.gupta 1014
 
35394 amit 1015
    /**
1016
     * Helper method to build CustomRetailer from fetched entities
1017
     */
1018
    private CustomRetailer buildCustomRetailer(com.spice.profitmandi.dao.entity.user.User user, Address address,
35896 amit 1019
                                               FofoStore fs) {
35394 amit 1020
        CustomRetailer customRetailer = new CustomRetailer();
1021
        customRetailer.setEmail(user.getEmailId());
1022
        customRetailer.setBusinessName(address.getName());
1023
        customRetailer.setMobileNumber(address.getPhoneNumber());
1024
        customRetailer.setCode(fs.getCode());
1025
        customRetailer.setAstId(fs.getAstId());
1026
        customRetailer.setActivationType(fs.getActivationType());
1027
        customRetailer.setCounterSize(fs.getCounterSize());
1028
        customRetailer.setCounterPotential(fs.getCounterPotential());
1029
        customRetailer.setWarehouseId(fs.getWarehouseId());
1030
        customRetailer.setPartnerId(fs.getId());
1031
        customRetailer.setFofoType(fs.getFofoType());
1032
        customRetailer.setCartId(user.getActiveCartId());
1033
 
35896 amit 1034
        customRetailer.setGstNumber(fs.getGstNumber());
35394 amit 1035
 
1036
        CustomAddress customAddress = buildCustomAddress(address);
1037
        customRetailer.setAddress(customAddress);
1038
        customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + customRetailer.getCode() + "- " + customAddress.getCity());
1039
        return customRetailer;
1040
    }
1041
 
1042
    /**
1043
     * Helper method to build CustomAddress from Address entity
1044
     */
1045
    private CustomAddress buildCustomAddress(Address address) {
1046
        CustomAddress customAddress = new CustomAddress();
1047
        customAddress.setCity(address.getCity());
1048
        customAddress.setState(address.getState());
1049
        customAddress.setLine1(address.getLine1());
1050
        customAddress.setLine2(address.getLine2());
1051
        customAddress.setPinCode(address.getPinCode());
1052
        customAddress.setName(address.getName());
1053
        customAddress.setPhoneNumber(address.getPhoneNumber());
1054
        return customAddress;
1055
    }
1056
 
31734 tejbeer 1057
    @Override
1058
    @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
1059
    public CustomRetailer getFofoRetailer(int fofoId) throws ProfitMandiBusinessException {
1060
        com.spice.profitmandi.dao.entity.user.User saholicUser = userUserRepository.selectById(fofoId);
35440 amit 1061
        User dtrUser = null;
1062
        try {
1063
            dtrUser = userRepository.selectByEmailId(saholicUser.getEmailId());
1064
        } catch (ProfitMandiBusinessException e) {
1065
            LOGGER.info("User not found for emailId: {} and id is : {}", saholicUser.getEmailId(), saholicUser.getId());
1066
        }
31734 tejbeer 1067
        FofoStore store = fofoStoreRepository.selectByRetailerId(fofoId);
35394 amit 1068
        Address address = addressRepository.selectById(saholicUser.getAddressId());
1069
 
31734 tejbeer 1070
        CustomRetailer customRetailer = new CustomRetailer();
1071
        customRetailer.setEmail(saholicUser.getEmailId());
1072
        customRetailer.setBusinessName(address.getName());
1073
        customRetailer.setMobileNumber(address.getPhoneNumber());
31862 tejbeer 1074
        customRetailer.setFirstName(dtrUser.getFirstName());
1075
        customRetailer.setLastName(dtrUser.getLastName());
35394 amit 1076
        customRetailer.setCartId(saholicUser.getActiveCartId());
1077
        customRetailer.setPartnerId(address.getRetaierId());
1078
        customRetailer.setCode(store.getCode());
1079
        customRetailer.setAstId(store.getAstId());
1080
        customRetailer.setActivationType(store.getActivationType());
1081
        customRetailer.setWarehouseId(store.getWarehouseId());
1082
 
35896 amit 1083
        customRetailer.setGstNumber(store.getGstNumber());
35394 amit 1084
 
1085
        // Reuse helper method for CustomAddress
1086
        CustomAddress customAddress = buildCustomAddress(address);
1087
        customRetailer.setAddress(customAddress);
31734 tejbeer 1088
        customRetailer.setDisplayName(address.getName() + " - " + address.getCity());
35394 amit 1089
 
31734 tejbeer 1090
        return customRetailer;
1091
    }
26125 amit.gupta 1092
 
31734 tejbeer 1093
    @Override
33247 ranu 1094
    public Map<Integer, CustomRetailer> getFofoRetailerUserId(List<Integer> fofoIds) throws ProfitMandiBusinessException {
35394 amit 1095
        if (fofoIds == null || fofoIds.isEmpty()) {
1096
            return new HashMap<>();
1097
        }
1098
 
31734 tejbeer 1099
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
35394 amit 1100
        Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
1101
                .filter(x -> x.getAddressId() != null)
1102
                .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.user.User::getAddressId, x -> x));
31734 tejbeer 1103
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
35394 amit 1104
 
1105
        // Batch fetch all retailerIds to userIds mapping to avoid N+1
1106
        Set<Integer> retailerIds = addresses.stream().map(Address::getRetaierId).collect(Collectors.toSet());
1107
        Map<Integer, Integer> retailerIdToUserIdMap = getUserIdRetailerIdMapReverse(retailerIds);
1108
 
35896 amit 1109
        // Batch fetch FofoStores for GST numbers
1110
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(retailerIds))
1111
                .stream().collect(Collectors.toMap(FofoStore::getId, fs -> fs));
35394 amit 1112
 
31734 tejbeer 1113
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
1114
        for (Address address : addresses) {
1115
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
35394 amit 1116
            Integer userId = retailerIdToUserIdMap.get(user.getId());
1117
            if (userId == null) {
1118
                continue;
1119
            }
1120
 
31734 tejbeer 1121
            CustomRetailer customRetailer = new CustomRetailer();
1122
            customRetailer.setEmail(user.getEmailId());
1123
            customRetailer.setBusinessName(address.getName());
1124
            customRetailer.setMobileNumber(address.getPhoneNumber());
35394 amit 1125
            customRetailer.setCartId(user.getActiveCartId());
1126
            customRetailer.setPartnerId(address.getRetaierId());
1127
 
35896 amit 1128
            FofoStore fs = fofoStoreMap.get(address.getRetaierId());
1129
            customRetailer.setGstNumber(fs != null ? fs.getGstNumber() : null);
35394 amit 1130
 
1131
            CustomAddress customAddress = buildCustomAddress(address);
1132
            customRetailer.setAddress(customAddress);
1133
            customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + customAddress.getCity());
31734 tejbeer 1134
            customRetailersMap.put(userId, customRetailer);
1135
        }
1136
        return customRetailersMap;
1137
    }
25295 amit.gupta 1138
 
35394 amit 1139
    /**
1140
     * Helper method to get retailerId to userId mapping
1141
     */
1142
    private Map<Integer, Integer> getUserIdRetailerIdMapReverse(Set<Integer> retailerIds) {
1143
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1144
        return userAccounts.stream().collect(Collectors.toMap(UserAccount::getAccountKey, UserAccount::getUserId));
1145
    }
1146
 
31734 tejbeer 1147
    @Override
33247 ranu 1148
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap() throws ProfitMandiBusinessException {
31734 tejbeer 1149
        Role roleFofo = null;
1150
        try {
1151
            roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
1152
        } catch (ProfitMandiBusinessException e) {
1153
            // TODO Auto-generated catch block
1154
            e.printStackTrace();
1155
        }
1156
        Role roleRetailer = null;
1157
        try {
1158
            roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
1159
        } catch (ProfitMandiBusinessException e) {
1160
            // TODO Auto-generated catch block
1161
            e.printStackTrace();
1162
        }
1163
        Set<Integer> roleIds = new HashSet<>();
1164
        roleIds.add(roleFofo.getId());
1165
        roleIds.add(roleRetailer.getId());
1166
        List<Integer> userIds = userRoleRepository.selectUserIdsByRoleIds(roleIds);
1167
        List<User> users = userRepository.selectAllByIds(new HashSet<>(userIds));
1168
        Map<Integer, Integer> userIdRetailerIdMap = this.getUserIdRetailerIdMap(userIds);
1169
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1170
        for (User user : users) {
1171
            retailerIdEmailIdMap.put(userIdRetailerIdMap.get(user.getId()), user.getEmailId());
1172
        }
1173
        return retailerIdEmailIdMap;
1174
    }
23955 govind 1175
 
31734 tejbeer 1176
    private Map<Integer, Integer> getUserIdRetailerIdMap(List<Integer> userIds) {
1177
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByUserIds(new HashSet<>(userIds));
1178
        Map<Integer, Integer> userIdRetailerIdMap = new HashMap<>();
1179
        for (UserAccount userAccount : userAccounts) {
1180
            userIdRetailerIdMap.put(userAccount.getUserId(), userAccount.getAccountKey());
1181
        }
1182
        return userIdRetailerIdMap;
1183
    }
25295 amit.gupta 1184
 
33247 ranu 1185
    private Map<Integer, String> getUserIdEmailIdMap(Set<Integer> userIds) throws ProfitMandiBusinessException {
31734 tejbeer 1186
        List<User> users = userRepository.selectAllByIds(userIds);
1187
        Map<Integer, String> userIdEmailIdMap = new HashMap<>();
1188
        for (User user : users) {
1189
            userIdEmailIdMap.put(user.getId(), user.getEmailId());
1190
        }
1191
        return userIdEmailIdMap;
1192
    }
23509 amit.gupta 1193
 
31734 tejbeer 1194
    @Override
33247 ranu 1195
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap(Set<Integer> retailerIds) throws ProfitMandiBusinessException {
31734 tejbeer 1196
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1197
        Set<Integer> userIds = new HashSet<>();
1198
        for (UserAccount userAccount : userAccounts) {
1199
            userIds.add(userAccount.getUserId());
1200
        }
1201
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1202
        Map<Integer, String> userIdEmailIdMap = this.getUserIdEmailIdMap(userIds);
1203
        for (UserAccount userAccount : userAccounts) {
1204
            retailerIdEmailIdMap.put(userAccount.getAccountKey(), userIdEmailIdMap.get(userAccount.getUserId()));
1205
        }
1206
        return retailerIdEmailIdMap;
1207
    }
25295 amit.gupta 1208
 
31734 tejbeer 1209
    @Override
33247 ranu 1210
    public Map<Integer, String> getAllFofoRetailerIdNameMap(List<Integer> storeIds) throws ProfitMandiBusinessException {
31734 tejbeer 1211
        Map<Integer, CustomRetailer> retailersMap = this.getFofoRetailers(storeIds);
1212
        Map<Integer, String> retailerIdNameMap = new HashMap<>();
1213
        for (Map.Entry<Integer, CustomRetailer> entry : retailersMap.entrySet()) {
1214
            retailerIdNameMap.put(entry.getKey(), entry.getValue().getBusinessName() + "-" + entry.getValue().getAddress().getCity());
1215
        }
1216
        return retailerIdNameMap;
1217
    }
24168 amit.gupta 1218
 
31734 tejbeer 1219
    @Override
1220
    @Cacheable(value = "FofoRetailerIdNameMap", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1221
    public Map<Integer, String> getAllFofoRetailerIdNameMap() throws ProfitMandiBusinessException {
31734 tejbeer 1222
        List<FofoStore> stores = fofoStoreRepository.selectAll();
1223
        List<Integer> storeIds = stores.stream().map(x -> x.getId()).collect(Collectors.toList());
1224
        return this.getAllFofoRetailerIdNameMap(storeIds);
1225
    }
24349 amit.gupta 1226
 
31734 tejbeer 1227
    @Override
33247 ranu 1228
    public List<MapWrapper<Integer, String>> getAllFofoRetailerIdNameList() throws ProfitMandiBusinessException {
31734 tejbeer 1229
        List<MapWrapper<Integer, String>> mapWrappers = new ArrayList<>();
1230
        // TODO Auto-generated method stub
1231
        Map<Integer, String> fofoIdNameMap = this.getAllFofoRetailerIdNameMap();
1232
        fofoIdNameMap.forEach((fofoId, name) -> {
1233
            MapWrapper<Integer, String> idWrapper = new MapWrapper<>();
1234
            idWrapper.setKey(fofoId);
1235
            idWrapper.setValue(name);
1236
            mapWrappers.add(idWrapper);
1237
        });
1238
        return mapWrappers;
1239
    }
24349 amit.gupta 1240
 
31734 tejbeer 1241
    @Override
1242
    @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1243
    public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly) throws ProfitMandiBusinessException {
35394 amit 1244
        Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream()
1245
                .filter(fs -> fs.getFofoType().equals(FofoType.FRANCHISE));
31734 tejbeer 1246
        if (activeOnly) {
35394 amit 1247
            storeStream = storeStream.filter(FofoStore::isActive);
31734 tejbeer 1248
        }
35394 amit 1249
        List<Integer> storeIds = storeStream.map(FofoStore::getId).collect(Collectors.toList());
31734 tejbeer 1250
        return this.getFofoRetailers(storeIds);
1251
    }
25295 amit.gupta 1252
 
31734 tejbeer 1253
    @Override
33367 ranu 1254
    @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
1255
    public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly, String pinCode) throws ProfitMandiBusinessException {
1256
        List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pinCode);
1257
        List<Integer> storeIds = new ArrayList<>();
35394 amit 1258
        if (!pincodePartners.isEmpty()) {
1259
            List<Integer> fofoIds = pincodePartners.stream().map(PincodePartner::getFofoId).collect(Collectors.toList());
33367 ranu 1260
            List<FofoStore> fofoStores = fofoStoreRepository.selectActivePartnersByRetailerIds(fofoIds);
35394 amit 1261
            storeIds = fofoStores.stream().map(FofoStore::getId).collect(Collectors.toList());
33367 ranu 1262
        }
1263
        return this.getFofoRetailers(storeIds);
1264
    }
1265
 
1266
    @Override
31734 tejbeer 1267
    @Cacheable(value = "allFofoRetailers", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1268
    public Map<Integer, CustomRetailer> getAllFofoRetailers() throws ProfitMandiBusinessException {
35394 amit 1269
        List<Integer> storeIds = fofoStoreRepository.selectAll().stream()
1270
                .map(FofoStore::getId)
1271
                .collect(Collectors.toList());
31734 tejbeer 1272
        return this.getFofoRetailers(storeIds);
1273
    }
27861 tejbeer 1274
 
31734 tejbeer 1275
    @Override
34619 ranu 1276
    @Cacheable(value = "allFofoRetailersInternalFalse", cacheManager = "thirtyMinsTimeOutCacheManager")
1277
    public Map<Integer, CustomRetailer> getAllFofoRetailersInternalFalse() throws ProfitMandiBusinessException {
35394 amit 1278
        List<Integer> storeIds = fofoStoreRepository.selectAll().stream()
1279
                .filter(fs -> fs.getFofoType().equals(FofoType.FRANCHISE))
1280
                .map(FofoStore::getId)
1281
                .collect(Collectors.toList());
34619 ranu 1282
        return this.getFofoRetailers(storeIds);
1283
    }
1284
 
1285
    @Override
33128 amit.gupta 1286
    public LoginRequestResponseModel registerWebUser(LoginRequestResponseModel loginRequestModel) throws
1287
            ProfitMandiBusinessException {
26522 amit.gupta 1288
 
31734 tejbeer 1289
        com.spice.profitmandi.dao.entity.user.User saholicUser = this.createSaholicUser(loginRequestModel);
1290
        loginRequestModel.setUserId(saholicUser.getId());
26522 amit.gupta 1291
 
31734 tejbeer 1292
        this.createRetailerAddress(loginRequestModel);
26522 amit.gupta 1293
 
31734 tejbeer 1294
        this.createPrivateDealUser(loginRequestModel);
1295
        this.updateSaholicUser(saholicUser.getId(), loginRequestModel.getBusinessAddress().getId());
26522 amit.gupta 1296
 
31734 tejbeer 1297
        return loginRequestModel;
26522 amit.gupta 1298
 
31734 tejbeer 1299
    }
26522 amit.gupta 1300
 
31734 tejbeer 1301
    private void createPrivateDealUser(LoginRequestResponseModel loginRequestModel) {
26522 amit.gupta 1302
 
31734 tejbeer 1303
        Integer counterId = this.createCounter(loginRequestModel.getEmail(), loginRequestModel.getGstNumber(), loginRequestModel.getBusinessAddress().getPhoneNumber(), loginRequestModel.getBusinessAddress().getName(), loginRequestModel.getBusinessAddress().getId());
1304
        try {
1305
            this.createPrivateDealUser(loginRequestModel.getUserId(), counterId, false);
1306
        } catch (Exception e) {
1307
            LOGGER.error("ERROR : ", e);
1308
        }
26522 amit.gupta 1309
 
31734 tejbeer 1310
        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
1311
        privateDealUserAddressMapping.setUserId(loginRequestModel.getUserId());
1312
        privateDealUserAddressMapping.setAddressId(loginRequestModel.getBusinessAddress().getId());
1313
        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
26522 amit.gupta 1314
 
31734 tejbeer 1315
    }
26522 amit.gupta 1316
 
33128 amit.gupta 1317
    private void createRetailerAddress(LoginRequestResponseModel loginRequestResponseModel) throws
1318
            ProfitMandiBusinessException {
31734 tejbeer 1319
        Address businessAddress = loginRequestResponseModel.getBusinessAddress();
1320
        businessAddress.setRetaierId(loginRequestResponseModel.getUserId());
1321
        addressRepository.persist(businessAddress);
1322
    }
26536 amit.gupta 1323
 
31734 tejbeer 1324
    private String getHash256(String originalString) {
1325
        String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
1326
        LOGGER.info("Hash String {}", hashString);
1327
        return hashString;
1328
    }
26533 amit.gupta 1329
 
31734 tejbeer 1330
    @Override
1331
    @Cacheable(value = "fofoIdUrl", cacheManager = "thirtyMinsTimeOutCacheManager")
1332
    public Map<Integer, String> getAllFofoRetailerIdUrlMap() {
1333
        Map<Integer, String> fofoRetailerUrlMap = new HashMap<>();
35394 amit 1334
        List<FofoStore> stores = fofoStoreRepository.selectAll().stream()
1335
                .filter(FofoStore::isActive)
1336
                .collect(Collectors.toList());
1337
 
1338
        // Batch fetch all district masters to avoid N+1 queries
1339
        List<DistrictMaster> allDistrictMasters = districtMasterRepository.selectAll();
1340
        Map<String, DistrictMaster> districtMasterMap = allDistrictMasters.stream()
1341
                .collect(Collectors.toMap(
1342
                        dm -> dm.getStateShortName() + "_" + dm.getShortName(),
1343
                        dm -> dm,
1344
                        (existing, replacement) -> existing));
1345
 
1346
        // Get fallback district master
1347
        DistrictMaster fallbackDistrict = districtMasterMap.get("HR_FB");
1348
 
31734 tejbeer 1349
        for (FofoStore store : stores) {
35394 amit 1350
            String codeWithoutDigits = store.getCode().replaceAll("\\d+", "");
1351
            if (codeWithoutDigits.length() < 3) {
1352
                LOGGER.warn("Invalid store code format: {}", store.getCode());
1353
                continue;
1354
            }
1355
            String stateShortName = codeWithoutDigits.substring(0, 2);
1356
            String districtShortName = codeWithoutDigits.substring(2);
1357
 
1358
            // Use pre-fetched map instead of N+1 query
1359
            String key = stateShortName + "_" + districtShortName;
1360
            DistrictMaster districtMaster = districtMasterMap.getOrDefault(key, fallbackDistrict);
1361
 
31734 tejbeer 1362
            if (districtMaster == null) {
35394 amit 1363
                LOGGER.warn("No district master found for key: {} and no fallback available", key);
1364
                continue;
31734 tejbeer 1365
            }
35394 amit 1366
 
1367
            String urlString = districtMaster.getStateShortName() + "/" +
1368
                    Utils.getHyphenatedString(districtMaster.getName()) + "/" + store.getCode();
31734 tejbeer 1369
            fofoRetailerUrlMap.put(store.getId(), urlString.toLowerCase());
1370
        }
1371
        return fofoRetailerUrlMap;
1372
    }
26533 amit.gupta 1373
 
31734 tejbeer 1374
    @Override
1375
    @Cacheable(value = "storeCodeRetailerMap", cacheManager = "thirtyMinsTimeOutCacheManager")
1376
    public Map<String, Integer> getStoreCodeRetailerMap() {
1377
        Map<Integer, String> map = this.getAllFofoRetailerIdUrlMap();
1378
        Map<String, Integer> returnMap = map.entrySet().stream().collect(Collectors.toMap(x -> {
1379
            String[] splitString = x.getValue().split("/");
1380
            return splitString[splitString.length - 1];
1381
        }, x -> x.getKey()));
1382
        LOGGER.info("returnMap {}", returnMap);
1383
        return returnMap;
1384
    }
27877 amit.gupta 1385
 
1386
 
31734 tejbeer 1387
    @Override
32668 raveendra. 1388
    public User getEmail() {
1389
        return null;
1390
    }
1391
 
1392
    @Override
1393
    public void update(com.spice.profitmandi.dao.entity.user.User user) {
1394
    }
1395
 
1396
    @Override
1397
    public void updateRetailerEmail(int fofoId, String newEmail) throws ProfitMandiBusinessException {
1398
        User dtrUser = null;
1399
        com.spice.profitmandi.dao.entity.user.User user = null;
1400
 
1401
        try {
1402
            dtrUser = userRepository.selectByEmailId(newEmail);
1403
        } catch (Exception e) {
1404
        }
1405
 
1406
        try {
1407
            user = userUserRepository.selectByEmailId(newEmail);
1408
        } catch (Exception e) {
1409
        }
1410
 
1411
        if (user != null || dtrUser != null) {
1412
            throw new ProfitMandiBusinessException("Email", newEmail, "Email already exist");
1413
        }
1414
        com.spice.profitmandi.dao.entity.user.User fofoUser = userUserRepository.selectById(fofoId);
1415
        String oldEmail = fofoUser.getEmailId();
1416
        LOGGER.info("old email {}", oldEmail);
1417
        User thisDtrUser = userRepository.selectByEmailId(oldEmail);
1418
 
1419
        fofoUser.setEmailId(newEmail);
1420
        thisDtrUser.setEmailId(newEmail);
1421
    }
1422
 
1423
 
32953 amit.gupta 1424
    //    @Override
32737 amit.gupta 1425
    @Cacheable(value = "getContactsByFofoId", cacheManager = "oneDayCacheManager")
33128 amit.gupta 1426
    public List<RetailerContact> getContactsByFofoId(int fofoId, boolean activeOnly) throws
1427
            ProfitMandiBusinessException {
32737 amit.gupta 1428
        List<RetailerContact> retailerContacts = retailerContactRepository.selectAllByRetailerId(fofoId, activeOnly);
1429
        com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
1430
        RetailerContact retailerContact = new RetailerContact();
1431
        retailerContact.setMobile(user.getMobileNumber());
1432
        retailerContact.setName(user.getName());
1433
        retailerContact.setActive(true);
1434
        retailerContact.setFofoId(fofoId);
1435
        retailerContacts.add(retailerContact);
1436
        return retailerContacts;
1437
    }
1438
 
1439
 
1440
    @Override
33128 amit.gupta 1441
    public Map<Integer, CustomRetailer> getFofoRetailersPaginated(boolean activeOnly, int offset,
33247 ranu 1442
                                                                  int limit, FofoType fofoType) throws ProfitMandiBusinessException {
30097 tejbeer 1443
 
31734 tejbeer 1444
        Stream<FofoStore> storeStream = fofoStoreRepository.selectByStatusFofoType(activeOnly, fofoType, offset, limit).stream();
30219 tejbeer 1445
 
31734 tejbeer 1446
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1447
        return this.getFofoRetailers(storeIds);
1448
    }
30219 tejbeer 1449
 
34813 aman 1450
    @Override
1451
    public Map<String, Object> computeIncomeMap(int fofoId, int yearMonth) {
1452
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1453
        LocalDateTime endOfMonth = startOfMonth.plusMonths(1);
1454
        YearMonth monthYear = YearMonth.now();
1455
 
1456
 
1457
        // 3) Fetch brand-wise data (same as original)
1458
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1459
                .selectLastMonthPendingIncomeByFofoId(fofoId, startOfMonth, endOfMonth);
1460
 
1461
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1462
                .selectLastMonthPurchaseInMarginByFofoId(fofoId, startOfMonth, endOfMonth);
1463
 
1464
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1465
                .selectFrontIncomeByBrand(fofoId, startOfMonth, endOfMonth);
1466
 
1467
        List<LastMonthCreditedIncomeModel> lastMonthSaleMargins = schemeInOutRepository
1468
                .selectLastMonthCreditedIncomeByFofoId(fofoId, startOfMonth, endOfMonth);
1469
 
1470
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository
1471
                .getTotalPayoutsByPartnerPeriod(
1472
                        YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()),
1473
                        fofoId, null, null);
1474
 
1475
        // 4) Convert to maps for brand-wise access
1476
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap =
1477
                lastMonthPendingIncomeModels.stream()
1478
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1479
 
1480
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap =
1481
                lastMonthPurchaseInMargins.stream()
1482
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1483
 
1484
        Map<String, LastMonthCreditedIncomeModel> lastMonthFrontEndIncomeMap =
1485
                lastMonthFrontEndIncomes.stream()
1486
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1487
 
1488
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap =
1489
                lastMonthSaleMargins.stream()
1490
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1491
 
1492
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream()
1493
                .collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand,
1494
                        Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1495
 
1496
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream()
1497
                .collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand,
1498
                        Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
1499
 
1500
        // 5) Get all unique brands
1501
        Set<String> brandSet = new HashSet<>();
1502
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1503
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1504
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1505
        brandSet.addAll(additionalPurchasePayout.keySet());
1506
        brandSet.addAll(additionSalePayout.keySet());
1507
        brandSet.addAll(lastMonthFrontEndIncomeMap.keySet());
1508
 
1509
        // 6) Calculate total amount per brand (same logic as original)
1510
        Map<String, Float> totalAmountMap = new HashMap<>();
1511
        brandSet.forEach(brand -> {
1512
            float total =
1513
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1514
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1515
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1516
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).floatValue()) +
1517
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).floatValue()) +
1518
                            (lastMonthFrontEndIncomeMap.get(brand) == null ? 0 : lastMonthFrontEndIncomeMap.get(brand).getAmount());
1519
            totalAmountMap.put(brand, total);
1520
        });
1521
 
1522
        // 7) Calculate aggregated totals
1523
        float totalIncome = totalAmountMap.values().stream()
1524
                .reduce(0f, Float::sum);
1525
 
1526
        float pendingIncome = lastMonthPendingIncomeMap.values().stream()
1527
                .map(LastMonthCreditedIncomeModel::getAmount)
1528
                .reduce(0f, Float::sum);
1529
 
1530
        float creditedIncome = totalIncome - pendingIncome;
1531
 
1532
        // 8) Build month labels
1533
        Map<Integer, String> monthValueMap = new HashMap<>();
1534
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MMM''uu");
1535
        for (int i = 0; i <= 5; i++) {
1536
            LocalDateTime m = LocalDateTime.now()
1537
                    .withDayOfMonth(1)
1538
                    .minusMonths(i);
1539
            monthValueMap.put(i, m.format(fmt));
1540
        }
1541
 
1542
        // 9) Assemble result with all brand-wise data
1543
        Map<String, Object> result = new HashMap<>();
1544
        result.put("totalIncome", totalIncome);
1545
        result.put("creditedIncome", creditedIncome);
1546
        result.put("pendingIncome", pendingIncome);
1547
        result.put("monthIndex", yearMonth);
1548
        result.put("monthValueMap", monthValueMap);
1549
 
1550
        // Include brand-wise data for detailed analysis
1551
        result.put("brandSet", brandSet);
1552
        result.put("totalAmountMap", totalAmountMap);
1553
        result.put("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1554
        result.put("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1555
        result.put("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1556
        result.put("additionalPurchasePayoutMap", additionalPurchasePayout);
1557
        result.put("additionalSalePayoutMap", additionSalePayout);
1558
        result.put("lastMonthFrontEndIncomeMap", lastMonthFrontEndIncomeMap);
1559
 
1560
        return result;
1561
    }
1562
 
22980 ashik.ali 1563
}