Subversion Repositories SmartDukaan

Rev

Rev 29605 | Rev 30097 | 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
 
26528 amit.gupta 3
import com.google.common.hash.Hashing;
22980 ashik.ali 4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30017 amit.gupta 5
import com.spice.profitmandi.common.model.*;
23329 ashik.ali 6
import com.spice.profitmandi.common.util.StringUtils;
7
import com.spice.profitmandi.common.util.Utils;
22980 ashik.ali 8
import com.spice.profitmandi.dao.entity.dtr.User;
30017 amit.gupta 9
import com.spice.profitmandi.dao.entity.dtr.*;
10
import com.spice.profitmandi.dao.entity.fofo.*;
24349 amit.gupta 11
import com.spice.profitmandi.dao.entity.inventory.State;
30017 amit.gupta 12
import com.spice.profitmandi.dao.entity.user.*;
23063 ashik.ali 13
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
23106 ashik.ali 14
import com.spice.profitmandi.dao.enumuration.dtr.RetailerType;
23136 ashik.ali 15
import com.spice.profitmandi.dao.enumuration.dtr.RoleType;
23365 ashik.ali 16
import com.spice.profitmandi.dao.enumuration.fofo.PaymentOptionType;
29042 tejbeer 17
import com.spice.profitmandi.dao.enumuration.transaction.PartnerVerificationApprovalStatus;
22980 ashik.ali 18
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
30017 amit.gupta 19
import com.spice.profitmandi.dao.repository.dtr.*;
23365 ashik.ali 20
import com.spice.profitmandi.dao.repository.fofo.FofoPartnerPaymentOptionRepository;
21
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
24349 amit.gupta 22
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
30017 amit.gupta 23
import com.spice.profitmandi.dao.repository.user.*;
27877 amit.gupta 24
import com.spice.profitmandi.service.offers.PartnerCriteria;
23329 ashik.ali 25
import in.shop2020.model.v1.inventory.StateInfo;
23043 ashik.ali 26
import in.shop2020.model.v1.user.CartStatus;
30017 amit.gupta 27
import org.apache.logging.log4j.LogManager;
28
import org.apache.logging.log4j.Logger;
29
import org.springframework.beans.factory.annotation.Autowired;
30
import org.springframework.beans.factory.annotation.Qualifier;
31
import org.springframework.cache.annotation.Cacheable;
32
import org.springframework.stereotype.Component;
23043 ashik.ali 33
 
30017 amit.gupta 34
import java.nio.charset.StandardCharsets;
35
import java.time.LocalDateTime;
36
import java.util.*;
37
import java.util.function.Function;
38
import java.util.stream.Collectors;
39
import java.util.stream.Stream;
40
 
22980 ashik.ali 41
@Component
42
public class RetailerServiceImpl implements RetailerService {
23955 govind 43
 
23568 govind 44
	private static final Logger LOGGER = LogManager.getLogger(RetailerServiceImpl.class);
23955 govind 45
 
22980 ashik.ali 46
	@Autowired
47
	private RetailerRepository retailerRepository;
23955 govind 48
 
22980 ashik.ali 49
	@Autowired
28024 tejbeer 50
	private RetailerBlockBrandsRepository retailerBlockBrandsRepository;
51
 
52
	@Autowired
22980 ashik.ali 53
	private UserAccountRepository userAccountRepository;
23955 govind 54
 
22980 ashik.ali 55
	@Autowired
28024 tejbeer 56
	private Mongo mongoClient;
57
 
58
	@Autowired
22980 ashik.ali 59
	private UserRepository userRepository;
23955 govind 60
 
22980 ashik.ali 61
	@Autowired
23043 ashik.ali 62
	private CartRepository cartRepository;
23955 govind 63
 
23043 ashik.ali 64
	@Autowired
22980 ashik.ali 65
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
23955 govind 66
 
22980 ashik.ali 67
	@Autowired
68
	private AddressRepository addressRepository;
23955 govind 69
 
22980 ashik.ali 70
	@Autowired
71
	private ShopRepository shopRepository;
23955 govind 72
 
22980 ashik.ali 73
	@Autowired
74
	private ShopAddressRepository shopAddressRepository;
23955 govind 75
 
22980 ashik.ali 76
	@Autowired
77
	private UserRoleRepository userRoleRepository;
23955 govind 78
 
22980 ashik.ali 79
	@Autowired
80
	private DocumentRepository documentRepository;
23955 govind 81
 
23043 ashik.ali 82
	@Autowired
23329 ashik.ali 83
	private PrivateDealUserRepository privateDealUserRepository;
23955 govind 84
 
23329 ashik.ali 85
	@Autowired
86
	private PrivateDealUserAddressMappingRepository privateDealUserAddressMappingRepository;
23955 govind 87
 
23329 ashik.ali 88
	@Autowired
89
	private CounterRepository counterRepository;
25295 amit.gupta 90
 
24349 amit.gupta 91
	@Autowired
92
	private StateRepository stateRepository;
23955 govind 93
 
23329 ashik.ali 94
	@Autowired
23043 ashik.ali 95
	@Qualifier("userUserRepository")
96
	private com.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;
23955 govind 97
 
23329 ashik.ali 98
	@Autowired
99
	private DistrictMasterRepository districtMasterRepository;
23955 govind 100
 
23329 ashik.ali 101
	@Autowired
102
	private FofoStoreRepository fofoStoreRepository;
23955 govind 103
 
23329 ashik.ali 104
	@Autowired
23365 ashik.ali 105
	private PaymentOptionRepository paymentOptionRepository;
23955 govind 106
 
23365 ashik.ali 107
	@Autowired
108
	private FofoPartnerPaymentOptionRepository fofoPartnerPaymentOptionRepository;
23955 govind 109
 
23842 ashik.ali 110
	@Autowired
111
	private RoleRepository roleRepository;
23955 govind 112
 
28908 tejbeer 113
	@Autowired
114
	private StoreTimelineTatService storeTimelineTatService;
115
 
116
	@Autowired
117
	private PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
118
 
29042 tejbeer 119
	@Autowired
120
	private PartnerOnboardingVerificationRepository partnerOnboardingVerificationRepository;
121
 
22980 ashik.ali 122
	@Override
123
	public Map<String, Object> getByEmailIdOrMobileNumber(String emailIdOrMobileNumber)
124
			throws ProfitMandiBusinessException {
23202 ashik.ali 125
		User user = null;
28024 tejbeer 126
		int fofoId = Utils.SYSTEM_PARTNER_ID;
127
 
23955 govind 128
		try {
23202 ashik.ali 129
			user = userRepository.selectByEmailIdOrMobileNumber(emailIdOrMobileNumber);
23955 govind 130
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
131
 
23202 ashik.ali 132
		}
23955 govind 133
		if (user == null) {
134
			try {
23329 ashik.ali 135
				user = userRepository.selectBySecondryEmailId(emailIdOrMobileNumber);
23955 govind 136
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
137
 
23329 ashik.ali 138
			}
23202 ashik.ali 139
		}
22980 ashik.ali 140
		Map<String, Object> map = new HashMap<>();
25295 amit.gupta 141
		map.put("stateNames", stateRepository.selectAll().stream().map(x -> x.getName()).collect(Collectors.toList()));
23955 govind 142
 
143
		if (user != null) {
144
 
23329 ashik.ali 145
			List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
23955 govind 146
 
23781 ashik.ali 147
			Role role = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 148
 
23329 ashik.ali 149
			map.put("userRoles", userRoles);
150
			map.put("user", user);
23955 govind 151
			// map.put("retailer", retailer);
23781 ashik.ali 152
			map.put("fofoRole", this.containsRoleType(userRoles, role.getId()));
23955 govind 153
 
23329 ashik.ali 154
			map.put("userRoleNames", this.toString(userRoles));
23955 govind 155
			try {
23329 ashik.ali 156
				int retailerId = userAccountRepository.selectRetailerIdByUserId(user.getId());
157
				Retailer retailer = retailerRepository.selectById(retailerId);
23955 govind 158
 
23329 ashik.ali 159
				map.put("retailer", retailer);
23955 govind 160
 
28024 tejbeer 161
				List<String> retailerBlockBrands = null;
162
				Set<String> brands = null;
163
				if (retailer.getId() != fofoId) {
164
					brands = mongoClient.getMongoBrands(retailer.getId(), null, 3).stream()
165
							.map(x -> (String) x.get("name")).collect(Collectors.toSet());
28189 tejbeer 166
					retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream()
167
							.map(x -> x.getBlockBrands()).collect(Collectors.toList());
168
 
28024 tejbeer 169
					LOGGER.info("loginDetailsFofoId" + retailer.getId());
170
				} else {
171
					LOGGER.info("fofoId" + fofoId);
172
					brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
173
							.collect(Collectors.toSet());
174
				}
175
				map.put("brands", brands);
176
				map.put("retailerBlockBrands", retailerBlockBrands);
23955 govind 177
				if (this.containsRoleType(userRoles, role.getId())) {
178
					try {
23329 ashik.ali 179
						FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
180
						map.put("fofoStore", fofoStore);
23955 govind 181
						// map.put("counterSize", fofoStore.getCounterSize().toString());
182
						// LOGGER.info("fofoStore" + fofoStore);
183
					} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 184
						LOGGER.error("FofoStore code not found");
185
					}
186
				}
23955 govind 187
 
188
				try {
23329 ashik.ali 189
					PrivateDealUser privateDealUser = privateDealUserRepository.selectById(retailer.getId());
23955 govind 190
					if (privateDealUser.getCounterId() != null) {
23329 ashik.ali 191
						Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
192
						map.put("gstNumber", counter.getGstin());
23955 govind 193
						// LOGGER.info("gstNumber" + counter.getGstin());
23329 ashik.ali 194
					}
23955 govind 195
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 196
					LOGGER.error("PrivateDealUser not found");
197
				}
23955 govind 198
				try {
199
					int retailerAddressId = retailerRegisteredAddressRepository
200
							.selectAddressIdByRetailerId(retailer.getId());
23329 ashik.ali 201
					Address retailerAddress = addressRepository.selectById(retailerAddressId);
202
					map.put("retailerAddress", retailerAddress);
24349 amit.gupta 203
					State state = stateRepository.selectByName(retailerAddress.getState());
23955 govind 204
					// LOGGER.info("retailerAddress.." + retailerAddress);
205
					List<DistrictMaster> districtMasters = districtMasterRepository
24349 amit.gupta 206
							.selectByStateShortName(state.getShortName());
23329 ashik.ali 207
					map.put("districtMasters", districtMasters);
23955 govind 208
					// LOGGER.info("districtMasters" + districtMasters);
23329 ashik.ali 209
					List<Shop> shops = shopRepository.selectByRetailerId(retailer.getId());
23955 govind 210
					map.put("shops", shops);
23329 ashik.ali 211
					this.addAddress(shops);
23955 govind 212
					// LOGGER.info("shops" + shops);
213
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 214
					LOGGER.error("Retailer Registered Address not found");
215
				}
23955 govind 216
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 217
				LOGGER.error("Retailer not found in user_account");
23043 ashik.ali 218
			}
219
		}
23955 govind 220
 
22980 ashik.ali 221
		return map;
222
	}
23955 govind 223
 
224
	private boolean containsRoleType(List<UserRole> userRoles, int roleId) {
225
		for (UserRole userRole : userRoles) {
226
			if (userRole.getRoleId() == roleId) {
23329 ashik.ali 227
				return true;
228
			}
229
		}
230
		return false;
231
	}
23955 govind 232
 
233
	private List<UserRole> addRole(List<UserRole> userRoles, int userId, int roleId) {
234
		if (userRoles == null) {
23329 ashik.ali 235
			userRoles = new ArrayList<>();
236
		}
23955 govind 237
		if (!this.containsRoleType(userRoles, roleId)) {
23329 ashik.ali 238
			UserRole userRole = new UserRole();
239
			userRole.setUserId(userId);
23781 ashik.ali 240
			userRole.setRoleId(roleId);
23329 ashik.ali 241
			try {
242
				userRoleRepository.persist(userRole);
243
			} catch (ProfitMandiBusinessException e) {
244
				LOGGER.error("UserRole is already exist");
245
			}
246
			userRoles.add(userRole);
247
		}
248
		return userRoles;
23955 govind 249
 
23329 ashik.ali 250
	}
23955 govind 251
 
25295 amit.gupta 252
	private List<UserRole> removeRole(List<UserRole> userRoles, int userId, int roleId) {
253
		if (userRoles == null) {
254
			userRoles = new ArrayList<>();
255
			return userRoles;
256
		}
257
		try {
258
			userRoles.remove(userRoleRepository.deleteByRoleUserId(userId, roleId));
259
		} catch (Exception e) {
260
 
261
		}
262
		return userRoles;
263
 
264
	}
265
 
22980 ashik.ali 266
	@SuppressWarnings("unchecked")
267
	@Override
23025 ashik.ali 268
	public Map<String, Object> updateRetailerDetails(UpdateRetailerRequest updateRetailerRequest)
269
			throws ProfitMandiBusinessException {
270
		Map<String, Object> map = this.getByEmailIdOrMobileNumber(updateRetailerRequest.getEmailIdOrMobileNumber());
23955 govind 271
		User user = (User) map.get("user");
28024 tejbeer 272
 
23329 ashik.ali 273
		user = this.createUser(user, updateRetailerRequest);
28024 tejbeer 274
 
23329 ashik.ali 275
		map.put("user", user);
23955 govind 276
		List<UserRole> userRoles = (List<UserRole>) map.get("userRoles");
23781 ashik.ali 277
		Role roleUser = roleRepository.selectByName(RoleType.USER.toString());
278
		userRoles = this.addRole(userRoles, user.getId(), roleUser.getId());
23955 govind 279
		Retailer retailer = (Retailer) map.get("retailer");
23329 ashik.ali 280
		retailer = this.updateRetailer(user, retailer, updateRetailerRequest);
28024 tejbeer 281
 
23329 ashik.ali 282
		map.put("retailer", retailer);
23955 govind 283
 
28189 tejbeer 284
		List<String> retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream()
285
				.map(x -> x.getBlockBrands()).collect(Collectors.toList());
28024 tejbeer 286
 
28189 tejbeer 287
		LOGGER.info("retailerBlockBrands" + retailerBlockBrands);
288
 
28024 tejbeer 289
		if (!retailerBlockBrands.isEmpty()) {
290
			retailerBlockBrandsRepository.deleteBrands(retailer.getId());
291
		}
292
 
293
		for (String blockBrand : updateRetailerRequest.getBlocksBrands()) {
294
			RetailerBlockBrands retailerBlockBrand = new RetailerBlockBrands();
295
 
296
			retailerBlockBrand.setFofoId(retailer.getId());
297
			retailerBlockBrand.setBlockBrands(blockBrand);
298
			retailerBlockBrandsRepository.persist(retailerBlockBrand);
299
 
300
		}
301
		map.put("retailerBlockBrands", retailerBlockBrands);
302
 
23781 ashik.ali 303
		Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
23955 govind 304
 
23781 ashik.ali 305
		userRoles = this.addRole(userRoles, user.getId(), roleRetailer.getId());
23955 govind 306
 
23781 ashik.ali 307
		Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 308
 
309
		if (updateRetailerRequest.isFofo()) {
23781 ashik.ali 310
			userRoles = this.addRole(userRoles, user.getId(), roleFofo.getId());
25295 amit.gupta 311
		} else {
312
			userRoles = this.removeRole(userRoles, user.getId(), roleFofo.getId());
23061 ashik.ali 313
		}
25295 amit.gupta 314
		map.put("fofoRole", this.containsRoleType(userRoles, roleFofo.getId()));
23955 govind 315
 
316
		if (this.containsRoleType(userRoles, roleFofo.getId())) {
23365 ashik.ali 317
			this.createDefaultPaymentOption(retailer.getId());
23329 ashik.ali 318
		}
23955 govind 319
 
23329 ashik.ali 320
		map.put("userRoles", userRoles);
321
		map.put("userRoleNames", this.toString(userRoles));
23955 govind 322
 
323
		Address retailerAddress = (Address) map.get("retailerAddress");
324
		retailerAddress = this.updateRetailerAddress(retailerAddress, updateRetailerRequest.getAddress(),
325
				retailer.getId());
23329 ashik.ali 326
		map.put("retailerAddress", retailerAddress);
23955 govind 327
 
328
		if (updateRetailerRequest.isFofo()) {
329
			FofoStore fofoStore = this.createFofoStoreCodeByRetailerId(retailer.getId(),
330
					updateRetailerRequest.getDistrictName(), retailerAddress.getState(), updateRetailerRequest);
23378 ashik.ali 331
			map.put("fofoStore", fofoStore);
25297 amit.gupta 332
			fofoStore.setActive(updateRetailerRequest.isActive());
23061 ashik.ali 333
		}
23955 govind 334
 
335
		this.createPrivateDealUser(user, updateRetailerRequest.isFofo(), updateRetailerRequest.getGstNumber(), retailer,
336
				retailerAddress.getId());
23329 ashik.ali 337
		map.put("gstNumber", updateRetailerRequest.getGstNumber());
338
		this.updateSaholicUser(retailer.getId(), retailerAddress.getId());
23955 govind 339
 
340
		List<Shop> shops = (List<Shop>) map.get("shops");
341
		if (shops == null) {
23060 ashik.ali 342
			shops = new ArrayList<>();
23061 ashik.ali 343
			map.put("shops", shops);
23060 ashik.ali 344
		}
23079 ashik.ali 345
		this.updateRetailerShops(shops, updateRetailerRequest.getShops(), retailer.getId(), retailerAddress);
23955 govind 346
 
23025 ashik.ali 347
		return map;
23955 govind 348
 
23025 ashik.ali 349
	}
23955 govind 350
 
351
	private void createDefaultPaymentOption(int fofoId) {
23365 ashik.ali 352
		List<Integer> paymentOptionIds = fofoPartnerPaymentOptionRepository.selectPaymentOptionIdsByFofoId(fofoId);
23955 govind 353
		if (paymentOptionIds.isEmpty()) {
23365 ashik.ali 354
			PaymentOption paymentOption = null;
23955 govind 355
			try {
23365 ashik.ali 356
				paymentOption = paymentOptionRepository.selectByName(PaymentOptionType.CASH.toString());
23955 govind 357
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23365 ashik.ali 358
				paymentOption = new PaymentOption();
359
				paymentOption.setName(PaymentOptionType.CASH.toString());
360
				paymentOptionRepository.persist(paymentOption);
361
			}
362
			FofoPartnerPaymentOption fofoPartnerPaymentOption = new FofoPartnerPaymentOption();
363
			fofoPartnerPaymentOption.setFofoId(fofoId);
364
			fofoPartnerPaymentOption.setPaymentOptionId(paymentOption.getId());
365
			fofoPartnerPaymentOptionRepository.persist(fofoPartnerPaymentOption);
366
		}
23955 govind 367
 
23365 ashik.ali 368
	}
23955 govind 369
 
370
	private User createUser(User user, UpdateRetailerRequest updateRetailerRequest) {
371
		if (user == null) {
23329 ashik.ali 372
			user = new User();
373
			user.setCity("");
374
			user.setPinCode(0);
375
			user.setState("");
376
			user.setPassword("");
377
			user.setMobile_verified(false);
378
			user.setReferral_url("");
379
			user.setGroup_id(1);
380
			user.setStatus(1);
381
			user.setActivated(true);
382
			user.setCreateTimestamp(LocalDateTime.now());
383
		}
24705 amit.gupta 384
		user.setActivated(updateRetailerRequest.isActive());
23329 ashik.ali 385
		user.setFirstName(updateRetailerRequest.getUserFirstName());
386
		user.setLastName(updateRetailerRequest.getUserLastName());
387
		user.setMobileNumber(updateRetailerRequest.getUserMobileNumber());
388
		user.setEmailId(updateRetailerRequest.getUserEmailId());
389
		user.setUsername(updateRetailerRequest.getUserEmailId());
23509 amit.gupta 390
		user.setUpdateTimestamp(LocalDateTime.now());
391
		userRepository.persist(user);
23329 ashik.ali 392
		return user;
23955 govind 393
 
23329 ashik.ali 394
	}
23955 govind 395
 
396
	private int createSaholicUser(User user, String retailerName) {
23043 ashik.ali 397
		com.spice.profitmandi.dao.entity.user.User saholicUser = null;
398
		try {
23063 ashik.ali 399
			saholicUser = userUserRepository.selectByEmailId(user.getEmailId());
23955 govind 400
		} catch (ProfitMandiBusinessException e) {
23043 ashik.ali 401
			LOGGER.info("User doesnt exist in old system");
402
		}
23955 govind 403
		if (saholicUser == null) {
23043 ashik.ali 404
			Cart cart = new Cart();
405
			cart.setCartStatus(CartStatus.ACTIVE);
406
			cartRepository.persist(cart);
407
			saholicUser = new com.spice.profitmandi.dao.entity.user.User();
23063 ashik.ali 408
			saholicUser.setEmailId(user.getEmailId());
23043 ashik.ali 409
			saholicUser.setName(retailerName);
410
			saholicUser.setActiveCartId(cart.getId());
23300 amit.gupta 411
			saholicUser.setCreateTimestamp(LocalDateTime.now());
23043 ashik.ali 412
			userUserRepository.persist(saholicUser);
23955 govind 413
 
23269 ashik.ali 414
			UserAccount ua = new UserAccount();
415
			ua.setAccountKey(saholicUser.getId());
416
			ua.setUserId(user.getId());
417
			ua.setType(AccountType.saholic);
23063 ashik.ali 418
			userAccountRepository.persist(ua);
419
 
23269 ashik.ali 420
			UserAccount ua2 = new UserAccount();
421
			ua2.setAccountKey(saholicUser.getActiveCartId());
422
			ua2.setUserId(user.getId());
423
			ua2.setType(AccountType.cartId);
23063 ashik.ali 424
			userAccountRepository.persist(ua2);
23955 govind 425
			LOGGER.info("created....");
23043 ashik.ali 426
		}
427
		return saholicUser.getId();
428
	}
23955 govind 429
 
26522 amit.gupta 430
	private com.spice.profitmandi.dao.entity.user.User createSaholicUser(
431
			LoginRequestResponseModel loginRequestResponseModel) {
432
		com.spice.profitmandi.dao.entity.user.User saholicUser = null;
433
		try {
434
			saholicUser = userUserRepository.selectByEmailId(loginRequestResponseModel.getEmail());
28198 tejbeer 435
			saholicUser.setCreateTimestamp(LocalDateTime.now());
26522 amit.gupta 436
		} catch (ProfitMandiBusinessException e) {
437
			LOGGER.info("User doesnt exist in old system");
438
		}
439
		if (saholicUser == null) {
440
			Cart cart = new Cart();
441
			cart.setCartStatus(CartStatus.ACTIVE);
442
			cartRepository.persist(cart);
443
			saholicUser = new com.spice.profitmandi.dao.entity.user.User();
26528 amit.gupta 444
			saholicUser.setPassword(getHash256(loginRequestResponseModel.getPassword()));
26522 amit.gupta 445
			saholicUser.setEmailId(loginRequestResponseModel.getEmail());
446
			saholicUser.setName(loginRequestResponseModel.getCustomerName());
447
			saholicUser.setActiveCartId(cart.getId());
448
			saholicUser.setCreateTimestamp(LocalDateTime.now());
449
			loginRequestResponseModel.setPassword(null);
450
			userUserRepository.persist(saholicUser);
451
		}
452
		return saholicUser;
453
	}
454
 
23955 govind 455
	private Retailer updateRetailer(User user, Retailer retailer, UpdateRetailerRequest updateRetailerRequest)
456
			throws ProfitMandiBusinessException {
457
		if (retailer == null) {
458
			LOGGER.info("createSaholicUser.....");
23063 ashik.ali 459
			int saholicUserId = this.createSaholicUser(user, updateRetailerRequest.getName());
23043 ashik.ali 460
			retailer = new Retailer();
461
			retailer.setId(saholicUserId);
462
		}
23329 ashik.ali 463
		retailer.setActive(updateRetailerRequest.isActive());
24704 amit.gupta 464
		user.setActivated(updateRetailerRequest.isActive());//
23955 govind 465
		// this.createRole(user.getId(), RoleType.RETAILER);
23025 ashik.ali 466
		retailer.setName(updateRetailerRequest.getName());
467
		retailer.setNumber(updateRetailerRequest.getNumber());
23955 govind 468
		if (updateRetailerRequest.getNumber() == null || updateRetailerRequest.getNumber().isEmpty()) {
23107 ashik.ali 469
			retailer.setType(RetailerType.UNREGISTERED_SHOP);
23955 govind 470
		} else {
23107 ashik.ali 471
			retailer.setType(RetailerType.GSTIN);
472
		}
23955 govind 473
		if (updateRetailerRequest.getDocumentId() > 0) {
474
			if (retailer.getDocumentId() != null && retailer.getDocumentId() != updateRetailerRequest.getDocumentId()) {
24374 amit.gupta 475
				try {
476
					documentRepository.deleteById(retailer.getDocumentId());
25295 amit.gupta 477
				} catch (Exception e) {
24374 amit.gupta 478
					e.printStackTrace();
479
				}
23489 ashik.ali 480
			}
23497 ashik.ali 481
			retailer.setDocumentId(updateRetailerRequest.getDocumentId());
482
			documentRepository.markDocumentAsPersisted(updateRetailerRequest.getDocumentId());
23025 ashik.ali 483
		}
484
		retailerRepository.persist(retailer);
23059 ashik.ali 485
		return retailer;
23025 ashik.ali 486
	}
23955 govind 487
 
488
	private void updateSaholicUser(int retailerId, int retailerAddressId) {
23329 ashik.ali 489
		try {
490
			com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(retailerId);
491
			user.setAddressId(retailerAddressId);
492
		} catch (ProfitMandiBusinessException e) {
23955 govind 493
 
23329 ashik.ali 494
		}
495
	}
23955 govind 496
 
497
	private void createPrivateDealUser(User user, boolean fofo, String gstNumber, Retailer retailer,
498
			int retailerAddressId) {
23329 ashik.ali 499
		PrivateDealUser privateDealUser = null;
23955 govind 500
		try {
23329 ashik.ali 501
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
23955 govind 502
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 503
			LOGGER.error("PrivateDealUser not found");
504
		}
23955 govind 505
 
506
		// = privateDealUserRepository.selectById(saholicUser.getId());
507
		if (privateDealUser == null) {
508
			Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(),
509
					retailer.getName(), retailerAddressId);
23473 ashik.ali 510
			try {
511
				this.createPrivateDealUser(retailer.getId(), counterId, fofo);
23955 govind 512
			} catch (Exception e) {
23473 ashik.ali 513
				LOGGER.error("ERROR : ", e);
514
			}
23955 govind 515
		} else {
516
			if (privateDealUser.getCounterId() == null) {
517
				Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(),
518
						retailer.getName(), retailerAddressId);
23329 ashik.ali 519
				privateDealUser.setCounterId(counterId);
520
				privateDealUser.setFofo(fofo);
521
				privateDealUserRepository.persist(privateDealUser);
23955 govind 522
			} else {
23329 ashik.ali 523
				Counter counter = null;
23955 govind 524
				try {
23329 ashik.ali 525
					counter = counterRepository.selectById(privateDealUser.getCounterId());
23955 govind 526
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 527
					LOGGER.error("Counter not found with id [{}]", privateDealUser.getCounterId());
528
				}
23955 govind 529
				if (counter == null) {
530
					this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(),
531
							retailerAddressId);
532
				} else {
23329 ashik.ali 533
					counter.setGstin(gstNumber);
534
					counterRepository.persist(counter);
535
				}
536
				privateDealUser.setFofo(fofo);
537
				privateDealUserRepository.persist(privateDealUser);
538
			}
539
		}
23955 govind 540
 
23329 ashik.ali 541
		PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
542
		privateDealUserAddressMapping.setUserId(retailer.getId());
543
		privateDealUserAddressMapping.setAddressId(retailerAddressId);
544
		privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
545
	}
23955 govind 546
 
547
	// Specifically set isFofo to true that has to be used by old system
548
	private void createPrivateDealUser(int retailerId, int counterId, boolean fofo) {
23329 ashik.ali 549
		PrivateDealUser privateDealUser = new PrivateDealUser();
550
		privateDealUser.setActive(true);
551
		privateDealUser.setBulkShipmentAmountLimit(fofo ? 1000000 : 50000);
552
		privateDealUser.setId(retailerId);
553
		privateDealUser.setCounterId(counterId);
554
		privateDealUser.setFofo(fofo);
555
		privateDealUserRepository.persist(privateDealUser);
556
	}
23955 govind 557
 
558
	private Integer createCounter(String emailId, String gstNumber, String mobileNumber, String name, int addressId) {
559
		if (gstNumber != null && !gstNumber.isEmpty()) {
23329 ashik.ali 560
			Counter counter = new Counter();
561
			counter.setEmailId(emailId);
562
			counter.setGstin(gstNumber);
563
			counter.setMobileNumber(mobileNumber);
564
			counter.setName(name);
565
			counter.setAddressId(addressId);
566
			counterRepository.persist(counter);
567
			return counter.getId();
23955 govind 568
		} else {
23329 ashik.ali 569
			return null;
570
		}
571
	}
23955 govind 572
 
573
	private Address updateRetailerAddress(Address address, CustomAddress customAddress, int retailerId)
574
			throws ProfitMandiBusinessException {
575
		if (address == null) {
23043 ashik.ali 576
			address = new Address();
577
			address.setRetaierId(retailerId);
578
			this.updateAddress(address, customAddress);
23955 govind 579
			// addressRepository.persist(addressRetailer);
580
 
23043 ashik.ali 581
			final RetailerRegisteredAddress retailerRegisteredAddress = new RetailerRegisteredAddress();
582
			retailerRegisteredAddress.setRetailerId(retailerId);
583
			retailerRegisteredAddress.setAddressId(address.getId());
584
			retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
23955 govind 585
		} else {
586
			this.updateAddress(address, customAddress);
587
			RetailerRegisteredAddress retailerRegisteredAddress = retailerRegisteredAddressRepository
588
					.selectByRetailerId(retailerId);
589
			retailerRegisteredAddress.setAddressId(address.getId());
590
			retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
23043 ashik.ali 591
		}
23059 ashik.ali 592
		return address;
23043 ashik.ali 593
	}
23955 govind 594
 
27411 amit.gupta 595
	private void updateAddress(Address address, CustomAddress customAddress) throws ProfitMandiBusinessException {
23025 ashik.ali 596
		address.setName(customAddress.getName());
23829 amit.gupta 597
		address.setPhoneNumber(customAddress.getPhoneNumber());
23025 ashik.ali 598
		address.setLine1(customAddress.getLine1());
599
		address.setLine2(customAddress.getLine2());
600
		address.setCity(customAddress.getCity());
601
		address.setPinCode(customAddress.getPinCode());
27411 amit.gupta 602
		State state = stateRepository.selectByName(customAddress.getState());
27877 amit.gupta 603
		if (state == null) {
604
			throw new ProfitMandiBusinessException("State name", "Invalid State - Pls Contact Technology",
605
					"Invalid State - Pls Contact Technology");
27411 amit.gupta 606
		}
607
		address.setState(state.getName());
23025 ashik.ali 608
		addressRepository.persist(address);
23955 govind 609
		LOGGER.info("Address Updated" + address);
23025 ashik.ali 610
	}
23955 govind 611
 
612
	private void updateRetailerShops(List<Shop> shops, Set<CustomShop> customShops, int retailerId,
613
			Address sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
614
		if (shops.isEmpty()) {
615
			for (CustomShop customShop : customShops) {
23043 ashik.ali 616
				Shop shop = new Shop();
23079 ashik.ali 617
				this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
23043 ashik.ali 618
				shops.add(shop);
619
			}
23955 govind 620
		} else {
621
			for (Shop shop : shops) {
622
				for (CustomShop customShop : customShops) {
623
					if (shop.getId() == customShop.getShopId()) {
23079 ashik.ali 624
						this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
23025 ashik.ali 625
					}
626
				}
627
			}
23955 govind 628
			for (CustomShop customShop : customShops) {
629
				if (customShop.getShopId() == 0) {
23043 ashik.ali 630
					Shop shop = new Shop();
23079 ashik.ali 631
					this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
23043 ashik.ali 632
					shops.add(shop);
633
				}
634
			}
23025 ashik.ali 635
		}
636
	}
23955 govind 637
 
638
	private void createOrUpdateShop(Shop shop, CustomShop customShop, int retailerId,
639
			Address sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
23043 ashik.ali 640
		shop.setRetailerId(retailerId);
641
		shop.setName(customShop.getName());
23955 govind 642
		if (customShop.getDocumentId() > 0) {
643
			if (shop.getDocumentId() != null && shop.getDocumentId() != customShop.getDocumentId()) {
24374 amit.gupta 644
				try {
645
					documentRepository.deleteById(shop.getDocumentId());
25295 amit.gupta 646
				} catch (Exception e) {
24374 amit.gupta 647
					e.printStackTrace();
648
				}
23489 ashik.ali 649
			}
23497 ashik.ali 650
			shop.setDocumentId(customShop.getDocumentId());
651
			documentRepository.markDocumentAsPersisted(customShop.getDocumentId());
23043 ashik.ali 652
		}
23955 govind 653
		if (shop.getAddressId() == null) {
23079 ashik.ali 654
			Address address = null;
23955 govind 655
			if (customShop.isSameAsRetailerAddress()) {
23079 ashik.ali 656
				address = sameAsRetailerAddressValue;
23955 govind 657
			} else {
658
				// shop.setDocumentId(customShop.getDocumentId());
23079 ashik.ali 659
				address = new Address();
660
				this.updateAddress(address, customShop.getAddress());
661
			}
23043 ashik.ali 662
			shop.setAddressId(address.getId());
663
			shop.setAddress(address);
664
			shopRepository.persist(shop);
23131 ashik.ali 665
			ShopAddress shopAddress = null;
23955 govind 666
			try {
23131 ashik.ali 667
				shopAddress = shopAddressRepository.selectByShopId(shop.getId());
668
				shopAddress.setAddressId(address.getId());
23955 govind 669
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23131 ashik.ali 670
				shopAddress = new ShopAddress();
671
				shopAddress.setAddressId(address.getId());
672
				shopAddress.setShopId(shop.getId());
673
			}
23043 ashik.ali 674
			shopAddressRepository.persist(shopAddress);
23955 govind 675
		} else {
24375 amit.gupta 676
			Address address = null;
677
			try {
678
				address = addressRepository.selectById(shop.getAddressId());
679
				CustomAddress customAddress = customShop.getAddress();
680
				if (!(address.getName().equals(customAddress.getName())
681
						&& address.getLine1().equals(customAddress.getLine1())
682
						&& address.getLine2().equals(customAddress.getLine2())
683
						&& address.getCity().equals(customAddress.getCity())
684
						&& address.getPinCode().equals(customAddress.getPinCode())
685
						&& address.getState().equals(customAddress.getState()))) {
686
					address = new Address();
687
					ShopAddress shopAddress = shopAddressRepository.selectByShopId(shop.getId());
688
					this.updateAddress(address, customAddress);
689
					shopAddress.setAddressId(address.getId());
690
					shopAddressRepository.persist(shopAddress);
691
					shop.setAddress(address);
692
					shopRepository.persist(shop);
693
				}
25295 amit.gupta 694
			} catch (Exception e) {
24375 amit.gupta 695
				if (customShop.isSameAsRetailerAddress()) {
696
					address = sameAsRetailerAddressValue;
697
				} else {
698
					// shop.setDocumentId(customShop.getDocumentId());
699
					address = new Address();
700
					this.updateAddress(address, customShop.getAddress());
701
				}
702
				shop.setAddressId(address.getId());
703
				shop.setAddress(address);
704
				shopRepository.persist(shop);
705
				ShopAddress shopAddress = null;
706
				try {
707
					shopAddress = shopAddressRepository.selectByShopId(shop.getId());
708
					shopAddress.setAddressId(address.getId());
709
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
710
					shopAddress = new ShopAddress();
711
					shopAddress.setAddressId(address.getId());
712
					shopAddress.setShopId(shop.getId());
713
				}
25295 amit.gupta 714
				shopAddressRepository.persist(shopAddress);
715
			}
23955 govind 716
 
23043 ashik.ali 717
		}
23955 govind 718
 
23043 ashik.ali 719
	}
23955 govind 720
 
721
	private void addAddress(List<Shop> shops) {
22980 ashik.ali 722
		Set<Integer> shopIds = this.toShopIds(shops);
23955 govind 723
		if (shopIds.isEmpty()) {
22980 ashik.ali 724
			return;
725
		}
726
		List<ShopAddress> shopAddresses = shopAddressRepository.selectByShopIds(shopIds);
727
		Map<Integer, Address> addressIdAddressMap = this.toAddressIdAddressMap(shopAddresses);
23955 govind 728
 
729
		for (Shop shop : shops) {
22980 ashik.ali 730
			shop.setAddress(addressIdAddressMap.get(shop.getAddressId()));
731
		}
732
	}
733
 
23955 govind 734
	private Map<Integer, Address> toAddressIdAddressMap(List<ShopAddress> shopAddresses) {
22980 ashik.ali 735
		Map<Integer, Address> addressIdAddressMap = new HashMap<>();
736
		List<Integer> addressIds = this.toAddressIds(shopAddresses);
737
		List<Address> addresses = addressRepository.selectByIds(addressIds);
23955 govind 738
		for (Address address : addresses) {
22980 ashik.ali 739
			addressIdAddressMap.put(address.getId(), address);
740
		}
741
		return addressIdAddressMap;
742
	}
23955 govind 743
 
744
	private List<Integer> toAddressIds(List<ShopAddress> shopAddresses) {
745
		Function<ShopAddress, Integer> shopAddressToAddressIdFunction = new Function<ShopAddress, Integer>() {
22980 ashik.ali 746
			@Override
747
			public Integer apply(ShopAddress shopAddress) {
748
				return shopAddress.getAddressId();
749
			}
750
		};
751
		return shopAddresses.stream().map(shopAddressToAddressIdFunction).collect(Collectors.toList());
752
	}
23955 govind 753
 
754
	private Set<Integer> toShopIds(List<Shop> shops) {
755
		Function<Shop, Integer> shopToAddressIdFunction = new Function<Shop, Integer>() {
22980 ashik.ali 756
			@Override
757
			public Integer apply(Shop shop) {
758
				return shop.getId();
759
			}
760
		};
761
		return shops.stream().map(shopToAddressIdFunction).collect(Collectors.toSet());
762
	}
23955 govind 763
 
764
	private String toString(List<UserRole> userRoles) {
23781 ashik.ali 765
		Set<Integer> roleIds = new HashSet<>();
23955 govind 766
		for (UserRole userRole : userRoles) {
23781 ashik.ali 767
			roleIds.add(userRole.getRoleId());
768
		}
769
		List<Role> roles = roleRepository.selectByIds(roleIds);
23955 govind 770
		Function<Role, String> roleToNameFunction = new Function<Role, String>() {
23781 ashik.ali 771
			public String apply(Role role) {
772
				return String.valueOf(role.getName());
22980 ashik.ali 773
			};
774
		};
23781 ashik.ali 775
		Set<String> userRoleStrings = roles.stream().map(roleToNameFunction).collect(Collectors.toSet());
22980 ashik.ali 776
		return String.join(", ", userRoleStrings);
777
	}
23955 govind 778
 
779
	private FofoStore createFofoStoreCodeByRetailerId(int retailerId, String districtName, String stateName,
780
			UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
23378 ashik.ali 781
		FofoStore fofoStore = null;
23955 govind 782
		try {
23378 ashik.ali 783
			fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
23955 govind 784
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
785
 
23378 ashik.ali 786
		}
23955 govind 787
 
788
		if (fofoStore != null) {
789
			fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
790
			fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
26209 tejbeer 791
			fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
28825 tejbeer 792
			fofoStore.setFofoType(updateRetailerRequest.getFofoType());
23955 govind 793
 
794
		} else {
23378 ashik.ali 795
			int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailerId);
796
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
23955 govind 797
 
23378 ashik.ali 798
			StateInfo stateInfo = null;
799
			try {
800
				stateInfo = Utils.getStateInfo(retailerAddress.getState());
801
			} catch (Exception e) {
802
				// TODO Auto-generated catch block
803
				e.printStackTrace();
23955 govind 804
				// throw new ProfitMandiBusinessException();
23378 ashik.ali 805
			}
23955 govind 806
			DistrictMaster districtMaster = districtMasterRepository.selectByNameAndStateShortName(districtName,
807
					stateInfo.getShortName());
808
 
23378 ashik.ali 809
			fofoStore = new FofoStore();
810
			fofoStore.setId(retailerId);
24023 amit.gupta 811
			fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
812
			fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
26209 tejbeer 813
			fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
23786 amit.gupta 814
			String latestStoreCode = fofoStoreRepository.selectLatestStore().getCode();
815
			int latestCodeCounter = Integer.parseInt(latestStoreCode.replaceAll("[A-Z]", ""));
23955 govind 816
			String fofoStoreCode = StringUtils.generateFofoStoreSequence(
817
					districtMaster.getStateShortName() + districtMaster.getShortName(), latestCodeCounter + 1);
23378 ashik.ali 818
			fofoStore.setCode(fofoStoreCode);
28189 tejbeer 819
			fofoStore.setBagsLastCredited(LocalDateTime.now());
28825 tejbeer 820
			fofoStore.setFofoType(updateRetailerRequest.getFofoType());
23378 ashik.ali 821
			fofoStoreRepository.persist(fofoStore);
28908 tejbeer 822
 
823
			// Auto fill in onboarding Panel
824
			PartnerOnBoardingPanel pobp = partnerOnBoardingPanelRepository
825
					.selectByPhoneNumber(Long.parseLong(retailerAddress.getPhoneNumber()));
826
			if (pobp != null) {
827
 
29042 tejbeer 828
				PartnerVerificationpanel partnerVerificationpanel = partnerOnboardingVerificationRepository
829
						.selectByOnboardingId(pobp.getId());
830
 
831
				if (partnerVerificationpanel != null) {
832
					if (partnerVerificationpanel.getApproval().equals(PartnerVerificationApprovalStatus.YES)) {
833
						pobp.setCode(fofoStore.getCode());
834
 
835
						storeTimelineTatService.onCodeCreated(pobp.getId());
836
 
837
					}
838
 
839
				}
840
 
28908 tejbeer 841
			}
23378 ashik.ali 842
		}
23955 govind 843
 
23378 ashik.ali 844
		return fofoStore;
845
	}
23955 govind 846
 
23329 ashik.ali 847
	@Override
23955 govind 848
	public FofoStore createFofoStoreCodeByUserId(int userId, String districtName, String stateName,
849
			UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
23329 ashik.ali 850
		User user = userRepository.selectById(userId);
851
		// = userAccountRepository.selectRetailerIdByUserId(user.getId());
852
		UserAccount userAccounts = userAccountRepository.selectSaholicByUserId(user.getId());
853
		Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
23781 ashik.ali 854
		Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 855
		try {
23781 ashik.ali 856
			userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleFofo.getId());
23955 govind 857
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 858
			throw new ProfitMandiBusinessException(ProfitMandiConstants.USER_ID, user.getId(), "USR_1013");
859
		}
23955 govind 860
		return this.createFofoStoreCodeByRetailerId(retailer.getId(), districtName, stateName, updateRetailerRequest);
861
 
23329 ashik.ali 862
	}
23955 govind 863
 
23329 ashik.ali 864
	@Override
865
	public List<DistrictMaster> getAllDistrictMaster(String stateName) {
866
		StateInfo stateInfo = null;
867
		try {
868
			stateInfo = Utils.getStateInfo(stateName);
869
		} catch (Exception e) {
870
			e.printStackTrace();
23955 govind 871
			// throw new ProfitMandiBusinessException();
23329 ashik.ali 872
		}
873
		return districtMasterRepository.selectByStateShortName(stateInfo.getShortName());
874
	}
22980 ashik.ali 875
 
23509 amit.gupta 876
	@Override
877
	public Map<Integer, CustomRetailer> getFofoRetailers(List<Integer> fofoIds) {
878
		List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
25295 amit.gupta 879
		Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
880
				.filter(x -> x.getAddressId() != null).collect(Collectors.toMap(x -> x.getAddressId(), x -> x));
23903 amit.gupta 881
		List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
23509 amit.gupta 882
		Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
25295 amit.gupta 883
		for (Address address : addresses) {
23903 amit.gupta 884
			com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
23509 amit.gupta 885
			CustomRetailer customRetailer = new CustomRetailer();
23903 amit.gupta 886
			customRetailer.setEmail(user.getEmailId());
23509 amit.gupta 887
			customRetailer.setBusinessName(address.getName());
888
			customRetailer.setMobileNumber(address.getPhoneNumber());
23532 amit.gupta 889
			try {
26151 amit.gupta 890
				FofoStore fs = fofoStoreRepository.selectByRetailerId(address.getRetaierId());
891
				customRetailer.setCode(fs.getCode());
892
				customRetailer.setWarehouseId(fs.getWarehouseId());
26977 amit.gupta 893
				customRetailer.setPartnerId(fs.getId());
26125 amit.gupta 894
			} catch (Exception e) {
895
				continue;
896
			}
897
			try {
23796 amit.gupta 898
				customRetailer.setCartId(user.getActiveCartId());
23532 amit.gupta 899
				PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
900
				Counter counter = counterRepository.selectById(pdu.getCounterId());
901
				customRetailer.setGstNumber(counter.getGstin());
23955 govind 902
			} catch (Exception e) {
23532 amit.gupta 903
				customRetailer.setGstNumber(null);
904
			}
905
			CustomAddress address1 = new CustomAddress();
906
			address1.setCity(address.getCity());
907
			address1.setState(address.getState());
908
			address1.setLine1(address.getLine1());
909
			address1.setLine2(address.getLine2());
910
			address1.setPinCode(address.getPinCode());
911
			address1.setName(address.getName());
912
			customRetailer.setAddress(address1);
26522 amit.gupta 913
			customRetailer.setDisplayName(
914
					customRetailer.getBusinessName() + "-" + customRetailer.getCode() + "- " + address1.getCity());
26977 amit.gupta 915
			customRetailersMap.put(customRetailer.getPartnerId(), customRetailer);
23509 amit.gupta 916
		}
917
		return customRetailersMap;
918
	}
25295 amit.gupta 919
 
23781 ashik.ali 920
	@Override
29605 amit.gupta 921
	@Cacheable(value = "getFofoRetailer", cacheManager = "oneDayCacheManager")
25295 amit.gupta 922
	public CustomRetailer getFofoRetailer(int fofoId) throws ProfitMandiBusinessException {
23957 tejbeer 923
		com.spice.profitmandi.dao.entity.user.User saholicUser = userUserRepository.selectById(fofoId);
26089 amit.gupta 924
		FofoStore store = fofoStoreRepository.selectByRetailerId(fofoId);
23957 tejbeer 925
		Address address = null;
926
		try {
927
			address = addressRepository.selectById(saholicUser.getAddressId());
928
		} catch (ProfitMandiBusinessException e1) {
929
			// TODO Auto-generated catch block
930
			e1.printStackTrace();
931
		}
932
		Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
25295 amit.gupta 933
		CustomRetailer customRetailer = new CustomRetailer();
934
		customRetailer.setEmail(saholicUser.getEmailId());
935
		customRetailer.setBusinessName(address.getName());
936
		customRetailer.setMobileNumber(address.getPhoneNumber());
937
		try {
938
			customRetailer.setCartId(saholicUser.getActiveCartId());
939
			PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
940
			Counter counter = counterRepository.selectById(pdu.getCounterId());
941
			customRetailer.setGstNumber(counter.getGstin());
942
		} catch (Exception e) {
943
			customRetailer.setGstNumber(null);
944
		}
945
		CustomAddress address1 = new CustomAddress();
946
		address1.setCity(address.getCity());
947
		address1.setState(address.getState());
948
		address1.setLine1(address.getLine1());
949
		address1.setLine2(address.getLine2());
950
		address1.setPinCode(address.getPinCode());
26653 amit.gupta 951
		address1.setPhoneNumber(address.getPhoneNumber());
25295 amit.gupta 952
		address1.setName(address.getName());
26125 amit.gupta 953
		customRetailer.setDisplayName(address.getName() + " - " + address.getCity());
25295 amit.gupta 954
		customRetailer.setAddress(address1);
955
		customRetailer.setPartnerId(address.getRetaierId());
26089 amit.gupta 956
		customRetailer.setCode(store.getCode());
26112 amit.gupta 957
		customRetailer.setWarehouseId(store.getWarehouseId());
25295 amit.gupta 958
		customRetailersMap.put(address.getRetaierId(), customRetailer);
23957 tejbeer 959
		return customRetailer;
25295 amit.gupta 960
 
23957 tejbeer 961
	}
26125 amit.gupta 962
 
25383 tejbeer 963
	@Override
27877 amit.gupta 964
	public Map<Integer, CustomRetailer> getFofoRetailerUserId(List<Integer> fofoIds) {
25383 tejbeer 965
		List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
966
		Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
967
				.filter(x -> x.getAddressId() != null).collect(Collectors.toMap(x -> x.getAddressId(), x -> x));
968
		List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
969
		Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
970
		for (Address address : addresses) {
971
			com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
972
			CustomRetailer customRetailer = new CustomRetailer();
973
			customRetailer.setEmail(user.getEmailId());
974
			customRetailer.setBusinessName(address.getName());
975
			customRetailer.setMobileNumber(address.getPhoneNumber());
27877 amit.gupta 976
			int userId = 0;
25383 tejbeer 977
			try {
27877 amit.gupta 978
				userId = userAccountRepository.selectUserIdByRetailerId(user.getId());
28024 tejbeer 979
			} catch (ProfitMandiBusinessException e) {
27877 amit.gupta 980
				continue;
981
			}
982
			try {
25383 tejbeer 983
				customRetailer.setCartId(user.getActiveCartId());
984
				PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
985
				Counter counter = counterRepository.selectById(pdu.getCounterId());
986
				customRetailer.setGstNumber(counter.getGstin());
987
			} catch (Exception e) {
988
				customRetailer.setGstNumber(null);
989
			}
990
			CustomAddress address1 = new CustomAddress();
991
			address1.setCity(address.getCity());
992
			address1.setState(address.getState());
993
			address1.setLine1(address.getLine1());
994
			address1.setLine2(address.getLine2());
995
			address1.setPinCode(address.getPinCode());
996
			address1.setName(address.getName());
997
			customRetailer.setAddress(address1);
998
			customRetailer.setPartnerId(address.getRetaierId());
999
			customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + address1.getCity());
1000
			customRetailersMap.put(userId, customRetailer);
1001
		}
1002
		return customRetailersMap;
1003
	}
25295 amit.gupta 1004
 
23957 tejbeer 1005
	@Override
23781 ashik.ali 1006
	public Map<Integer, String> getAllFofoRetailerIdEmailIdMap() {
1007
		Role roleFofo = null;
1008
		try {
1009
			roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
1010
		} catch (ProfitMandiBusinessException e) {
1011
			// TODO Auto-generated catch block
1012
			e.printStackTrace();
1013
		}
1014
		Role roleRetailer = null;
1015
		try {
1016
			roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
1017
		} catch (ProfitMandiBusinessException e) {
1018
			// TODO Auto-generated catch block
1019
			e.printStackTrace();
1020
		}
1021
		Set<Integer> roleIds = new HashSet<>();
1022
		roleIds.add(roleFofo.getId());
1023
		roleIds.add(roleRetailer.getId());
1024
		List<Integer> userIds = userRoleRepository.selectUserIdsByRoleIds(roleIds);
1025
		List<User> users = userRepository.selectAllByIds(new HashSet<>(userIds));
1026
		Map<Integer, Integer> userIdRetailerIdMap = this.getUserIdRetailerIdMap(userIds);
1027
		Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
23955 govind 1028
		for (User user : users) {
23781 ashik.ali 1029
			retailerIdEmailIdMap.put(userIdRetailerIdMap.get(user.getId()), user.getEmailId());
1030
		}
1031
		return retailerIdEmailIdMap;
1032
	}
23955 govind 1033
 
1034
	private Map<Integer, Integer> getUserIdRetailerIdMap(List<Integer> userIds) {
23781 ashik.ali 1035
		List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByUserIds(new HashSet<>(userIds));
1036
		Map<Integer, Integer> userIdRetailerIdMap = new HashMap<>();
23955 govind 1037
		for (UserAccount userAccount : userAccounts) {
23781 ashik.ali 1038
			userIdRetailerIdMap.put(userAccount.getUserId(), userAccount.getAccountKey());
1039
		}
1040
		return userIdRetailerIdMap;
1041
	}
25295 amit.gupta 1042
 
1043
	private Map<Integer, String> getUserIdEmailIdMap(Set<Integer> userIds) {
23880 ashik.ali 1044
		List<User> users = userRepository.selectAllByIds(userIds);
1045
		Map<Integer, String> userIdEmailIdMap = new HashMap<>();
23955 govind 1046
		for (User user : users) {
23880 ashik.ali 1047
			userIdEmailIdMap.put(user.getId(), user.getEmailId());
1048
		}
1049
		return userIdEmailIdMap;
1050
	}
23509 amit.gupta 1051
 
23880 ashik.ali 1052
	@Override
1053
	public Map<Integer, String> getAllFofoRetailerIdEmailIdMap(Set<Integer> retailerIds) {
1054
		List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1055
		Set<Integer> userIds = new HashSet<>();
23955 govind 1056
		for (UserAccount userAccount : userAccounts) {
23880 ashik.ali 1057
			userIds.add(userAccount.getUserId());
1058
		}
1059
		Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1060
		Map<Integer, String> userIdEmailIdMap = this.getUserIdEmailIdMap(userIds);
23955 govind 1061
		for (UserAccount userAccount : userAccounts) {
23880 ashik.ali 1062
			retailerIdEmailIdMap.put(userAccount.getAccountKey(), userIdEmailIdMap.get(userAccount.getUserId()));
1063
		}
1064
		return retailerIdEmailIdMap;
1065
	}
25295 amit.gupta 1066
 
24168 amit.gupta 1067
	@Override
24349 amit.gupta 1068
	public Map<Integer, String> getAllFofoRetailerIdNameMap(List<Integer> storeIds) {
24168 amit.gupta 1069
		Map<Integer, CustomRetailer> retailersMap = this.getFofoRetailers(storeIds);
1070
		Map<Integer, String> retailerIdNameMap = new HashMap<>();
25295 amit.gupta 1071
		for (Map.Entry<Integer, CustomRetailer> entry : retailersMap.entrySet()) {
1072
			retailerIdNameMap.put(entry.getKey(),
1073
					entry.getValue().getBusinessName() + "-" + entry.getValue().getAddress().getCity());
24168 amit.gupta 1074
		}
1075
		return retailerIdNameMap;
1076
	}
1077
 
1078
	@Override
28330 amit.gupta 1079
	@Cacheable(value = "FofoRetailerIdNameMap", cacheManager = "oneDayCacheManager")
24168 amit.gupta 1080
	public Map<Integer, String> getAllFofoRetailerIdNameMap() {
24349 amit.gupta 1081
		List<FofoStore> stores = fofoStoreRepository.selectAll();
25295 amit.gupta 1082
		List<Integer> storeIds = stores.stream().map(x -> x.getId()).collect(Collectors.toList());
24349 amit.gupta 1083
		return this.getAllFofoRetailerIdNameMap(storeIds);
1084
	}
1085
 
1086
	@Override
1087
	public List<MapWrapper<Integer, String>> getAllFofoRetailerIdNameList() {
1088
		List<MapWrapper<Integer, String>> mapWrappers = new ArrayList<>();
24168 amit.gupta 1089
		// TODO Auto-generated method stub
24349 amit.gupta 1090
		Map<Integer, String> fofoIdNameMap = this.getAllFofoRetailerIdNameMap();
25295 amit.gupta 1091
		fofoIdNameMap.forEach((fofoId, name) -> {
24349 amit.gupta 1092
			MapWrapper<Integer, String> idWrapper = new MapWrapper<>();
1093
			idWrapper.setKey(fofoId);
1094
			idWrapper.setValue(name);
1095
			mapWrappers.add(idWrapper);
1096
		});
1097
		return mapWrappers;
1098
	}
1099
 
1100
	@Override
27124 amit.gupta 1101
	@Cacheable(value = "retailerNames", cacheManager = "oneDayCacheManager")
26962 amit.gupta 1102
	public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly) {
24349 amit.gupta 1103
		// TODO Auto-generated method stub
26962 amit.gupta 1104
		Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream();
27861 tejbeer 1105
		if (activeOnly) {
1106
			storeStream = storeStream.filter(x -> x.isActive());
26962 amit.gupta 1107
		}
1108
		List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
24349 amit.gupta 1109
		return this.getFofoRetailers(storeIds);
24168 amit.gupta 1110
	}
25295 amit.gupta 1111
 
26522 amit.gupta 1112
	@Override
30017 amit.gupta 1113
	@Cacheable(value = "allFofoRetailers", cacheManager = "oneDayCacheManager")
27861 tejbeer 1114
	public Map<Integer, CustomRetailer> getAllFofoRetailers() {
1115
		// TODO Auto-generated method stub
1116
		Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream();
1117
 
1118
		List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1119
		return this.getFofoRetailers(storeIds);
1120
	}
1121
 
1122
	@Override
26522 amit.gupta 1123
	public LoginRequestResponseModel registerWebUser(LoginRequestResponseModel loginRequestModel)
1124
			throws ProfitMandiBusinessException {
1125
 
1126
		com.spice.profitmandi.dao.entity.user.User saholicUser = this.createSaholicUser(loginRequestModel);
1127
		loginRequestModel.setUserId(saholicUser.getId());
1128
 
1129
		this.createRetailerAddress(loginRequestModel);
1130
 
1131
		this.createPrivateDealUser(loginRequestModel);
1132
		this.updateSaholicUser(saholicUser.getId(), loginRequestModel.getBusinessAddress().getId());
1133
 
1134
		return loginRequestModel;
1135
 
1136
	}
1137
 
1138
	private void createPrivateDealUser(LoginRequestResponseModel loginRequestModel) {
1139
 
1140
		Integer counterId = this.createCounter(loginRequestModel.getEmail(), loginRequestModel.getGstNumber(),
1141
				loginRequestModel.getBusinessAddress().getPhoneNumber(),
1142
				loginRequestModel.getBusinessAddress().getName(), loginRequestModel.getBusinessAddress().getId());
1143
		try {
1144
			this.createPrivateDealUser(loginRequestModel.getUserId(), counterId, false);
1145
		} catch (Exception e) {
1146
			LOGGER.error("ERROR : ", e);
1147
		}
1148
 
1149
		PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
1150
		privateDealUserAddressMapping.setUserId(loginRequestModel.getUserId());
1151
		privateDealUserAddressMapping.setAddressId(loginRequestModel.getBusinessAddress().getId());
1152
		privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
1153
 
1154
	}
1155
 
1156
	private void createRetailerAddress(LoginRequestResponseModel loginRequestResponseModel)
1157
			throws ProfitMandiBusinessException {
1158
		Address businessAddress = loginRequestResponseModel.getBusinessAddress();
1159
		businessAddress.setRetaierId(loginRequestResponseModel.getUserId());
1160
		addressRepository.persist(businessAddress);
1161
	}
26536 amit.gupta 1162
 
26528 amit.gupta 1163
	private String getHash256(String originalString) {
26533 amit.gupta 1164
		String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
1165
		LOGGER.info("Hash String {}", hashString);
1166
		return hashString;
26528 amit.gupta 1167
	}
26533 amit.gupta 1168
 
1169
	@Override
26536 amit.gupta 1170
	@Cacheable(value = "fofoIdUrl", cacheManager = "oneDayCacheManager")
26533 amit.gupta 1171
	public Map<Integer, String> getAllFofoRetailerIdUrlMap() {
26536 amit.gupta 1172
		Map<Integer, String> fofoRetailerUrlMap = new HashMap<>();
1173
		List<FofoStore> stores = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive())
1174
				.collect(Collectors.toList());
1175
		Map<Integer, com.spice.profitmandi.dao.entity.user.User> userMap = userUserRepository
1176
				.selectByIds(stores.stream().map(x -> x.getId()).collect(Collectors.toList())).stream()
1177
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1178
		for (FofoStore store : stores) {
26537 amit.gupta 1179
			LOGGER.info("Store is {}", store);
26544 amit.gupta 1180
			String districtShortName = store.getCode().replaceAll("\\d+", "").substring(2);
26593 amit.gupta 1181
			String stateShortName = store.getCode().replaceAll("\\d+", "").substring(0, 2);
26539 amit.gupta 1182
			DistrictMaster districtMaster = null;
26544 amit.gupta 1183
			LOGGER.info("Store shortname is {}", districtShortName);
26593 amit.gupta 1184
			districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName(districtShortName,
1185
					stateShortName);
26543 amit.gupta 1186
			if (districtMaster == null) {
26544 amit.gupta 1187
				districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName("FB", "HR");
26539 amit.gupta 1188
			}
26542 amit.gupta 1189
			LOGGER.info("Store id - {}", store.getId());
28825 tejbeer 1190
			// com.spice.profitmandi.dao.entity.user.User user = userMap.get(store.getId());
26536 amit.gupta 1191
			String urlString = districtMaster.getStateShortName() + "/"
27877 amit.gupta 1192
					+ Utils.getHyphenatedString(districtMaster.getName()) + "/" + store.getCode();
28346 amit.gupta 1193
			fofoRetailerUrlMap.put(store.getId(), urlString.toLowerCase());
26541 amit.gupta 1194
			LOGGER.info("Store is {} end", store);
26536 amit.gupta 1195
 
1196
		}
1197
		return fofoRetailerUrlMap;
26533 amit.gupta 1198
	}
1199
 
1200
	@Override
26590 amit.gupta 1201
	@Cacheable(value = "storeCodeRetailerMap", cacheManager = "oneDayCacheManager")
1202
	public Map<String, Integer> getStoreCodeRetailerMap() {
26533 amit.gupta 1203
		Map<Integer, String> map = this.getAllFofoRetailerIdUrlMap();
26596 amit.gupta 1204
		Map<String, Integer> returnMap = map.entrySet().stream().collect(Collectors.toMap(x -> {
26593 amit.gupta 1205
			String[] splitString = x.getValue().split("/");
27877 amit.gupta 1206
			return splitString[splitString.length - 1];
26593 amit.gupta 1207
		}, x -> x.getKey()));
26596 amit.gupta 1208
		LOGGER.info("returnMap {}", returnMap);
1209
		return returnMap;
26533 amit.gupta 1210
	}
27877 amit.gupta 1211
 
1212
	@Override
1213
	public String getPartnerCriteriaString(PartnerCriteria partnerCriteria) {
1214
 
1215
		StringBuilder sb = new StringBuilder();
1216
		if (partnerCriteria.getFofoIds().size() > 0) {
1217
			List<Integer> fofoIds = partnerCriteria.getFofoIds();
1218
			Map<Integer, CustomRetailer> customRetailers = this.getFofoRetailerUserId(fofoIds);
28024 tejbeer 1219
			List<String> businessNames = customRetailers.values().stream().map(x -> x.getBusinessName())
1220
					.collect(Collectors.toList());
27877 amit.gupta 1221
			sb.append(String.join(", ", businessNames));
1222
 
1223
		} else {
1224
			sb.append("All");
28024 tejbeer 1225
			if (partnerCriteria.getPartnerTypes().size() > 0) {
1226
				sb.append(" ").append(String.join(", ", partnerCriteria.getPartnerTypes().stream()
1227
						.map(x -> x.getValue()).collect(Collectors.toList())));
27877 amit.gupta 1228
			}
1229
			sb.append(" partners ");
28024 tejbeer 1230
			if (partnerCriteria.getRegionIds().size() > 0) {
27877 amit.gupta 1231
				sb.append("from ");
28024 tejbeer 1232
				sb.append(String.join(", ", partnerCriteria.getRegionIds().stream()
1233
						.map(x -> ProfitMandiConstants.WAREHOUSE_MAP.get(x)).collect(Collectors.toList())));
27877 amit.gupta 1234
			}
1235
		}
1236
		return sb.toString();
1237
	}
22980 ashik.ali 1238
}