Subversion Repositories SmartDukaan

Rev

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