Subversion Repositories SmartDukaan

Rev

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