Subversion Repositories SmartDukaan

Rev

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

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