Subversion Repositories SmartDukaan

Rev

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