Subversion Repositories SmartDukaan

Rev

Rev 35394 | Rev 35425 | 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
 
931
            storeTimelineTatService.sendTrialStoreCreationMail(
932
                    fofoStore,
933
                    updateRetailerRequest
934
            );
935
 
936
            if (fofoStore.getActivationType() == ActivationType.ACTIVE
937
                    && fofoStore.getActiveTimeStamp() != null) {
938
 
939
                storeTimelineTatService.sendTrialActivationMail(
940
                        fofoStore,
941
                        updateRetailerRequest
942
                );
943
            }
35289 amit 944
        }
945
 
31734 tejbeer 946
        return fofoStore;
947
    }
23955 govind 948
 
31734 tejbeer 949
    @Override
33128 amit.gupta 950
    public FofoStore createFofoStoreCodeByUserId(int userId, String districtName, String
951
            stateName, UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
31734 tejbeer 952
        User user = userRepository.selectById(userId);
953
        // = userAccountRepository.selectRetailerIdByUserId(user.getId());
954
        UserAccount userAccounts = userAccountRepository.selectSaholicByUserId(user.getId());
955
        Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
956
        Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
957
        try {
958
            userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleFofo.getId());
959
        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
960
            throw new ProfitMandiBusinessException(ProfitMandiConstants.USER_ID, user.getId(), "USR_1013");
961
        }
962
        return this.createFofoStoreCodeByRetailerId(retailer.getId(), districtName, stateName, updateRetailerRequest);
23955 govind 963
 
31734 tejbeer 964
    }
23955 govind 965
 
31734 tejbeer 966
    @Override
967
    public List<DistrictMaster> getAllDistrictMaster(String stateName) {
968
        // StateInfo stateInfo = null;
969
        State stateInfo = null;
970
        try {
971
            // stateInfo = Utils.getStateInfo(stateName);
30525 tejbeer 972
 
31734 tejbeer 973
            stateInfo = stateRepository.selectByName(stateName);
974
        } catch (Exception e) {
975
            e.printStackTrace();
976
            // throw new ProfitMandiBusinessException();
977
        }
978
        return districtMasterRepository.selectByStateShortName(stateInfo.getShortName());
979
    }
22980 ashik.ali 980
 
31734 tejbeer 981
    @Override
34149 tejus.loha 982
    @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 983
    public Map<Integer, CustomRetailer> getFofoRetailers(List<Integer> fofoIds) throws ProfitMandiBusinessException {
35394 amit 984
        if (fofoIds == null || fofoIds.isEmpty()) {
985
            return new HashMap<>();
986
        }
987
 
31734 tejbeer 988
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
35394 amit 989
        Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
990
                .filter(x -> x.getAddressId() != null)
991
                .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.user.User::getAddressId, x -> x));
31734 tejbeer 992
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
35394 amit 993
 
994
        // Batch fetch all FofoStores to avoid N+1 queries
995
        Set<Integer> retailerIds = addresses.stream().map(Address::getRetaierId).collect(Collectors.toSet());
996
        Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(retailerIds))
997
                .stream().collect(Collectors.toMap(FofoStore::getId, fs -> fs));
998
 
999
        // Batch fetch all PrivateDealUsers to avoid N+1 queries
1000
        Map<Integer, PrivateDealUser> privateDealUserMap = privateDealUserRepository.selectByIds(new ArrayList<>(retailerIds))
1001
                .stream().collect(Collectors.toMap(PrivateDealUser::getId, pdu -> pdu));
1002
 
1003
        // Batch fetch all Counters to avoid N+1 queries
1004
        Set<Integer> counterIds = privateDealUserMap.values().stream()
1005
                .filter(pdu -> pdu.getCounterId() != null)
1006
                .map(PrivateDealUser::getCounterId)
1007
                .collect(Collectors.toSet());
1008
        Map<Integer, Counter> counterMap = counterIds.isEmpty() ? Collections.emptyMap()
1009
                : counterRepository.selectByIds(new ArrayList<>(counterIds))
1010
                        .stream().collect(Collectors.toMap(Counter::getId, c -> c));
1011
 
31734 tejbeer 1012
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
1013
        for (Address address : addresses) {
1014
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
35394 amit 1015
            FofoStore fs = fofoStoreMap.get(address.getRetaierId());
1016
            if (fs == null) {
31734 tejbeer 1017
                continue;
1018
            }
35394 amit 1019
 
1020
            CustomRetailer customRetailer = buildCustomRetailer(user, address, fs, privateDealUserMap, counterMap);
31734 tejbeer 1021
            customRetailersMap.put(customRetailer.getPartnerId(), customRetailer);
1022
        }
1023
        return customRetailersMap;
1024
    }
25295 amit.gupta 1025
 
35394 amit 1026
    /**
1027
     * Helper method to build CustomRetailer from fetched entities
1028
     */
1029
    private CustomRetailer buildCustomRetailer(com.spice.profitmandi.dao.entity.user.User user, Address address,
1030
                                                FofoStore fs, Map<Integer, PrivateDealUser> privateDealUserMap,
1031
                                                Map<Integer, Counter> counterMap) {
1032
        CustomRetailer customRetailer = new CustomRetailer();
1033
        customRetailer.setEmail(user.getEmailId());
1034
        customRetailer.setBusinessName(address.getName());
1035
        customRetailer.setMobileNumber(address.getPhoneNumber());
1036
        customRetailer.setCode(fs.getCode());
1037
        customRetailer.setAstId(fs.getAstId());
1038
        customRetailer.setActivationType(fs.getActivationType());
1039
        customRetailer.setCounterSize(fs.getCounterSize());
1040
        customRetailer.setCounterPotential(fs.getCounterPotential());
1041
        customRetailer.setWarehouseId(fs.getWarehouseId());
1042
        customRetailer.setPartnerId(fs.getId());
1043
        customRetailer.setFofoType(fs.getFofoType());
1044
        customRetailer.setCartId(user.getActiveCartId());
1045
 
1046
        // Get GST number from pre-fetched maps
1047
        PrivateDealUser pdu = privateDealUserMap.get(address.getRetaierId());
1048
        if (pdu != null && pdu.getCounterId() != null) {
1049
            Counter counter = counterMap.get(pdu.getCounterId());
1050
            customRetailer.setGstNumber(counter != null ? counter.getGstin() : null);
1051
        }
1052
 
1053
        CustomAddress customAddress = buildCustomAddress(address);
1054
        customRetailer.setAddress(customAddress);
1055
        customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + customRetailer.getCode() + "- " + customAddress.getCity());
1056
        return customRetailer;
1057
    }
1058
 
1059
    /**
1060
     * Helper method to build CustomAddress from Address entity
1061
     */
1062
    private CustomAddress buildCustomAddress(Address address) {
1063
        CustomAddress customAddress = new CustomAddress();
1064
        customAddress.setCity(address.getCity());
1065
        customAddress.setState(address.getState());
1066
        customAddress.setLine1(address.getLine1());
1067
        customAddress.setLine2(address.getLine2());
1068
        customAddress.setPinCode(address.getPinCode());
1069
        customAddress.setName(address.getName());
1070
        customAddress.setPhoneNumber(address.getPhoneNumber());
1071
        return customAddress;
1072
    }
1073
 
31734 tejbeer 1074
    @Override
1075
    @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
1076
    public CustomRetailer getFofoRetailer(int fofoId) throws ProfitMandiBusinessException {
1077
        com.spice.profitmandi.dao.entity.user.User saholicUser = userUserRepository.selectById(fofoId);
31862 tejbeer 1078
        User dtrUser = userRepository.selectByEmailId(saholicUser.getEmailId());
31734 tejbeer 1079
        FofoStore store = fofoStoreRepository.selectByRetailerId(fofoId);
35394 amit 1080
        Address address = addressRepository.selectById(saholicUser.getAddressId());
1081
 
31734 tejbeer 1082
        CustomRetailer customRetailer = new CustomRetailer();
1083
        customRetailer.setEmail(saholicUser.getEmailId());
1084
        customRetailer.setBusinessName(address.getName());
1085
        customRetailer.setMobileNumber(address.getPhoneNumber());
31862 tejbeer 1086
        customRetailer.setFirstName(dtrUser.getFirstName());
1087
        customRetailer.setLastName(dtrUser.getLastName());
35394 amit 1088
        customRetailer.setCartId(saholicUser.getActiveCartId());
1089
        customRetailer.setPartnerId(address.getRetaierId());
1090
        customRetailer.setCode(store.getCode());
1091
        customRetailer.setAstId(store.getAstId());
1092
        customRetailer.setActivationType(store.getActivationType());
1093
        customRetailer.setWarehouseId(store.getWarehouseId());
1094
 
1095
        // Get GST number
31734 tejbeer 1096
        try {
1097
            PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
35394 amit 1098
            if (pdu != null && pdu.getCounterId() != null) {
1099
                Counter counter = counterRepository.selectById(pdu.getCounterId());
1100
                customRetailer.setGstNumber(counter != null ? counter.getGstin() : null);
1101
            }
31734 tejbeer 1102
        } catch (Exception e) {
1103
            customRetailer.setGstNumber(null);
1104
        }
35394 amit 1105
 
1106
        // Reuse helper method for CustomAddress
1107
        CustomAddress customAddress = buildCustomAddress(address);
1108
        customRetailer.setAddress(customAddress);
31734 tejbeer 1109
        customRetailer.setDisplayName(address.getName() + " - " + address.getCity());
35394 amit 1110
 
31734 tejbeer 1111
        return customRetailer;
1112
    }
26125 amit.gupta 1113
 
31734 tejbeer 1114
    @Override
33247 ranu 1115
    public Map<Integer, CustomRetailer> getFofoRetailerUserId(List<Integer> fofoIds) throws ProfitMandiBusinessException {
35394 amit 1116
        if (fofoIds == null || fofoIds.isEmpty()) {
1117
            return new HashMap<>();
1118
        }
1119
 
31734 tejbeer 1120
        List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
35394 amit 1121
        Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
1122
                .filter(x -> x.getAddressId() != null)
1123
                .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.user.User::getAddressId, x -> x));
31734 tejbeer 1124
        List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
35394 amit 1125
 
1126
        // Batch fetch all retailerIds to userIds mapping to avoid N+1
1127
        Set<Integer> retailerIds = addresses.stream().map(Address::getRetaierId).collect(Collectors.toSet());
1128
        Map<Integer, Integer> retailerIdToUserIdMap = getUserIdRetailerIdMapReverse(retailerIds);
1129
 
1130
        // Batch fetch all PrivateDealUsers to avoid N+1 queries
1131
        Map<Integer, PrivateDealUser> privateDealUserMap = privateDealUserRepository.selectByIds(new ArrayList<>(retailerIds))
1132
                .stream().collect(Collectors.toMap(PrivateDealUser::getId, pdu -> pdu));
1133
 
1134
        // Batch fetch all Counters to avoid N+1 queries
1135
        Set<Integer> counterIds = privateDealUserMap.values().stream()
1136
                .filter(pdu -> pdu.getCounterId() != null)
1137
                .map(PrivateDealUser::getCounterId)
1138
                .collect(Collectors.toSet());
1139
        Map<Integer, Counter> counterMap = counterIds.isEmpty() ? Collections.emptyMap()
1140
                : counterRepository.selectByIds(new ArrayList<>(counterIds))
1141
                        .stream().collect(Collectors.toMap(Counter::getId, c -> c));
1142
 
31734 tejbeer 1143
        Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
1144
        for (Address address : addresses) {
1145
            com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
35394 amit 1146
            Integer userId = retailerIdToUserIdMap.get(user.getId());
1147
            if (userId == null) {
1148
                continue;
1149
            }
1150
 
31734 tejbeer 1151
            CustomRetailer customRetailer = new CustomRetailer();
1152
            customRetailer.setEmail(user.getEmailId());
1153
            customRetailer.setBusinessName(address.getName());
1154
            customRetailer.setMobileNumber(address.getPhoneNumber());
35394 amit 1155
            customRetailer.setCartId(user.getActiveCartId());
1156
            customRetailer.setPartnerId(address.getRetaierId());
1157
 
1158
            // Get GST number from pre-fetched maps
1159
            PrivateDealUser pdu = privateDealUserMap.get(address.getRetaierId());
1160
            if (pdu != null && pdu.getCounterId() != null) {
1161
                Counter counter = counterMap.get(pdu.getCounterId());
1162
                customRetailer.setGstNumber(counter != null ? counter.getGstin() : null);
31734 tejbeer 1163
            }
35394 amit 1164
 
1165
            CustomAddress customAddress = buildCustomAddress(address);
1166
            customRetailer.setAddress(customAddress);
1167
            customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + customAddress.getCity());
31734 tejbeer 1168
            customRetailersMap.put(userId, customRetailer);
1169
        }
1170
        return customRetailersMap;
1171
    }
25295 amit.gupta 1172
 
35394 amit 1173
    /**
1174
     * Helper method to get retailerId to userId mapping
1175
     */
1176
    private Map<Integer, Integer> getUserIdRetailerIdMapReverse(Set<Integer> retailerIds) {
1177
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1178
        return userAccounts.stream().collect(Collectors.toMap(UserAccount::getAccountKey, UserAccount::getUserId));
1179
    }
1180
 
31734 tejbeer 1181
    @Override
33247 ranu 1182
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap() throws ProfitMandiBusinessException {
31734 tejbeer 1183
        Role roleFofo = null;
1184
        try {
1185
            roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
1186
        } catch (ProfitMandiBusinessException e) {
1187
            // TODO Auto-generated catch block
1188
            e.printStackTrace();
1189
        }
1190
        Role roleRetailer = null;
1191
        try {
1192
            roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
1193
        } catch (ProfitMandiBusinessException e) {
1194
            // TODO Auto-generated catch block
1195
            e.printStackTrace();
1196
        }
1197
        Set<Integer> roleIds = new HashSet<>();
1198
        roleIds.add(roleFofo.getId());
1199
        roleIds.add(roleRetailer.getId());
1200
        List<Integer> userIds = userRoleRepository.selectUserIdsByRoleIds(roleIds);
1201
        List<User> users = userRepository.selectAllByIds(new HashSet<>(userIds));
1202
        Map<Integer, Integer> userIdRetailerIdMap = this.getUserIdRetailerIdMap(userIds);
1203
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1204
        for (User user : users) {
1205
            retailerIdEmailIdMap.put(userIdRetailerIdMap.get(user.getId()), user.getEmailId());
1206
        }
1207
        return retailerIdEmailIdMap;
1208
    }
23955 govind 1209
 
31734 tejbeer 1210
    private Map<Integer, Integer> getUserIdRetailerIdMap(List<Integer> userIds) {
1211
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByUserIds(new HashSet<>(userIds));
1212
        Map<Integer, Integer> userIdRetailerIdMap = new HashMap<>();
1213
        for (UserAccount userAccount : userAccounts) {
1214
            userIdRetailerIdMap.put(userAccount.getUserId(), userAccount.getAccountKey());
1215
        }
1216
        return userIdRetailerIdMap;
1217
    }
25295 amit.gupta 1218
 
33247 ranu 1219
    private Map<Integer, String> getUserIdEmailIdMap(Set<Integer> userIds) throws ProfitMandiBusinessException {
31734 tejbeer 1220
        List<User> users = userRepository.selectAllByIds(userIds);
1221
        Map<Integer, String> userIdEmailIdMap = new HashMap<>();
1222
        for (User user : users) {
1223
            userIdEmailIdMap.put(user.getId(), user.getEmailId());
1224
        }
1225
        return userIdEmailIdMap;
1226
    }
23509 amit.gupta 1227
 
31734 tejbeer 1228
    @Override
33247 ranu 1229
    public Map<Integer, String> getAllFofoRetailerIdEmailIdMap(Set<Integer> retailerIds) throws ProfitMandiBusinessException {
31734 tejbeer 1230
        List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1231
        Set<Integer> userIds = new HashSet<>();
1232
        for (UserAccount userAccount : userAccounts) {
1233
            userIds.add(userAccount.getUserId());
1234
        }
1235
        Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1236
        Map<Integer, String> userIdEmailIdMap = this.getUserIdEmailIdMap(userIds);
1237
        for (UserAccount userAccount : userAccounts) {
1238
            retailerIdEmailIdMap.put(userAccount.getAccountKey(), userIdEmailIdMap.get(userAccount.getUserId()));
1239
        }
1240
        return retailerIdEmailIdMap;
1241
    }
25295 amit.gupta 1242
 
31734 tejbeer 1243
    @Override
33247 ranu 1244
    public Map<Integer, String> getAllFofoRetailerIdNameMap(List<Integer> storeIds) throws ProfitMandiBusinessException {
31734 tejbeer 1245
        Map<Integer, CustomRetailer> retailersMap = this.getFofoRetailers(storeIds);
1246
        Map<Integer, String> retailerIdNameMap = new HashMap<>();
1247
        for (Map.Entry<Integer, CustomRetailer> entry : retailersMap.entrySet()) {
1248
            retailerIdNameMap.put(entry.getKey(), entry.getValue().getBusinessName() + "-" + entry.getValue().getAddress().getCity());
1249
        }
1250
        return retailerIdNameMap;
1251
    }
24168 amit.gupta 1252
 
31734 tejbeer 1253
    @Override
1254
    @Cacheable(value = "FofoRetailerIdNameMap", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1255
    public Map<Integer, String> getAllFofoRetailerIdNameMap() throws ProfitMandiBusinessException {
31734 tejbeer 1256
        List<FofoStore> stores = fofoStoreRepository.selectAll();
1257
        List<Integer> storeIds = stores.stream().map(x -> x.getId()).collect(Collectors.toList());
1258
        return this.getAllFofoRetailerIdNameMap(storeIds);
1259
    }
24349 amit.gupta 1260
 
31734 tejbeer 1261
    @Override
33247 ranu 1262
    public List<MapWrapper<Integer, String>> getAllFofoRetailerIdNameList() throws ProfitMandiBusinessException {
31734 tejbeer 1263
        List<MapWrapper<Integer, String>> mapWrappers = new ArrayList<>();
1264
        // TODO Auto-generated method stub
1265
        Map<Integer, String> fofoIdNameMap = this.getAllFofoRetailerIdNameMap();
1266
        fofoIdNameMap.forEach((fofoId, name) -> {
1267
            MapWrapper<Integer, String> idWrapper = new MapWrapper<>();
1268
            idWrapper.setKey(fofoId);
1269
            idWrapper.setValue(name);
1270
            mapWrappers.add(idWrapper);
1271
        });
1272
        return mapWrappers;
1273
    }
24349 amit.gupta 1274
 
31734 tejbeer 1275
    @Override
1276
    @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1277
    public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly) throws ProfitMandiBusinessException {
35394 amit 1278
        Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream()
1279
                .filter(fs -> fs.getFofoType().equals(FofoType.FRANCHISE));
31734 tejbeer 1280
        if (activeOnly) {
35394 amit 1281
            storeStream = storeStream.filter(FofoStore::isActive);
31734 tejbeer 1282
        }
35394 amit 1283
        List<Integer> storeIds = storeStream.map(FofoStore::getId).collect(Collectors.toList());
31734 tejbeer 1284
        return this.getFofoRetailers(storeIds);
1285
    }
25295 amit.gupta 1286
 
31734 tejbeer 1287
    @Override
33367 ranu 1288
    @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
1289
    public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly, String pinCode) throws ProfitMandiBusinessException {
1290
        List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pinCode);
1291
        List<Integer> storeIds = new ArrayList<>();
35394 amit 1292
        if (!pincodePartners.isEmpty()) {
1293
            List<Integer> fofoIds = pincodePartners.stream().map(PincodePartner::getFofoId).collect(Collectors.toList());
33367 ranu 1294
            List<FofoStore> fofoStores = fofoStoreRepository.selectActivePartnersByRetailerIds(fofoIds);
35394 amit 1295
            storeIds = fofoStores.stream().map(FofoStore::getId).collect(Collectors.toList());
33367 ranu 1296
        }
1297
        return this.getFofoRetailers(storeIds);
1298
    }
1299
 
1300
    @Override
31734 tejbeer 1301
    @Cacheable(value = "allFofoRetailers", cacheManager = "thirtyMinsTimeOutCacheManager")
33247 ranu 1302
    public Map<Integer, CustomRetailer> getAllFofoRetailers() throws ProfitMandiBusinessException {
35394 amit 1303
        List<Integer> storeIds = fofoStoreRepository.selectAll().stream()
1304
                .map(FofoStore::getId)
1305
                .collect(Collectors.toList());
31734 tejbeer 1306
        return this.getFofoRetailers(storeIds);
1307
    }
27861 tejbeer 1308
 
31734 tejbeer 1309
    @Override
34619 ranu 1310
    @Cacheable(value = "allFofoRetailersInternalFalse", cacheManager = "thirtyMinsTimeOutCacheManager")
1311
    public Map<Integer, CustomRetailer> getAllFofoRetailersInternalFalse() throws ProfitMandiBusinessException {
35394 amit 1312
        List<Integer> storeIds = fofoStoreRepository.selectAll().stream()
1313
                .filter(fs -> fs.getFofoType().equals(FofoType.FRANCHISE))
1314
                .map(FofoStore::getId)
1315
                .collect(Collectors.toList());
34619 ranu 1316
        return this.getFofoRetailers(storeIds);
1317
    }
1318
 
1319
    @Override
33128 amit.gupta 1320
    public LoginRequestResponseModel registerWebUser(LoginRequestResponseModel loginRequestModel) throws
1321
            ProfitMandiBusinessException {
26522 amit.gupta 1322
 
31734 tejbeer 1323
        com.spice.profitmandi.dao.entity.user.User saholicUser = this.createSaholicUser(loginRequestModel);
1324
        loginRequestModel.setUserId(saholicUser.getId());
26522 amit.gupta 1325
 
31734 tejbeer 1326
        this.createRetailerAddress(loginRequestModel);
26522 amit.gupta 1327
 
31734 tejbeer 1328
        this.createPrivateDealUser(loginRequestModel);
1329
        this.updateSaholicUser(saholicUser.getId(), loginRequestModel.getBusinessAddress().getId());
26522 amit.gupta 1330
 
31734 tejbeer 1331
        return loginRequestModel;
26522 amit.gupta 1332
 
31734 tejbeer 1333
    }
26522 amit.gupta 1334
 
31734 tejbeer 1335
    private void createPrivateDealUser(LoginRequestResponseModel loginRequestModel) {
26522 amit.gupta 1336
 
31734 tejbeer 1337
        Integer counterId = this.createCounter(loginRequestModel.getEmail(), loginRequestModel.getGstNumber(), loginRequestModel.getBusinessAddress().getPhoneNumber(), loginRequestModel.getBusinessAddress().getName(), loginRequestModel.getBusinessAddress().getId());
1338
        try {
1339
            this.createPrivateDealUser(loginRequestModel.getUserId(), counterId, false);
1340
        } catch (Exception e) {
1341
            LOGGER.error("ERROR : ", e);
1342
        }
26522 amit.gupta 1343
 
31734 tejbeer 1344
        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
1345
        privateDealUserAddressMapping.setUserId(loginRequestModel.getUserId());
1346
        privateDealUserAddressMapping.setAddressId(loginRequestModel.getBusinessAddress().getId());
1347
        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
26522 amit.gupta 1348
 
31734 tejbeer 1349
    }
26522 amit.gupta 1350
 
33128 amit.gupta 1351
    private void createRetailerAddress(LoginRequestResponseModel loginRequestResponseModel) throws
1352
            ProfitMandiBusinessException {
31734 tejbeer 1353
        Address businessAddress = loginRequestResponseModel.getBusinessAddress();
1354
        businessAddress.setRetaierId(loginRequestResponseModel.getUserId());
1355
        addressRepository.persist(businessAddress);
1356
    }
26536 amit.gupta 1357
 
31734 tejbeer 1358
    private String getHash256(String originalString) {
1359
        String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
1360
        LOGGER.info("Hash String {}", hashString);
1361
        return hashString;
1362
    }
26533 amit.gupta 1363
 
31734 tejbeer 1364
    @Override
1365
    @Cacheable(value = "fofoIdUrl", cacheManager = "thirtyMinsTimeOutCacheManager")
1366
    public Map<Integer, String> getAllFofoRetailerIdUrlMap() {
1367
        Map<Integer, String> fofoRetailerUrlMap = new HashMap<>();
35394 amit 1368
        List<FofoStore> stores = fofoStoreRepository.selectAll().stream()
1369
                .filter(FofoStore::isActive)
1370
                .collect(Collectors.toList());
1371
 
1372
        // Batch fetch all district masters to avoid N+1 queries
1373
        List<DistrictMaster> allDistrictMasters = districtMasterRepository.selectAll();
1374
        Map<String, DistrictMaster> districtMasterMap = allDistrictMasters.stream()
1375
                .collect(Collectors.toMap(
1376
                        dm -> dm.getStateShortName() + "_" + dm.getShortName(),
1377
                        dm -> dm,
1378
                        (existing, replacement) -> existing));
1379
 
1380
        // Get fallback district master
1381
        DistrictMaster fallbackDistrict = districtMasterMap.get("HR_FB");
1382
 
31734 tejbeer 1383
        for (FofoStore store : stores) {
35394 amit 1384
            String codeWithoutDigits = store.getCode().replaceAll("\\d+", "");
1385
            if (codeWithoutDigits.length() < 3) {
1386
                LOGGER.warn("Invalid store code format: {}", store.getCode());
1387
                continue;
1388
            }
1389
            String stateShortName = codeWithoutDigits.substring(0, 2);
1390
            String districtShortName = codeWithoutDigits.substring(2);
1391
 
1392
            // Use pre-fetched map instead of N+1 query
1393
            String key = stateShortName + "_" + districtShortName;
1394
            DistrictMaster districtMaster = districtMasterMap.getOrDefault(key, fallbackDistrict);
1395
 
31734 tejbeer 1396
            if (districtMaster == null) {
35394 amit 1397
                LOGGER.warn("No district master found for key: {} and no fallback available", key);
1398
                continue;
31734 tejbeer 1399
            }
35394 amit 1400
 
1401
            String urlString = districtMaster.getStateShortName() + "/" +
1402
                    Utils.getHyphenatedString(districtMaster.getName()) + "/" + store.getCode();
31734 tejbeer 1403
            fofoRetailerUrlMap.put(store.getId(), urlString.toLowerCase());
1404
        }
1405
        return fofoRetailerUrlMap;
1406
    }
26533 amit.gupta 1407
 
31734 tejbeer 1408
    @Override
1409
    @Cacheable(value = "storeCodeRetailerMap", cacheManager = "thirtyMinsTimeOutCacheManager")
1410
    public Map<String, Integer> getStoreCodeRetailerMap() {
1411
        Map<Integer, String> map = this.getAllFofoRetailerIdUrlMap();
1412
        Map<String, Integer> returnMap = map.entrySet().stream().collect(Collectors.toMap(x -> {
1413
            String[] splitString = x.getValue().split("/");
1414
            return splitString[splitString.length - 1];
1415
        }, x -> x.getKey()));
1416
        LOGGER.info("returnMap {}", returnMap);
1417
        return returnMap;
1418
    }
27877 amit.gupta 1419
 
1420
 
31734 tejbeer 1421
    @Override
32668 raveendra. 1422
    public User getEmail() {
1423
        return null;
1424
    }
1425
 
1426
    @Override
1427
    public void update(com.spice.profitmandi.dao.entity.user.User user) {
1428
    }
1429
 
1430
    @Override
1431
    public void updateRetailerEmail(int fofoId, String newEmail) throws ProfitMandiBusinessException {
1432
        User dtrUser = null;
1433
        com.spice.profitmandi.dao.entity.user.User user = null;
1434
 
1435
        try {
1436
            dtrUser = userRepository.selectByEmailId(newEmail);
1437
        } catch (Exception e) {
1438
        }
1439
 
1440
        try {
1441
            user = userUserRepository.selectByEmailId(newEmail);
1442
        } catch (Exception e) {
1443
        }
1444
 
1445
        if (user != null || dtrUser != null) {
1446
            throw new ProfitMandiBusinessException("Email", newEmail, "Email already exist");
1447
        }
1448
        com.spice.profitmandi.dao.entity.user.User fofoUser = userUserRepository.selectById(fofoId);
1449
        String oldEmail = fofoUser.getEmailId();
1450
        LOGGER.info("old email {}", oldEmail);
1451
        User thisDtrUser = userRepository.selectByEmailId(oldEmail);
1452
 
1453
        fofoUser.setEmailId(newEmail);
1454
        thisDtrUser.setEmailId(newEmail);
1455
    }
1456
 
1457
 
32953 amit.gupta 1458
    //    @Override
32737 amit.gupta 1459
    @Cacheable(value = "getContactsByFofoId", cacheManager = "oneDayCacheManager")
33128 amit.gupta 1460
    public List<RetailerContact> getContactsByFofoId(int fofoId, boolean activeOnly) throws
1461
            ProfitMandiBusinessException {
32737 amit.gupta 1462
        List<RetailerContact> retailerContacts = retailerContactRepository.selectAllByRetailerId(fofoId, activeOnly);
1463
        com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(fofoId);
1464
        RetailerContact retailerContact = new RetailerContact();
1465
        retailerContact.setMobile(user.getMobileNumber());
1466
        retailerContact.setName(user.getName());
1467
        retailerContact.setActive(true);
1468
        retailerContact.setFofoId(fofoId);
1469
        retailerContacts.add(retailerContact);
1470
        return retailerContacts;
1471
    }
1472
 
1473
 
1474
    @Override
33128 amit.gupta 1475
    public Map<Integer, CustomRetailer> getFofoRetailersPaginated(boolean activeOnly, int offset,
33247 ranu 1476
                                                                  int limit, FofoType fofoType) throws ProfitMandiBusinessException {
30097 tejbeer 1477
 
31734 tejbeer 1478
        Stream<FofoStore> storeStream = fofoStoreRepository.selectByStatusFofoType(activeOnly, fofoType, offset, limit).stream();
30219 tejbeer 1479
 
31734 tejbeer 1480
        List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1481
        return this.getFofoRetailers(storeIds);
1482
    }
30219 tejbeer 1483
 
34813 aman 1484
    @Override
1485
    public Map<String, Object> computeIncomeMap(int fofoId, int yearMonth) {
1486
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1487
        LocalDateTime endOfMonth = startOfMonth.plusMonths(1);
1488
        YearMonth monthYear = YearMonth.now();
1489
 
1490
 
1491
        // 3) Fetch brand-wise data (same as original)
1492
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1493
                .selectLastMonthPendingIncomeByFofoId(fofoId, startOfMonth, endOfMonth);
1494
 
1495
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1496
                .selectLastMonthPurchaseInMarginByFofoId(fofoId, startOfMonth, endOfMonth);
1497
 
1498
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1499
                .selectFrontIncomeByBrand(fofoId, startOfMonth, endOfMonth);
1500
 
1501
        List<LastMonthCreditedIncomeModel> lastMonthSaleMargins = schemeInOutRepository
1502
                .selectLastMonthCreditedIncomeByFofoId(fofoId, startOfMonth, endOfMonth);
1503
 
1504
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository
1505
                .getTotalPayoutsByPartnerPeriod(
1506
                        YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()),
1507
                        fofoId, null, null);
1508
 
1509
        // 4) Convert to maps for brand-wise access
1510
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap =
1511
                lastMonthPendingIncomeModels.stream()
1512
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1513
 
1514
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap =
1515
                lastMonthPurchaseInMargins.stream()
1516
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1517
 
1518
        Map<String, LastMonthCreditedIncomeModel> lastMonthFrontEndIncomeMap =
1519
                lastMonthFrontEndIncomes.stream()
1520
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1521
 
1522
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap =
1523
                lastMonthSaleMargins.stream()
1524
                        .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1525
 
1526
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream()
1527
                .collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand,
1528
                        Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1529
 
1530
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream()
1531
                .collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand,
1532
                        Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
1533
 
1534
        // 5) Get all unique brands
1535
        Set<String> brandSet = new HashSet<>();
1536
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1537
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1538
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1539
        brandSet.addAll(additionalPurchasePayout.keySet());
1540
        brandSet.addAll(additionSalePayout.keySet());
1541
        brandSet.addAll(lastMonthFrontEndIncomeMap.keySet());
1542
 
1543
        // 6) Calculate total amount per brand (same logic as original)
1544
        Map<String, Float> totalAmountMap = new HashMap<>();
1545
        brandSet.forEach(brand -> {
1546
            float total =
1547
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1548
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1549
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1550
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).floatValue()) +
1551
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).floatValue()) +
1552
                            (lastMonthFrontEndIncomeMap.get(brand) == null ? 0 : lastMonthFrontEndIncomeMap.get(brand).getAmount());
1553
            totalAmountMap.put(brand, total);
1554
        });
1555
 
1556
        // 7) Calculate aggregated totals
1557
        float totalIncome = totalAmountMap.values().stream()
1558
                .reduce(0f, Float::sum);
1559
 
1560
        float pendingIncome = lastMonthPendingIncomeMap.values().stream()
1561
                .map(LastMonthCreditedIncomeModel::getAmount)
1562
                .reduce(0f, Float::sum);
1563
 
1564
        float creditedIncome = totalIncome - pendingIncome;
1565
 
1566
        // 8) Build month labels
1567
        Map<Integer, String> monthValueMap = new HashMap<>();
1568
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MMM''uu");
1569
        for (int i = 0; i <= 5; i++) {
1570
            LocalDateTime m = LocalDateTime.now()
1571
                    .withDayOfMonth(1)
1572
                    .minusMonths(i);
1573
            monthValueMap.put(i, m.format(fmt));
1574
        }
1575
 
1576
        // 9) Assemble result with all brand-wise data
1577
        Map<String, Object> result = new HashMap<>();
1578
        result.put("totalIncome", totalIncome);
1579
        result.put("creditedIncome", creditedIncome);
1580
        result.put("pendingIncome", pendingIncome);
1581
        result.put("monthIndex", yearMonth);
1582
        result.put("monthValueMap", monthValueMap);
1583
 
1584
        // Include brand-wise data for detailed analysis
1585
        result.put("brandSet", brandSet);
1586
        result.put("totalAmountMap", totalAmountMap);
1587
        result.put("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1588
        result.put("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1589
        result.put("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1590
        result.put("additionalPurchasePayoutMap", additionalPurchasePayout);
1591
        result.put("additionalSalePayoutMap", additionSalePayout);
1592
        result.put("lastMonthFrontEndIncomeMap", lastMonthFrontEndIncomeMap);
1593
 
1594
        return result;
1595
    }
1596
 
22980 ashik.ali 1597
}