Subversion Repositories SmartDukaan

Rev

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