Subversion Repositories SmartDukaan

Rev

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

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