Subversion Repositories SmartDukaan

Rev

Rev 35971 | 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
 
35971 aman 330
        // Ensure UserAccount links new dtr user to retailer (handles case where
331
        // dtr.user was deleted and re-created with a new ID)
332
        try {
333
            userAccountRepository.selectSaholicByUserId(dtrUser.getId());
334
        } catch (ProfitMandiBusinessException e) {
335
            try {
336
                UserAccount ua = new UserAccount();
337
                ua.setAccountKey(retailer.getId());
338
                ua.setUserId(dtrUser.getId());
339
                ua.setType(AccountType.saholic);
340
                userAccountRepository.persist(ua);
341
            } catch (Exception ex) {
342
                LOGGER.error("Error creating saholic UserAccount for userId: {}", dtrUser.getId(), ex);
343
            }
344
        }
345
 
31734 tejbeer 346
        List<String> retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream().map(x -> x.getBlockBrands()).collect(Collectors.toList());
28024 tejbeer 347
 
31734 tejbeer 348
        LOGGER.info("retailerBlockBrands" + retailerBlockBrands);
28189 tejbeer 349
 
31734 tejbeer 350
        if (!retailerBlockBrands.isEmpty()) {
351
            retailerBlockBrandsRepository.deleteBrands(retailer.getId());
352
        }
28024 tejbeer 353
 
31734 tejbeer 354
        for (String blockBrand : updateRetailerRequest.getBlocksBrands()) {
355
            RetailerBlockBrands retailerBlockBrand = new RetailerBlockBrands();
28024 tejbeer 356
 
31734 tejbeer 357
            retailerBlockBrand.setFofoId(retailer.getId());
358
            retailerBlockBrand.setBlockBrands(blockBrand);
359
            retailerBlockBrandsRepository.persist(retailerBlockBrand);
28024 tejbeer 360
 
31734 tejbeer 361
        }
362
        map.put("retailerBlockBrands", retailerBlockBrands);
28024 tejbeer 363
 
31734 tejbeer 364
        Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
23955 govind 365
 
32953 amit.gupta 366
        userRoles = this.addRole(userRoles, dtrUser.getId(), roleRetailer.getId());
23955 govind 367
 
31734 tejbeer 368
        Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 369
 
31734 tejbeer 370
        if (updateRetailerRequest.isFofo()) {
32953 amit.gupta 371
            userRoles = this.addRole(userRoles, dtrUser.getId(), roleFofo.getId());
31734 tejbeer 372
        } else {
32953 amit.gupta 373
            userRoles = this.removeRole(userRoles, dtrUser.getId(), roleFofo.getId());
31734 tejbeer 374
        }
375
        map.put("fofoRole", this.containsRoleType(userRoles, roleFofo.getId()));
23955 govind 376
 
31734 tejbeer 377
        if (this.containsRoleType(userRoles, roleFofo.getId())) {
378
            this.createDefaultPaymentOption(retailer.getId());
379
        }
23955 govind 380
 
31734 tejbeer 381
        map.put("userRoles", userRoles);
382
        map.put("userRoleNames", this.toString(userRoles));
23955 govind 383
 
31734 tejbeer 384
        Address retailerAddress = (Address) map.get("retailerAddress");
385
        retailerAddress = this.updateRetailerAddress(retailerAddress, updateRetailerRequest.getAddress(), retailer.getId());
386
        map.put("retailerAddress", retailerAddress);
23955 govind 387
 
31734 tejbeer 388
        if (updateRetailerRequest.isFofo()) {
389
            FofoStore fofoStore = this.createFofoStoreCodeByRetailerId(retailer.getId(), updateRetailerRequest.getDistrictName(), retailerAddress.getState(), updateRetailerRequest);
390
            map.put("fofoStore", fofoStore);
35956 amit 391
            if (fofoStore.isClosed() && updateRetailerRequest.isActive()) {
392
                throw new ProfitMandiBusinessException("Store Closed", "Store Permanently Closed",
393
                        "This store is permanently closed and cannot be reactivated");
394
            }
31734 tejbeer 395
            fofoStore.setActive(updateRetailerRequest.isActive());
33131 ranu 396
            List<AST> astDetail = postOfficeService.getAreasAndTerritoriesByStateName(retailerAddress.getState());
397
            map.put("astDetail", astDetail);
31734 tejbeer 398
        }
23955 govind 399
 
32953 amit.gupta 400
        this.createPrivateDealUser(dtrUser, updateRetailerRequest.isFofo(), updateRetailerRequest.getGstNumber(), retailer, retailerAddress.getId());
31734 tejbeer 401
        map.put("gstNumber", updateRetailerRequest.getGstNumber());
402
        this.updateSaholicUser(retailer.getId(), retailerAddress.getId());
23955 govind 403
 
31734 tejbeer 404
        List<Shop> shops = (List<Shop>) map.get("shops");
405
        if (shops == null) {
406
            shops = new ArrayList<>();
407
            map.put("shops", shops);
408
        }
409
        this.updateRetailerShops(shops, updateRetailerRequest.getShops(), retailer.getId(), retailerAddress);
23955 govind 410
 
31734 tejbeer 411
        return map;
23955 govind 412
 
31734 tejbeer 413
    }
23955 govind 414
 
31734 tejbeer 415
    private void createDefaultPaymentOption(int fofoId) {
416
        List<Integer> paymentOptionIds = fofoPartnerPaymentOptionRepository.selectPaymentOptionIdsByFofoId(fofoId);
417
        if (paymentOptionIds.isEmpty()) {
418
            PaymentOption paymentOption = null;
419
            try {
420
                paymentOption = paymentOptionRepository.selectByName(PaymentOptionType.CASH.toString());
421
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
422
                paymentOption = new PaymentOption();
423
                paymentOption.setName(PaymentOptionType.CASH.toString());
424
                paymentOptionRepository.persist(paymentOption);
425
            }
426
            FofoPartnerPaymentOption fofoPartnerPaymentOption = new FofoPartnerPaymentOption();
427
            fofoPartnerPaymentOption.setFofoId(fofoId);
428
            fofoPartnerPaymentOption.setPaymentOptionId(paymentOption.getId());
429
            fofoPartnerPaymentOptionRepository.persist(fofoPartnerPaymentOption);
430
        }
23955 govind 431
 
31734 tejbeer 432
    }
23955 govind 433
 
33128 amit.gupta 434
    private User createUser(User user, UpdateRetailerRequest updateRetailerRequest) throws
435
            ProfitMandiBusinessException {
32965 amit.gupta 436
 
437
        User dtrUser = null;
438
        try {
439
            dtrUser = userRepository.selectByMobileNumber(updateRetailerRequest.getUserMobileNumber());
440
        } catch (ProfitMandiBusinessException e) {
441
            //Ignore the exception
442
        }
33140 ranu 443
        if (dtrUser != null && (user == null || user.getId() != dtrUser.getId()))
444
            throw new ProfitMandiBusinessException("Mobile already exist", updateRetailerRequest.getUserMobileNumber(), dtrUser.getEmailId());
32966 amit.gupta 445
 
446
        User dtrUserByEmail = null;
447
        try {
448
            dtrUserByEmail = userRepository.selectByEmailId(updateRetailerRequest.getUserEmailId());
449
        } catch (ProfitMandiBusinessException e) {
450
            //ignore the exception
451
        }
33025 amit.gupta 452
        if (user != null && dtrUserByEmail != null && user.getId() != dtrUserByEmail.getId())
32965 amit.gupta 453
            throw new ProfitMandiBusinessException("Email already exist", updateRetailerRequest.getUserEmailId(), "");
32953 amit.gupta 454
 
455
 
31734 tejbeer 456
        if (user == null) {
457
            user = new User();
458
            user.setCity("");
459
            user.setPinCode(0);
460
            user.setState("");
461
            user.setPassword("");
462
            user.setMobile_verified(false);
463
            user.setReferral_url("");
464
            user.setGroup_id(1);
465
            user.setStatus(1);
466
            user.setActivated(true);
467
            user.setCreateTimestamp(LocalDateTime.now());
468
        }
469
        user.setActivated(updateRetailerRequest.isActive());
470
        user.setFirstName(updateRetailerRequest.getUserFirstName());
471
        user.setLastName(updateRetailerRequest.getUserLastName());
472
        user.setMobileNumber(updateRetailerRequest.getUserMobileNumber());
473
        user.setEmailId(updateRetailerRequest.getUserEmailId());
474
        user.setUsername(updateRetailerRequest.getUserEmailId());
475
        user.setUpdateTimestamp(LocalDateTime.now());
476
        userRepository.persist(user);
477
        return user;
23955 govind 478
 
31734 tejbeer 479
    }
23955 govind 480
 
31734 tejbeer 481
    private int createSaholicUser(User user, String retailerName) {
482
        com.spice.profitmandi.dao.entity.user.User saholicUser = null;
483
        try {
484
            saholicUser = userUserRepository.selectByEmailId(user.getEmailId());
485
        } catch (ProfitMandiBusinessException e) {
486
            LOGGER.info("User doesnt exist in old system");
487
        }
488
        if (saholicUser == null) {
489
            Cart cart = new Cart();
490
            cart.setCartStatus(CartStatus.ACTIVE);
491
            cartRepository.persist(cart);
492
            saholicUser = new com.spice.profitmandi.dao.entity.user.User();
493
            saholicUser.setEmailId(user.getEmailId());
494
            saholicUser.setName(retailerName);
495
            saholicUser.setActiveCartId(cart.getId());
496
            saholicUser.setCreateTimestamp(LocalDateTime.now());
497
            userUserRepository.persist(saholicUser);
23955 govind 498
 
31734 tejbeer 499
            UserAccount ua = new UserAccount();
500
            ua.setAccountKey(saholicUser.getId());
501
            ua.setUserId(user.getId());
502
            ua.setType(AccountType.saholic);
503
            userAccountRepository.persist(ua);
23063 ashik.ali 504
 
31734 tejbeer 505
            UserAccount ua2 = new UserAccount();
506
            ua2.setAccountKey(saholicUser.getActiveCartId());
507
            ua2.setUserId(user.getId());
508
            ua2.setType(AccountType.cartId);
509
            userAccountRepository.persist(ua2);
510
            LOGGER.info("created....");
511
        }
512
        return saholicUser.getId();
513
    }
23955 govind 514
 
31734 tejbeer 515
    private com.spice.profitmandi.dao.entity.user.User createSaholicUser(
32953 amit.gupta 516
            LoginRequestResponseModel loginRequestResponseModel) {
31734 tejbeer 517
        com.spice.profitmandi.dao.entity.user.User saholicUser = null;
518
        try {
519
            saholicUser = userUserRepository.selectByEmailId(loginRequestResponseModel.getEmail());
520
            saholicUser.setCreateTimestamp(LocalDateTime.now());
521
        } catch (ProfitMandiBusinessException e) {
522
            LOGGER.info("User doesnt exist in old system");
523
        }
524
        if (saholicUser == null) {
525
            Cart cart = new Cart();
526
            cart.setCartStatus(CartStatus.ACTIVE);
527
            cartRepository.persist(cart);
528
            saholicUser = new com.spice.profitmandi.dao.entity.user.User();
529
            saholicUser.setPassword(getHash256(loginRequestResponseModel.getPassword()));
530
            saholicUser.setEmailId(loginRequestResponseModel.getEmail());
531
            saholicUser.setName(loginRequestResponseModel.getCustomerName());
532
            saholicUser.setActiveCartId(cart.getId());
533
            saholicUser.setCreateTimestamp(LocalDateTime.now());
534
            loginRequestResponseModel.setPassword(null);
535
            userUserRepository.persist(saholicUser);
536
        }
537
        return saholicUser;
538
    }
26522 amit.gupta 539
 
33128 amit.gupta 540
    private Retailer updateRetailer(User user, Retailer retailer, UpdateRetailerRequest updateRetailerRequest) throws
541
            ProfitMandiBusinessException {
31734 tejbeer 542
        if (retailer == null) {
543
            LOGGER.info("createSaholicUser.....");
544
            int saholicUserId = this.createSaholicUser(user, updateRetailerRequest.getName());
545
            retailer = new Retailer();
546
            retailer.setId(saholicUserId);
547
        }
548
        retailer.setActive(updateRetailerRequest.isActive());
549
        user.setActivated(updateRetailerRequest.isActive());//
550
        // this.createRole(user.getId(), RoleType.RETAILER);
551
        retailer.setName(updateRetailerRequest.getName());
552
        retailer.setNumber(updateRetailerRequest.getNumber());
553
        if (updateRetailerRequest.getNumber() == null || updateRetailerRequest.getNumber().isEmpty()) {
554
            retailer.setType(RetailerType.UNREGISTERED_SHOP);
555
        } else {
556
            retailer.setType(RetailerType.GSTIN);
557
        }
558
        if (updateRetailerRequest.getDocumentId() > 0) {
559
            if (retailer.getDocumentId() != null && retailer.getDocumentId() != updateRetailerRequest.getDocumentId()) {
560
                try {
561
                    documentRepository.deleteById(retailer.getDocumentId());
562
                } catch (Exception e) {
563
                    e.printStackTrace();
564
                }
565
            }
566
            retailer.setDocumentId(updateRetailerRequest.getDocumentId());
567
            documentRepository.markDocumentAsPersisted(updateRetailerRequest.getDocumentId());
568
        }
569
        retailerRepository.persist(retailer);
570
        return retailer;
571
    }
23955 govind 572
 
31734 tejbeer 573
    private void updateSaholicUser(int retailerId, int retailerAddressId) {
574
        try {
575
            com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(retailerId);
576
            user.setAddressId(retailerAddressId);
32555 amit.gupta 577
            Cart cart = cartRepository.selectById(user.getActiveCartId());
578
            cart.setAddressId(retailerAddressId);
31734 tejbeer 579
        } catch (ProfitMandiBusinessException e) {
23955 govind 580
 
31734 tejbeer 581
        }
582
    }
23955 govind 583
 
33128 amit.gupta 584
    private void createPrivateDealUser(User user, boolean fofo, String gstNumber, Retailer retailer,
585
                                       int retailerAddressId) {
31734 tejbeer 586
        PrivateDealUser privateDealUser = null;
587
        try {
588
            privateDealUser = privateDealUserRepository.selectById(retailer.getId());
589
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
590
            LOGGER.error("PrivateDealUser not found");
591
        }
23955 govind 592
 
31734 tejbeer 593
        // = privateDealUserRepository.selectById(saholicUser.getId());
594
        if (privateDealUser == null) {
595
            Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
596
            try {
597
                this.createPrivateDealUser(retailer.getId(), counterId, fofo);
598
            } catch (Exception e) {
599
                LOGGER.error("ERROR : ", e);
600
            }
601
        } else {
602
            if (privateDealUser.getCounterId() == null) {
603
                Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
604
                privateDealUser.setCounterId(counterId);
605
                privateDealUser.setFofo(fofo);
606
                privateDealUserRepository.persist(privateDealUser);
607
            } else {
608
                Counter counter = null;
609
                try {
610
                    counter = counterRepository.selectById(privateDealUser.getCounterId());
611
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
612
                    LOGGER.error("Counter not found with id [{}]", privateDealUser.getCounterId());
613
                }
614
                if (counter == null) {
615
                    this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(), retailerAddressId);
616
                } else {
617
                    counter.setGstin(gstNumber);
618
                    counterRepository.persist(counter);
619
                }
620
                privateDealUser.setFofo(fofo);
621
                privateDealUserRepository.persist(privateDealUser);
622
            }
623
        }
23955 govind 624
 
31734 tejbeer 625
        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
626
        privateDealUserAddressMapping.setUserId(retailer.getId());
627
        privateDealUserAddressMapping.setAddressId(retailerAddressId);
628
        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
629
    }
23955 govind 630
 
31734 tejbeer 631
    // Specifically set isFofo to true that has to be used by old system
632
    private void createPrivateDealUser(int retailerId, int counterId, boolean fofo) {
633
        PrivateDealUser privateDealUser = new PrivateDealUser();
634
        privateDealUser.setActive(true);
635
        privateDealUser.setBulkShipmentAmountLimit(fofo ? 1000000 : 50000);
636
        privateDealUser.setId(retailerId);
637
        privateDealUser.setCounterId(counterId);
638
        privateDealUser.setFofo(fofo);
639
        privateDealUserRepository.persist(privateDealUser);
640
    }
23955 govind 641
 
31734 tejbeer 642
    private Integer createCounter(String emailId, String gstNumber, String mobileNumber, String name, int addressId) {
643
        if (gstNumber != null && !gstNumber.isEmpty()) {
644
            Counter counter = new Counter();
645
            counter.setEmailId(emailId);
646
            counter.setGstin(gstNumber);
647
            counter.setMobileNumber(mobileNumber);
648
            counter.setName(name);
649
            counter.setAddressId(addressId);
650
            counterRepository.persist(counter);
651
            return counter.getId();
652
        } else {
653
            return null;
654
        }
655
    }
23955 govind 656
 
33128 amit.gupta 657
    private Address updateRetailerAddress(Address address, CustomAddress customAddress, int retailerId) throws
658
            ProfitMandiBusinessException {
31734 tejbeer 659
        if (address == null) {
35971 aman 660
            // Try to find existing address via RetailerRegisteredAddress (handles case where
661
            // dtr.user was deleted but retailer/address still exist in database)
662
            try {
663
                int existingAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailerId);
664
                address = addressRepository.selectById(existingAddressId);
665
            } catch (ProfitMandiBusinessException e) {
666
                // No existing address found for this retailer
667
            }
23955 govind 668
 
35971 aman 669
            if (address != null) {
670
                // Existing address found - update it
671
                this.updateAddress(address, customAddress);
672
                RetailerRegisteredAddress retailerRegisteredAddress = retailerRegisteredAddressRepository.selectByRetailerId(retailerId);
673
                retailerRegisteredAddress.setAddressId(address.getId());
674
                retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
675
            } else {
676
                // Truly new address
677
                address = new Address();
678
                address.setRetaierId(retailerId);
679
                this.updateAddress(address, customAddress);
680
 
681
                final RetailerRegisteredAddress retailerRegisteredAddress = new RetailerRegisteredAddress();
682
                retailerRegisteredAddress.setRetailerId(retailerId);
683
                retailerRegisteredAddress.setAddressId(address.getId());
684
                retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
685
            }
31734 tejbeer 686
        } else {
687
            this.updateAddress(address, customAddress);
688
            RetailerRegisteredAddress retailerRegisteredAddress = retailerRegisteredAddressRepository.selectByRetailerId(retailerId);
689
            retailerRegisteredAddress.setAddressId(address.getId());
690
            retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
691
        }
692
        return address;
693
    }
23955 govind 694
 
31734 tejbeer 695
    private void updateAddress(Address address, CustomAddress customAddress) throws ProfitMandiBusinessException {
696
        address.setName(customAddress.getName());
697
        address.setPhoneNumber(customAddress.getPhoneNumber());
698
        address.setLine1(customAddress.getLine1());
699
        address.setLine2(customAddress.getLine2());
700
        address.setCity(customAddress.getCity());
701
        address.setPinCode(customAddress.getPinCode());
702
        State state = stateRepository.selectByName(customAddress.getState());
703
        if (state == null) {
704
            throw new ProfitMandiBusinessException("State name", "Invalid State - Pls Contact Technology", "Invalid State - Pls Contact Technology");
705
        }
706
        address.setState(state.getName());
707
        addressRepository.persist(address);
708
        LOGGER.info("Address Updated" + address);
709
    }
23955 govind 710
 
33128 amit.gupta 711
    private void updateRetailerShops(List<Shop> shops, Set<CustomShop> customShops, int retailerId, Address
712
            sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
31734 tejbeer 713
        if (shops.isEmpty()) {
714
            for (CustomShop customShop : customShops) {
715
                Shop shop = new Shop();
716
                this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
717
                shops.add(shop);
718
            }
719
        } else {
720
            for (Shop shop : shops) {
721
                for (CustomShop customShop : customShops) {
722
                    if (shop.getId() == customShop.getShopId()) {
723
                        this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
724
                    }
725
                }
726
            }
727
            for (CustomShop customShop : customShops) {
728
                if (customShop.getShopId() == 0) {
729
                    Shop shop = new Shop();
730
                    this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
731
                    shops.add(shop);
732
                }
733
            }
734
        }
735
    }
23955 govind 736
 
33128 amit.gupta 737
    private void createOrUpdateShop(Shop shop, CustomShop customShop, int retailerId, Address
738
            sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
31734 tejbeer 739
        shop.setRetailerId(retailerId);
740
        shop.setName(customShop.getName());
741
        if (customShop.getDocumentId() > 0) {
742
            if (shop.getDocumentId() != null && shop.getDocumentId() != customShop.getDocumentId()) {
743
                try {
744
                    documentRepository.deleteById(shop.getDocumentId());
745
                } catch (Exception e) {
746
                    e.printStackTrace();
747
                }
748
            }
749
            shop.setDocumentId(customShop.getDocumentId());
750
            documentRepository.markDocumentAsPersisted(customShop.getDocumentId());
751
        }
752
        if (shop.getAddressId() == null) {
753
            Address address = null;
754
            if (customShop.isSameAsRetailerAddress()) {
755
                address = sameAsRetailerAddressValue;
756
            } else {
757
                // shop.setDocumentId(customShop.getDocumentId());
758
                address = new Address();
759
                this.updateAddress(address, customShop.getAddress());
760
            }
761
            shop.setAddressId(address.getId());
762
            shop.setAddress(address);
763
            shopRepository.persist(shop);
764
            ShopAddress shopAddress = null;
765
            try {
766
                shopAddress = shopAddressRepository.selectByShopId(shop.getId());
767
                shopAddress.setAddressId(address.getId());
768
            } catch (ProfitMandiBusinessException profitMandiBusinessException) {
769
                shopAddress = new ShopAddress();
770
                shopAddress.setAddressId(address.getId());
771
                shopAddress.setShopId(shop.getId());
772
            }
773
            shopAddressRepository.persist(shopAddress);
774
        } else {
775
            Address address = null;
776
            try {
777
                address = addressRepository.selectById(shop.getAddressId());
778
                CustomAddress customAddress = customShop.getAddress();
779
                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()))) {
780
                    address = new Address();
781
                    ShopAddress shopAddress = shopAddressRepository.selectByShopId(shop.getId());
782
                    this.updateAddress(address, customAddress);
783
                    shopAddress.setAddressId(address.getId());
784
                    shopAddressRepository.persist(shopAddress);
785
                    shop.setAddress(address);
786
                    shopRepository.persist(shop);
787
                }
788
            } catch (Exception e) {
789
                if (customShop.isSameAsRetailerAddress()) {
790
                    address = sameAsRetailerAddressValue;
791
                } else {
792
                    // shop.setDocumentId(customShop.getDocumentId());
793
                    address = new Address();
794
                    this.updateAddress(address, customShop.getAddress());
795
                }
796
                shop.setAddressId(address.getId());
797
                shop.setAddress(address);
798
                shopRepository.persist(shop);
799
                ShopAddress shopAddress = null;
800
                try {
801
                    shopAddress = shopAddressRepository.selectByShopId(shop.getId());
802
                    shopAddress.setAddressId(address.getId());
803
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
804
                    shopAddress = new ShopAddress();
805
                    shopAddress.setAddressId(address.getId());
806
                    shopAddress.setShopId(shop.getId());
807
                }
808
                shopAddressRepository.persist(shopAddress);
809
            }
23955 govind 810
 
31734 tejbeer 811
        }
23955 govind 812
 
31734 tejbeer 813
    }
23955 govind 814
 
33247 ranu 815
    private void addAddress(List<Shop> shops) throws ProfitMandiBusinessException {
31734 tejbeer 816
        Set<Integer> shopIds = this.toShopIds(shops);
817
        if (shopIds.isEmpty()) {
818
            return;
819
        }
820
        List<ShopAddress> shopAddresses = shopAddressRepository.selectByShopIds(shopIds);
821
        Map<Integer, Address> addressIdAddressMap = this.toAddressIdAddressMap(shopAddresses);
23955 govind 822
 
31734 tejbeer 823
        for (Shop shop : shops) {
824
            shop.setAddress(addressIdAddressMap.get(shop.getAddressId()));
825
        }
826
    }
22980 ashik.ali 827
 
33247 ranu 828
    private Map<Integer, Address> toAddressIdAddressMap(List<ShopAddress> shopAddresses) throws ProfitMandiBusinessException {
31734 tejbeer 829
        Map<Integer, Address> addressIdAddressMap = new HashMap<>();
830
        List<Integer> addressIds = this.toAddressIds(shopAddresses);
831
        List<Address> addresses = addressRepository.selectByIds(addressIds);
832
        for (Address address : addresses) {
833
            addressIdAddressMap.put(address.getId(), address);
834
        }
835
        return addressIdAddressMap;
836
    }
23955 govind 837
 
31734 tejbeer 838
    private List<Integer> toAddressIds(List<ShopAddress> shopAddresses) {
35394 amit 839
        return shopAddresses.stream()
840
                .map(ShopAddress::getAddressId)
841
                .collect(Collectors.toList());
31734 tejbeer 842
    }
23955 govind 843
 
31734 tejbeer 844
    private Set<Integer> toShopIds(List<Shop> shops) {
35394 amit 845
        return shops.stream()
846
                .map(Shop::getId)
847
                .collect(Collectors.toSet());
31734 tejbeer 848
    }
23955 govind 849
 
33247 ranu 850
    private String toString(List<UserRole> userRoles) throws ProfitMandiBusinessException {
31734 tejbeer 851
        Set<Integer> roleIds = new HashSet<>();
852
        for (UserRole userRole : userRoles) {
853
            roleIds.add(userRole.getRoleId());
854
        }
855
        List<Role> roles = roleRepository.selectByIds(roleIds);
31735 amit.gupta 856
        Function<Role, String> roleToNameFunction = role -> String.valueOf(role.getName());
31734 tejbeer 857
        Set<String> userRoleStrings = roles.stream().map(roleToNameFunction).collect(Collectors.toSet());
858
        return String.join(", ", userRoleStrings);
859
    }
23955 govind 860
 
33128 amit.gupta 861
    private FofoStore createFofoStoreCodeByRetailerId(int retailerId, String districtName, String
862
            stateName, UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
31734 tejbeer 863
        FofoStore fofoStore = null;
864
        try {
865
            fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
866
            fofoStore.setActivationType(ActivationType.ACTIVE);
30097 tejbeer 867
 
31734 tejbeer 868
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
23955 govind 869
 
31734 tejbeer 870
        }
23955 govind 871
 
31734 tejbeer 872
        if (fofoStore != null) {
873
            fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
33124 ranu 874
            fofoStore.setAstId(updateRetailerRequest.getAstId());
31734 tejbeer 875
            fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
876
            fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
877
            fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
878
            fofoStore.setFofoType(updateRetailerRequest.getFofoType());
35896 amit 879
            fofoStore.setGstNumber(updateRetailerRequest.getGstNumber());
31734 tejbeer 880
        } else {
881
            int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailerId);
882
            Address retailerAddress = addressRepository.selectById(retailerAddressId);
23955 govind 883
 
31734 tejbeer 884
            // StateInfo stateInfo = null;
885
            State stateInfo = null;
886
            try {
30527 tejbeer 887
 
31734 tejbeer 888
                stateInfo = stateRepository.selectByName(retailerAddress.getState());
889
                // stateInfo = Utils.getStateInfo(retailerAddress.getState());
890
            } catch (Exception e) {
891
                // TODO Auto-generated catch block
892
                e.printStackTrace();
893
                // throw new ProfitMandiBusinessException();
894
            }
895
            DistrictMaster districtMaster = districtMasterRepository.selectByNameAndStateShortName(districtName, stateInfo.getShortName());
23955 govind 896
 
31734 tejbeer 897
            fofoStore = new FofoStore();
898
            fofoStore.setId(retailerId);
899
            fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
900
            fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
31730 tejbeer 901
 
31734 tejbeer 902
            fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
903
            fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
35289 amit 904
 
905
            //Check for Trial users here
32615 raveendra. 906
            int nextStoreCodeInt = fofoStoreRepository.selectLatestStore().getCodeInt() + 1;
907
 
31734 tejbeer 908
            String fofoStoreCode = StringUtils.generateFofoStoreSequence(
32615 raveendra. 909
                    districtMaster.getStateShortName() + districtMaster.getShortName(), nextStoreCodeInt);
35306 amit 910
            try {
911
                TrialForm trialForm = trialFormRepository.selectByEmailOrMobile(updateRetailerRequest.getUserMobileNumber());
912
                if (trialForm != null) {
913
                    fofoStoreCode = "T-" + fofoStoreCode;
914
                    fofoStore.setTrial(true);
915
                    fofoStore.setTrialStart(LocalDate.now());
916
                    fofoStore.setTrialEnd(LocalDate.now().plusDays(31));
35360 aman 917
                    trialForm.setStatus(ProfitMandiConstants.Status.TMP_STORE_CODE_CREATED);
35306 amit 918
                    //TODO:Amit G, Send store code notification to retailer.
919
                }
920
            } catch (ProfitMandiBusinessException e) {
35289 amit 921
            }
31734 tejbeer 922
            fofoStore.setCode(fofoStoreCode);
32615 raveendra. 923
            fofoStore.setCodeInt(nextStoreCodeInt);
31734 tejbeer 924
            fofoStore.setBagsLastCredited(LocalDateTime.now());
35203 amit 925
            if (retailerAddress.getName().contains(ProfitMandiConstants.COMPANY_NAME) || retailerAddress.getName().contains(ProfitMandiConstants.COMPANY_SHORT_NAME)) {
926
                fofoStore.setInternal(true);
927
            } else {
928
                fofoStore.setInternal(false);
929
            }
930
            fofoStore.setFofoType(FofoType.FRANCHISE);
31734 tejbeer 931
            fofoStore.setFofoType(updateRetailerRequest.getFofoType());
932
            fofoStore.setActivationType(ActivationType.ACTIVE);
35896 amit 933
            fofoStore.setGstNumber(updateRetailerRequest.getGstNumber());
31734 tejbeer 934
            fofoStoreRepository.persist(fofoStore);
28908 tejbeer 935
 
36064 aman 936
            // Link store code to onboarding panel (only for NEW store creation)
35971 aman 937
            try {
36064 aman 938
                PartnerOnBoardingPanel pobp = partnerOnBoardingPanelRepository.selectByPhoneNumber(
939
                        Long.parseLong(retailerAddress.getPhoneNumber()));
35971 aman 940
                if (pobp != null) {
36064 aman 941
                    PartnerVerificationpanel pvp = partnerOnboardingVerificationRepository
942
                            .selectByOnboardingId(pobp.getId());
943
                    if (pvp != null && PartnerVerificationApprovalStatus.YES.equals(pvp.getApproval())) {
35971 aman 944
                        pobp.setCode(fofoStore.getCode());
945
                        storeTimelineTatService.onCodeCreated(pobp.getId());
946
                        PartnerVerificationCheckboxes cb = partnerOnboardingVerificationRepository
947
                                .selectVerifiCheckboxByOnboardingId(pobp.getId());
948
                        if (cb == null) {
949
                            cb = new PartnerVerificationCheckboxes();
950
                            cb.setOnboardingId(pobp.getId());
951
                            partnerOnboardingVerificationRepository.persist(cb);
952
                        }
953
                    }
954
                }
955
            } catch (Exception e) {
36064 aman 956
                LOGGER.error("Error linking store code to onboarding for retailerId: {}", retailerId, e);
35971 aman 957
            }
958
 
36064 aman 959
            PincodePartner pincodePartner = pincodePartnerRepository.selectPartnerByPincode(retailerAddress.getPinCode(), fofoStore.getId());
960
            if (pincodePartner == null) {
961
                PincodePartner pinPartner = new PincodePartner();
962
                pinPartner.setFofoId(fofoStore.getId());
963
                pinPartner.setPincode(retailerAddress.getPinCode());
964
                pincodePartnerRepository.perist(pinPartner);
965
            }
35418 aman 966
 
36064 aman 967
            if (fofoStore.isTrial()) {
968
                storeTimelineTatService.sendTrialStoreCreationMail(fofoStore, updateRetailerRequest);
969
                storeTimelineTatService.sendTrialActivationMail(fofoStore, updateRetailerRequest);
970
            }
35289 amit 971
        }
972
 
31734 tejbeer 973
        return fofoStore;
974
    }
23955 govind 975
 
31734 tejbeer 976
    @Override
33128 amit.gupta 977
    public FofoStore createFofoStoreCodeByUserId(int userId, String districtName, String
978
            stateName, UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
31734 tejbeer 979
        User user = userRepository.selectById(userId);
980
        // = userAccountRepository.selectRetailerIdByUserId(user.getId());
981
        UserAccount userAccounts = userAccountRepository.selectSaholicByUserId(user.getId());
982
        Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
983
        Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
984
        try {
985
            userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleFofo.getId());
986
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
987
            throw new ProfitMandiBusinessException(ProfitMandiConstants.USER_ID, user.getId(), "USR_1013");
988
        }
989
        return this.createFofoStoreCodeByRetailerId(retailer.getId(), districtName, stateName, updateRetailerRequest);
23955 govind 990
 
31734 tejbeer 991
    }
23955 govind 992
 
31734 tejbeer 993
    @Override
994
    public List<DistrictMaster> getAllDistrictMaster(String stateName) {
995
        // StateInfo stateInfo = null;
996
        State stateInfo = null;
997
        try {
998
            // stateInfo = Utils.getStateInfo(stateName);
30525 tejbeer 999
 
31734 tejbeer 1000
            stateInfo = stateRepository.selectByName(stateName);
1001
        } catch (Exception e) {
1002
            e.printStackTrace();
1003
            // throw new ProfitMandiBusinessException();
1004
        }
1005
        return districtMasterRepository.selectByStateShortName(stateInfo.getShortName());
1006
    }
22980 ashik.ali 1007
 
31734 tejbeer 1008
    @Override
34149 tejus.loha 1009
    @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1010
    public Map<Integer, CustomRetailer> getFofoRetailers(List<Integer> fofoIds) throws ProfitMandiBusinessException {
35394 amit 1011
        if (fofoIds == null || fofoIds.isEmpty()) {
1012
            return new HashMap<>();
1013
        }
1014
 
31734 tejbeer 1015
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
35440 amit 1016
 
1017
        // Check for saholicUsers without corresponding dtrUser
1018
        List<String> saholicEmails = saholicUsers.stream()
1019
                .map(com.spice.profitmandi.dao.entity.user.User::getEmailId)
1020
                .filter(email -> email != null)
1021
                .collect(Collectors.toList());
1022
        Set<String> dtrUserEmails = userRepository.selectAllByEmailIds(saholicEmails).stream()
1023
                .map(User::getEmailId)
1024
                .collect(Collectors.toSet());
1025
        for (com.spice.profitmandi.dao.entity.user.User saholicUser : saholicUsers) {
1026
            if (saholicUser.getEmailId() != null && !dtrUserEmails.contains(saholicUser.getEmailId())) {
1027
                LOGGER.warn("dtrUser not found for saholicUser - id: {}, email: {}", saholicUser.getId(), saholicUser.getEmailId());
1028
            }
1029
        }
1030
 
35394 amit 1031
        Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
1032
                .filter(x -> x.getAddressId() != null)
1033
                .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.user.User::getAddressId, x -> x));
31734 tejbeer 1034
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
35394 amit 1035
 
1036
        // Batch fetch all FofoStores to avoid N+1 queries
1037
        Set<Integer> retailerIds = addresses.stream().map(Address::getRetaierId).collect(Collectors.toSet());
1038
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(retailerIds))
1039
                .stream().collect(Collectors.toMap(FofoStore::getId, fs -> fs));
1040
 
31734 tejbeer 1041
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
1042
        for (Address address : addresses) {
1043
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
35394 amit 1044
            FofoStore fs = fofoStoreMap.get(address.getRetaierId());
1045
            if (fs == null) {
31734 tejbeer 1046
                continue;
1047
            }
35394 amit 1048
 
35896 amit 1049
            CustomRetailer customRetailer = buildCustomRetailer(user, address, fs);
31734 tejbeer 1050
            customRetailersMap.put(customRetailer.getPartnerId(), customRetailer);
1051
        }
1052
        return customRetailersMap;
1053
    }
25295 amit.gupta 1054
 
35394 amit 1055
    /**
1056
     * Helper method to build CustomRetailer from fetched entities
1057
     */
1058
    private CustomRetailer buildCustomRetailer(com.spice.profitmandi.dao.entity.user.User user, Address address,
35896 amit 1059
                                               FofoStore fs) {
35394 amit 1060
        CustomRetailer customRetailer = new CustomRetailer();
1061
        customRetailer.setEmail(user.getEmailId());
1062
        customRetailer.setBusinessName(address.getName());
1063
        customRetailer.setMobileNumber(address.getPhoneNumber());
1064
        customRetailer.setCode(fs.getCode());
1065
        customRetailer.setAstId(fs.getAstId());
1066
        customRetailer.setActivationType(fs.getActivationType());
1067
        customRetailer.setCounterSize(fs.getCounterSize());
1068
        customRetailer.setCounterPotential(fs.getCounterPotential());
1069
        customRetailer.setWarehouseId(fs.getWarehouseId());
1070
        customRetailer.setPartnerId(fs.getId());
1071
        customRetailer.setFofoType(fs.getFofoType());
1072
        customRetailer.setCartId(user.getActiveCartId());
1073
 
35896 amit 1074
        customRetailer.setGstNumber(fs.getGstNumber());
35394 amit 1075
 
1076
        CustomAddress customAddress = buildCustomAddress(address);
1077
        customRetailer.setAddress(customAddress);
1078
        customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + customRetailer.getCode() + "- " + customAddress.getCity());
1079
        return customRetailer;
1080
    }
1081
 
1082
    /**
1083
     * Helper method to build CustomAddress from Address entity
1084
     */
1085
    private CustomAddress buildCustomAddress(Address address) {
1086
        CustomAddress customAddress = new CustomAddress();
1087
        customAddress.setCity(address.getCity());
1088
        customAddress.setState(address.getState());
1089
        customAddress.setLine1(address.getLine1());
1090
        customAddress.setLine2(address.getLine2());
1091
        customAddress.setPinCode(address.getPinCode());
1092
        customAddress.setName(address.getName());
1093
        customAddress.setPhoneNumber(address.getPhoneNumber());
1094
        return customAddress;
1095
    }
1096
 
31734 tejbeer 1097
    @Override
1098
    @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
1099
    public CustomRetailer getFofoRetailer(int fofoId) throws ProfitMandiBusinessException {
1100
        com.spice.profitmandi.dao.entity.user.User saholicUser = userUserRepository.selectById(fofoId);
35440 amit 1101
        User dtrUser = null;
1102
        try {
1103
            dtrUser = userRepository.selectByEmailId(saholicUser.getEmailId());
1104
        } catch (ProfitMandiBusinessException e) {
1105
            LOGGER.info("User not found for emailId: {} and id is : {}", saholicUser.getEmailId(), saholicUser.getId());
1106
        }
31734 tejbeer 1107
        FofoStore store = fofoStoreRepository.selectByRetailerId(fofoId);
35394 amit 1108
        Address address = addressRepository.selectById(saholicUser.getAddressId());
1109
 
31734 tejbeer 1110
        CustomRetailer customRetailer = new CustomRetailer();
1111
        customRetailer.setEmail(saholicUser.getEmailId());
1112
        customRetailer.setBusinessName(address.getName());
1113
        customRetailer.setMobileNumber(address.getPhoneNumber());
31862 tejbeer 1114
        customRetailer.setFirstName(dtrUser.getFirstName());
1115
        customRetailer.setLastName(dtrUser.getLastName());
35394 amit 1116
        customRetailer.setCartId(saholicUser.getActiveCartId());
1117
        customRetailer.setPartnerId(address.getRetaierId());
1118
        customRetailer.setCode(store.getCode());
1119
        customRetailer.setAstId(store.getAstId());
1120
        customRetailer.setActivationType(store.getActivationType());
1121
        customRetailer.setWarehouseId(store.getWarehouseId());
1122
 
35896 amit 1123
        customRetailer.setGstNumber(store.getGstNumber());
35394 amit 1124
 
1125
        // Reuse helper method for CustomAddress
1126
        CustomAddress customAddress = buildCustomAddress(address);
1127
        customRetailer.setAddress(customAddress);
31734 tejbeer 1128
        customRetailer.setDisplayName(address.getName() + " - " + address.getCity());
35394 amit 1129
 
31734 tejbeer 1130
        return customRetailer;
1131
    }
26125 amit.gupta 1132
 
31734 tejbeer 1133
    @Override
33247 ranu 1134
    public Map<Integer, CustomRetailer> getFofoRetailerUserId(List<Integer> fofoIds) throws ProfitMandiBusinessException {
35394 amit 1135
        if (fofoIds == null || fofoIds.isEmpty()) {
1136
            return new HashMap<>();
1137
        }
1138
 
31734 tejbeer 1139
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
35394 amit 1140
        Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
1141
                .filter(x -> x.getAddressId() != null)
1142
                .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.user.User::getAddressId, x -> x));
31734 tejbeer 1143
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
35394 amit 1144
 
1145
        // Batch fetch all retailerIds to userIds mapping to avoid N+1
1146
        Set<Integer> retailerIds = addresses.stream().map(Address::getRetaierId).collect(Collectors.toSet());
1147
        Map<Integer, Integer> retailerIdToUserIdMap = getUserIdRetailerIdMapReverse(retailerIds);
1148
 
35896 amit 1149
        // Batch fetch FofoStores for GST numbers
1150
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(retailerIds))
1151
                .stream().collect(Collectors.toMap(FofoStore::getId, fs -> fs));
35394 amit 1152
 
31734 tejbeer 1153
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
1154
        for (Address address : addresses) {
1155
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
35394 amit 1156
            Integer userId = retailerIdToUserIdMap.get(user.getId());
1157
            if (userId == null) {
1158
                continue;
1159
            }
1160
 
31734 tejbeer 1161
            CustomRetailer customRetailer = new CustomRetailer();
1162
            customRetailer.setEmail(user.getEmailId());
1163
            customRetailer.setBusinessName(address.getName());
1164
            customRetailer.setMobileNumber(address.getPhoneNumber());
35394 amit 1165
            customRetailer.setCartId(user.getActiveCartId());
1166
            customRetailer.setPartnerId(address.getRetaierId());
1167
 
35896 amit 1168
            FofoStore fs = fofoStoreMap.get(address.getRetaierId());
1169
            customRetailer.setGstNumber(fs != null ? fs.getGstNumber() : null);
35394 amit 1170
 
1171
            CustomAddress customAddress = buildCustomAddress(address);
1172
            customRetailer.setAddress(customAddress);
1173
            customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + customAddress.getCity());
31734 tejbeer 1174
            customRetailersMap.put(userId, customRetailer);
1175
        }
1176
        return customRetailersMap;
1177
    }
25295 amit.gupta 1178
 
35394 amit 1179
    /**
1180
     * Helper method to get retailerId to userId mapping
1181
     */
1182
    private Map<Integer, Integer> getUserIdRetailerIdMapReverse(Set<Integer> retailerIds) {
1183
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1184
        return userAccounts.stream().collect(Collectors.toMap(UserAccount::getAccountKey, UserAccount::getUserId));
1185
    }
1186
 
31734 tejbeer 1187
    @Override
33247 ranu 1188
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap() throws ProfitMandiBusinessException {
31734 tejbeer 1189
        Role roleFofo = null;
1190
        try {
1191
            roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
1192
        } catch (ProfitMandiBusinessException e) {
1193
            // TODO Auto-generated catch block
1194
            e.printStackTrace();
1195
        }
1196
        Role roleRetailer = null;
1197
        try {
1198
            roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
1199
        } catch (ProfitMandiBusinessException e) {
1200
            // TODO Auto-generated catch block
1201
            e.printStackTrace();
1202
        }
1203
        Set<Integer> roleIds = new HashSet<>();
1204
        roleIds.add(roleFofo.getId());
1205
        roleIds.add(roleRetailer.getId());
1206
        List<Integer> userIds = userRoleRepository.selectUserIdsByRoleIds(roleIds);
1207
        List<User> users = userRepository.selectAllByIds(new HashSet<>(userIds));
1208
        Map<Integer, Integer> userIdRetailerIdMap = this.getUserIdRetailerIdMap(userIds);
1209
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1210
        for (User user : users) {
1211
            retailerIdEmailIdMap.put(userIdRetailerIdMap.get(user.getId()), user.getEmailId());
1212
        }
1213
        return retailerIdEmailIdMap;
1214
    }
23955 govind 1215
 
31734 tejbeer 1216
    private Map<Integer, Integer> getUserIdRetailerIdMap(List<Integer> userIds) {
1217
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByUserIds(new HashSet<>(userIds));
1218
        Map<Integer, Integer> userIdRetailerIdMap = new HashMap<>();
1219
        for (UserAccount userAccount : userAccounts) {
1220
            userIdRetailerIdMap.put(userAccount.getUserId(), userAccount.getAccountKey());
1221
        }
1222
        return userIdRetailerIdMap;
1223
    }
25295 amit.gupta 1224
 
33247 ranu 1225
    private Map<Integer, String> getUserIdEmailIdMap(Set<Integer> userIds) throws ProfitMandiBusinessException {
31734 tejbeer 1226
        List<User> users = userRepository.selectAllByIds(userIds);
1227
        Map<Integer, String> userIdEmailIdMap = new HashMap<>();
1228
        for (User user : users) {
1229
            userIdEmailIdMap.put(user.getId(), user.getEmailId());
1230
        }
1231
        return userIdEmailIdMap;
1232
    }
23509 amit.gupta 1233
 
31734 tejbeer 1234
    @Override
33247 ranu 1235
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap(Set<Integer> retailerIds) throws ProfitMandiBusinessException {
31734 tejbeer 1236
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1237
        Set<Integer> userIds = new HashSet<>();
1238
        for (UserAccount userAccount : userAccounts) {
1239
            userIds.add(userAccount.getUserId());
1240
        }
1241
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1242
        Map<Integer, String> userIdEmailIdMap = this.getUserIdEmailIdMap(userIds);
1243
        for (UserAccount userAccount : userAccounts) {
1244
            retailerIdEmailIdMap.put(userAccount.getAccountKey(), userIdEmailIdMap.get(userAccount.getUserId()));
1245
        }
1246
        return retailerIdEmailIdMap;
1247
    }
25295 amit.gupta 1248
 
31734 tejbeer 1249
    @Override
33247 ranu 1250
    public Map<Integer, String> getAllFofoRetailerIdNameMap(List<Integer> storeIds) throws ProfitMandiBusinessException {
31734 tejbeer 1251
        Map<Integer, CustomRetailer> retailersMap = this.getFofoRetailers(storeIds);
1252
        Map<Integer, String> retailerIdNameMap = new HashMap<>();
1253
        for (Map.Entry<Integer, CustomRetailer> entry : retailersMap.entrySet()) {
1254
            retailerIdNameMap.put(entry.getKey(), entry.getValue().getBusinessName() + "-" + entry.getValue().getAddress().getCity());
1255
        }
1256
        return retailerIdNameMap;
1257
    }
24168 amit.gupta 1258
 
31734 tejbeer 1259
    @Override
1260
    @Cacheable(value = "FofoRetailerIdNameMap", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1261
    public Map<Integer, String> getAllFofoRetailerIdNameMap() throws ProfitMandiBusinessException {
31734 tejbeer 1262
        List<FofoStore> stores = fofoStoreRepository.selectAll();
1263
        List<Integer> storeIds = stores.stream().map(x -> x.getId()).collect(Collectors.toList());
1264
        return this.getAllFofoRetailerIdNameMap(storeIds);
1265
    }
24349 amit.gupta 1266
 
31734 tejbeer 1267
    @Override
33247 ranu 1268
    public List<MapWrapper<Integer, String>> getAllFofoRetailerIdNameList() throws ProfitMandiBusinessException {
31734 tejbeer 1269
        List<MapWrapper<Integer, String>> mapWrappers = new ArrayList<>();
1270
        // TODO Auto-generated method stub
1271
        Map<Integer, String> fofoIdNameMap = this.getAllFofoRetailerIdNameMap();
1272
        fofoIdNameMap.forEach((fofoId, name) -> {
1273
            MapWrapper<Integer, String> idWrapper = new MapWrapper<>();
1274
            idWrapper.setKey(fofoId);
1275
            idWrapper.setValue(name);
1276
            mapWrappers.add(idWrapper);
1277
        });
1278
        return mapWrappers;
1279
    }
24349 amit.gupta 1280
 
31734 tejbeer 1281
    @Override
1282
    @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1283
    public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly) throws ProfitMandiBusinessException {
35394 amit 1284
        Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream()
1285
                .filter(fs -> fs.getFofoType().equals(FofoType.FRANCHISE));
31734 tejbeer 1286
        if (activeOnly) {
35394 amit 1287
            storeStream = storeStream.filter(FofoStore::isActive);
31734 tejbeer 1288
        }
35394 amit 1289
        List<Integer> storeIds = storeStream.map(FofoStore::getId).collect(Collectors.toList());
31734 tejbeer 1290
        return this.getFofoRetailers(storeIds);
1291
    }
25295 amit.gupta 1292
 
31734 tejbeer 1293
    @Override
33367 ranu 1294
    @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
1295
    public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly, String pinCode) throws ProfitMandiBusinessException {
1296
        List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pinCode);
1297
        List<Integer> storeIds = new ArrayList<>();
35394 amit 1298
        if (!pincodePartners.isEmpty()) {
1299
            List<Integer> fofoIds = pincodePartners.stream().map(PincodePartner::getFofoId).collect(Collectors.toList());
33367 ranu 1300
            List<FofoStore> fofoStores = fofoStoreRepository.selectActivePartnersByRetailerIds(fofoIds);
35394 amit 1301
            storeIds = fofoStores.stream().map(FofoStore::getId).collect(Collectors.toList());
33367 ranu 1302
        }
1303
        return this.getFofoRetailers(storeIds);
1304
    }
1305
 
1306
    @Override
31734 tejbeer 1307
    @Cacheable(value = "allFofoRetailers", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1308
    public Map<Integer, CustomRetailer> getAllFofoRetailers() throws ProfitMandiBusinessException {
35394 amit 1309
        List<Integer> storeIds = fofoStoreRepository.selectAll().stream()
1310
                .map(FofoStore::getId)
1311
                .collect(Collectors.toList());
31734 tejbeer 1312
        return this.getFofoRetailers(storeIds);
1313
    }
27861 tejbeer 1314
 
31734 tejbeer 1315
    @Override
34619 ranu 1316
    @Cacheable(value = "allFofoRetailersInternalFalse", cacheManager = "thirtyMinsTimeOutCacheManager")
1317
    public Map<Integer, CustomRetailer> getAllFofoRetailersInternalFalse() throws ProfitMandiBusinessException {
35394 amit 1318
        List<Integer> storeIds = fofoStoreRepository.selectAll().stream()
1319
                .filter(fs -> fs.getFofoType().equals(FofoType.FRANCHISE))
1320
                .map(FofoStore::getId)
1321
                .collect(Collectors.toList());
34619 ranu 1322
        return this.getFofoRetailers(storeIds);
1323
    }
1324
 
1325
    @Override
33128 amit.gupta 1326
    public LoginRequestResponseModel registerWebUser(LoginRequestResponseModel loginRequestModel) throws
1327
            ProfitMandiBusinessException {
26522 amit.gupta 1328
 
31734 tejbeer 1329
        com.spice.profitmandi.dao.entity.user.User saholicUser = this.createSaholicUser(loginRequestModel);
1330
        loginRequestModel.setUserId(saholicUser.getId());
26522 amit.gupta 1331
 
31734 tejbeer 1332
        this.createRetailerAddress(loginRequestModel);
26522 amit.gupta 1333
 
31734 tejbeer 1334
        this.createPrivateDealUser(loginRequestModel);
1335
        this.updateSaholicUser(saholicUser.getId(), loginRequestModel.getBusinessAddress().getId());
26522 amit.gupta 1336
 
31734 tejbeer 1337
        return loginRequestModel;
26522 amit.gupta 1338
 
31734 tejbeer 1339
    }
26522 amit.gupta 1340
 
31734 tejbeer 1341
    private void createPrivateDealUser(LoginRequestResponseModel loginRequestModel) {
26522 amit.gupta 1342
 
31734 tejbeer 1343
        Integer counterId = this.createCounter(loginRequestModel.getEmail(), loginRequestModel.getGstNumber(), loginRequestModel.getBusinessAddress().getPhoneNumber(), loginRequestModel.getBusinessAddress().getName(), loginRequestModel.getBusinessAddress().getId());
1344
        try {
1345
            this.createPrivateDealUser(loginRequestModel.getUserId(), counterId, false);
1346
        } catch (Exception e) {
1347
            LOGGER.error("ERROR : ", e);
1348
        }
26522 amit.gupta 1349
 
31734 tejbeer 1350
        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
1351
        privateDealUserAddressMapping.setUserId(loginRequestModel.getUserId());
1352
        privateDealUserAddressMapping.setAddressId(loginRequestModel.getBusinessAddress().getId());
1353
        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
26522 amit.gupta 1354
 
31734 tejbeer 1355
    }
26522 amit.gupta 1356
 
33128 amit.gupta 1357
    private void createRetailerAddress(LoginRequestResponseModel loginRequestResponseModel) throws
1358
            ProfitMandiBusinessException {
31734 tejbeer 1359
        Address businessAddress = loginRequestResponseModel.getBusinessAddress();
1360
        businessAddress.setRetaierId(loginRequestResponseModel.getUserId());
1361
        addressRepository.persist(businessAddress);
1362
    }
26536 amit.gupta 1363
 
31734 tejbeer 1364
    private String getHash256(String originalString) {
1365
        String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
1366
        LOGGER.info("Hash String {}", hashString);
1367
        return hashString;
1368
    }
26533 amit.gupta 1369
 
31734 tejbeer 1370
    @Override
1371
    @Cacheable(value = "fofoIdUrl", cacheManager = "thirtyMinsTimeOutCacheManager")
1372
    public Map<Integer, String> getAllFofoRetailerIdUrlMap() {
1373
        Map<Integer, String> fofoRetailerUrlMap = new HashMap<>();
35394 amit 1374
        List<FofoStore> stores = fofoStoreRepository.selectAll().stream()
1375
                .filter(FofoStore::isActive)
1376
                .collect(Collectors.toList());
1377
 
1378
        // Batch fetch all district masters to avoid N+1 queries
1379
        List<DistrictMaster> allDistrictMasters = districtMasterRepository.selectAll();
1380
        Map<String, DistrictMaster> districtMasterMap = allDistrictMasters.stream()
1381
                .collect(Collectors.toMap(
1382
                        dm -> dm.getStateShortName() + "_" + dm.getShortName(),
1383
                        dm -> dm,
1384
                        (existing, replacement) -> existing));
1385
 
1386
        // Get fallback district master
1387
        DistrictMaster fallbackDistrict = districtMasterMap.get("HR_FB");
1388
 
31734 tejbeer 1389
        for (FofoStore store : stores) {
35394 amit 1390
            String codeWithoutDigits = store.getCode().replaceAll("\\d+", "");
1391
            if (codeWithoutDigits.length() < 3) {
1392
                LOGGER.warn("Invalid store code format: {}", store.getCode());
1393
                continue;
1394
            }
1395
            String stateShortName = codeWithoutDigits.substring(0, 2);
1396
            String districtShortName = codeWithoutDigits.substring(2);
1397
 
1398
            // Use pre-fetched map instead of N+1 query
1399
            String key = stateShortName + "_" + districtShortName;
1400
            DistrictMaster districtMaster = districtMasterMap.getOrDefault(key, fallbackDistrict);
1401
 
31734 tejbeer 1402
            if (districtMaster == null) {
35394 amit 1403
                LOGGER.warn("No district master found for key: {} and no fallback available", key);
1404
                continue;
31734 tejbeer 1405
            }
35394 amit 1406
 
1407
            String urlString = districtMaster.getStateShortName() + "/" +
1408
                    Utils.getHyphenatedString(districtMaster.getName()) + "/" + store.getCode();
31734 tejbeer 1409
            fofoRetailerUrlMap.put(store.getId(), urlString.toLowerCase());
1410
        }
1411
        return fofoRetailerUrlMap;
1412
    }
26533 amit.gupta 1413
 
31734 tejbeer 1414
    @Override
1415
    @Cacheable(value = "storeCodeRetailerMap", cacheManager = "thirtyMinsTimeOutCacheManager")
1416
    public Map<String, Integer> getStoreCodeRetailerMap() {
1417
        Map<Integer, String> map = this.getAllFofoRetailerIdUrlMap();
1418
        Map<String, Integer> returnMap = map.entrySet().stream().collect(Collectors.toMap(x -> {
1419
            String[] splitString = x.getValue().split("/");
1420
            return splitString[splitString.length - 1];
1421
        }, x -> x.getKey()));
1422
        LOGGER.info("returnMap {}", returnMap);
1423
        return returnMap;
1424
    }
27877 amit.gupta 1425
 
1426
 
31734 tejbeer 1427
    @Override
32668 raveendra. 1428
    public User getEmail() {
1429
        return null;
1430
    }
1431
 
1432
    @Override
1433
    public void update(com.spice.profitmandi.dao.entity.user.User user) {
1434
    }
1435
 
1436
    @Override
1437
    public void updateRetailerEmail(int fofoId, String newEmail) throws ProfitMandiBusinessException {
1438
        User dtrUser = null;
1439
        com.spice.profitmandi.dao.entity.user.User user = null;
1440
 
1441
        try {
1442
            dtrUser = userRepository.selectByEmailId(newEmail);
1443
        } catch (Exception e) {
1444
        }
1445
 
1446
        try {
1447
            user = userUserRepository.selectByEmailId(newEmail);
1448
        } catch (Exception e) {
1449
        }
1450
 
1451
        if (user != null || dtrUser != null) {
1452
            throw new ProfitMandiBusinessException("Email", newEmail, "Email already exist");
1453
        }
1454
        com.spice.profitmandi.dao.entity.user.User fofoUser = userUserRepository.selectById(fofoId);
1455
        String oldEmail = fofoUser.getEmailId();
1456
        LOGGER.info("old email {}", oldEmail);
1457
        User thisDtrUser = userRepository.selectByEmailId(oldEmail);
1458
 
1459
        fofoUser.setEmailId(newEmail);
1460
        thisDtrUser.setEmailId(newEmail);
1461
    }
1462
 
1463
 
32953 amit.gupta 1464
    //    @Override
32737 amit.gupta 1465
    @Cacheable(value = "getContactsByFofoId", cacheManager = "oneDayCacheManager")
33128 amit.gupta 1466
    public List<RetailerContact> getContactsByFofoId(int fofoId, boolean activeOnly) throws
1467
            ProfitMandiBusinessException {
32737 amit.gupta 1468
        List<RetailerContact> retailerContacts = retailerContactRepository.selectAllByRetailerId(fofoId, activeOnly);
1469
        com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
1470
        RetailerContact retailerContact = new RetailerContact();
1471
        retailerContact.setMobile(user.getMobileNumber());
1472
        retailerContact.setName(user.getName());
1473
        retailerContact.setActive(true);
1474
        retailerContact.setFofoId(fofoId);
1475
        retailerContacts.add(retailerContact);
1476
        return retailerContacts;
1477
    }
1478
 
1479
 
1480
    @Override
33128 amit.gupta 1481
    public Map<Integer, CustomRetailer> getFofoRetailersPaginated(boolean activeOnly, int offset,
33247 ranu 1482
                                                                  int limit, FofoType fofoType) throws ProfitMandiBusinessException {
30097 tejbeer 1483
 
31734 tejbeer 1484
        Stream<FofoStore> storeStream = fofoStoreRepository.selectByStatusFofoType(activeOnly, fofoType, offset, limit).stream();
30219 tejbeer 1485
 
31734 tejbeer 1486
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1487
        return this.getFofoRetailers(storeIds);
1488
    }
30219 tejbeer 1489
 
34813 aman 1490
    @Override
1491
    public Map<String, Object> computeIncomeMap(int fofoId, int yearMonth) {
1492
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1493
        LocalDateTime endOfMonth = startOfMonth.plusMonths(1);
1494
        YearMonth monthYear = YearMonth.now();
1495
 
1496
 
1497
        // 3) Fetch brand-wise data (same as original)
1498
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1499
                .selectLastMonthPendingIncomeByFofoId(fofoId, startOfMonth, endOfMonth);
1500
 
1501
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1502
                .selectLastMonthPurchaseInMarginByFofoId(fofoId, startOfMonth, endOfMonth);
1503
 
1504
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1505
                .selectFrontIncomeByBrand(fofoId, startOfMonth, endOfMonth);
1506
 
1507
        List<LastMonthCreditedIncomeModel> lastMonthSaleMargins = schemeInOutRepository
1508
                .selectLastMonthCreditedIncomeByFofoId(fofoId, startOfMonth, endOfMonth);
1509
 
1510
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository
1511
                .getTotalPayoutsByPartnerPeriod(
1512
                        YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()),
1513
                        fofoId, null, null);
1514
 
1515
        // 4) Convert to maps for brand-wise access
1516
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap =
1517
                lastMonthPendingIncomeModels.stream()
1518
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1519
 
1520
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap =
1521
                lastMonthPurchaseInMargins.stream()
1522
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1523
 
1524
        Map<String, LastMonthCreditedIncomeModel> lastMonthFrontEndIncomeMap =
1525
                lastMonthFrontEndIncomes.stream()
1526
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1527
 
1528
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap =
1529
                lastMonthSaleMargins.stream()
1530
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1531
 
1532
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream()
1533
                .collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand,
1534
                        Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1535
 
1536
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream()
1537
                .collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand,
1538
                        Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
1539
 
1540
        // 5) Get all unique brands
1541
        Set<String> brandSet = new HashSet<>();
1542
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1543
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1544
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1545
        brandSet.addAll(additionalPurchasePayout.keySet());
1546
        brandSet.addAll(additionSalePayout.keySet());
1547
        brandSet.addAll(lastMonthFrontEndIncomeMap.keySet());
1548
 
1549
        // 6) Calculate total amount per brand (same logic as original)
1550
        Map<String, Float> totalAmountMap = new HashMap<>();
1551
        brandSet.forEach(brand -> {
1552
            float total =
1553
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1554
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1555
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1556
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).floatValue()) +
1557
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).floatValue()) +
1558
                            (lastMonthFrontEndIncomeMap.get(brand) == null ? 0 : lastMonthFrontEndIncomeMap.get(brand).getAmount());
1559
            totalAmountMap.put(brand, total);
1560
        });
1561
 
1562
        // 7) Calculate aggregated totals
1563
        float totalIncome = totalAmountMap.values().stream()
1564
                .reduce(0f, Float::sum);
1565
 
1566
        float pendingIncome = lastMonthPendingIncomeMap.values().stream()
1567
                .map(LastMonthCreditedIncomeModel::getAmount)
1568
                .reduce(0f, Float::sum);
1569
 
1570
        float creditedIncome = totalIncome - pendingIncome;
1571
 
1572
        // 8) Build month labels
1573
        Map<Integer, String> monthValueMap = new HashMap<>();
1574
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MMM''uu");
1575
        for (int i = 0; i <= 5; i++) {
1576
            LocalDateTime m = LocalDateTime.now()
1577
                    .withDayOfMonth(1)
1578
                    .minusMonths(i);
1579
            monthValueMap.put(i, m.format(fmt));
1580
        }
1581
 
1582
        // 9) Assemble result with all brand-wise data
1583
        Map<String, Object> result = new HashMap<>();
1584
        result.put("totalIncome", totalIncome);
1585
        result.put("creditedIncome", creditedIncome);
1586
        result.put("pendingIncome", pendingIncome);
1587
        result.put("monthIndex", yearMonth);
1588
        result.put("monthValueMap", monthValueMap);
1589
 
1590
        // Include brand-wise data for detailed analysis
1591
        result.put("brandSet", brandSet);
1592
        result.put("totalAmountMap", totalAmountMap);
1593
        result.put("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1594
        result.put("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1595
        result.put("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1596
        result.put("additionalPurchasePayoutMap", additionalPurchasePayout);
1597
        result.put("additionalSalePayoutMap", additionSalePayout);
1598
        result.put("lastMonthFrontEndIncomeMap", lastMonthFrontEndIncomeMap);
1599
 
1600
        return result;
1601
    }
1602
 
22980 ashik.ali 1603
}