Subversion Repositories SmartDukaan

Rev

Rev 35425 | Rev 35896 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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