Subversion Repositories SmartDukaan

Rev

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