Subversion Repositories SmartDukaan

Rev

Rev 36439 | Details | Compare with Previous | Last modification | View Log | RSS feed

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