Subversion Repositories SmartDukaan

Rev

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