Subversion Repositories SmartDukaan

Rev

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