Subversion Repositories SmartDukaan

Rev

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