Subversion Repositories SmartDukaan

Rev

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