Subversion Repositories SmartDukaan

Rev

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