| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using SVETA.Api.Helpers.Authorize; |
| | | 3 | | using SVETA.Api.Services.Interfaces; |
| | | 4 | | using System; |
| | | 5 | | using System.Linq; |
| | | 6 | | using CrmVtbc; |
| | | 7 | | using System.Collections.Generic; |
| | | 8 | | using Microsoft.Extensions.Options; |
| | | 9 | | using SVETA.Api.Data.Domain; |
| | | 10 | | using WinSolutions.Sveta.Common; |
| | | 11 | | using System.Security.Claims; |
| | | 12 | | using System.Threading.Tasks; |
| | | 13 | | using WinSolutions.Sveta.Server.Data.DataModel.Contexts; |
| | | 14 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 15 | | using WinSolutions.Sveta.Server.Data.DataModel.Kinds; |
| | | 16 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 17 | | using Microsoft.Extensions.Logging; |
| | | 18 | | using SVETA.Api.Helpers; |
| | | 19 | | |
| | | 20 | | namespace WinSolutions.Sveta.Server.Services.Implements |
| | | 21 | | { |
| | | 22 | | public class CrmSyncWorker : ICrmSyncWorker |
| | | 23 | | { |
| | | 24 | | private readonly SvetaDbContext _db; |
| | | 25 | | private readonly ICommonContragentService _commonContragentService; |
| | | 26 | | private readonly ICommonUserService _commonUserService; |
| | | 27 | | private readonly ICrmService _crmService; |
| | | 28 | | private readonly ConfigurationsSettings _confSettings; |
| | | 29 | | private readonly ILogger<CrmSyncWorker> _logger; |
| | | 30 | | |
| | | 31 | | private long serviceUserId; |
| | | 32 | | private bool crmStatus; |
| | | 33 | | private bool isNewUser; |
| | 0 | 34 | | public CrmSyncWorker(SvetaDbContext db, ICommonContragentService commonContragentService, ICommonUserService com |
| | 0 | 35 | | IOptions<ConfigurationsSettings> optionsConfs, ILogger<CrmSyncWorker> logger) |
| | 0 | 36 | | { |
| | 0 | 37 | | _confSettings = optionsConfs.Value; |
| | 0 | 38 | | _db = db; |
| | 0 | 39 | | _logger = logger; |
| | 0 | 40 | | _commonContragentService = commonContragentService; |
| | 0 | 41 | | _commonUserService = commonUserService; |
| | 0 | 42 | | _crmService = crmService; |
| | 0 | 43 | | if (!Guid.TryParse(_confSettings.GetConfValue("AuthenticationSettings", "ServiceUserTID"), out Guid serviceU |
| | 0 | 44 | | throw new ArgumentException("Не удалось разобрать значение ключа ServiceUserTID в секции AuthenticationS |
| | 0 | 45 | | serviceUserId = _commonUserService.GetUser(serviceUser).Result.Id; |
| | 0 | 46 | | if (!Boolean.TryParse(_confSettings.GetConfValue("CrmSettings", "SyncOn"), out crmStatus)) |
| | 0 | 47 | | throw new SvetaException("Не удалось определить статус синхронизации с CRM. Не удалось разобрать значени |
| | 0 | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Запускает синхронизацию с CRM. |
| | | 52 | | /// </summary> |
| | | 53 | | /// <param name="userTid">внешний идентификатор пользователя</param> |
| | | 54 | | /// <param name="contragentTid">внешний идентификатор контрагента</param> |
| | | 55 | | /// <param name="checkContragent">true, если необходимо проверить привязку контрагента к юзеру. Использовать tru |
| | | 56 | | /// <returns></returns> |
| | | 57 | | public async Task SyncWithCrm(Guid? userTid, Guid? contragentTid, bool checkContragent = false) |
| | 0 | 58 | | { |
| | 0 | 59 | | if ((userTid.IsDefaultValueOrNull() && contragentTid.IsDefaultValueOrNull()) || !crmStatus) |
| | 0 | 60 | | return; |
| | | 61 | | //new CrmVtbc.Model.Creatio.Account() |
| | | 62 | | // new CrmVtbc.Model.Creatio.Contact() |
| | 0 | 63 | | isNewUser = false; |
| | 0 | 64 | | User user = null; |
| | 0 | 65 | | Contragent contragent = null; |
| | 0 | 66 | | if (!userTid.IsDefaultValueOrNull()) |
| | 0 | 67 | | { |
| | 0 | 68 | | user = await SyncUserWithCrm(userTid.Value); |
| | 0 | 69 | | if (checkContragent) |
| | 0 | 70 | | { |
| | | 71 | | //проверяем не поменялся ли КА у юзера |
| | 0 | 72 | | var contragentCrmId = await _crmService.GetValue<Guid>("Contact", "NrbSvetaAccountId", new Dictionar |
| | 0 | 73 | | if (contragentCrmId.IsDefaultValueOrNull()) |
| | 0 | 74 | | throw new SvetaException($"В CRM у пользователя с TID={userTid.Value} не указан контрагент. Полу |
| | 0 | 75 | | contragentTid = await _crmService.GetValue<Guid>("Account", "NrbTID", new Dictionary<string, object> |
| | 0 | 76 | | if (contragentTid.IsDefaultValueOrNull()) |
| | 0 | 77 | | throw new SvetaException($"В CRM не найден контрагент с Id={contragentCrmId}. Полученное значени |
| | 0 | 78 | | } |
| | 0 | 79 | | } |
| | 0 | 80 | | if (!contragentTid.IsDefaultValueOrNull()) |
| | 0 | 81 | | contragent = await SyncContragentWithCrm(contragentTid.Value); |
| | | 82 | | //если синкуем и юзера и КА, то проверяем корректность привязки |
| | 0 | 83 | | if ((user != null && contragent != null) && user.Contragent?.Id != contragent?.Id) |
| | 0 | 84 | | { |
| | 0 | 85 | | user.Contragent = contragent; |
| | 0 | 86 | | await _commonUserService.Update(user, serviceUserId); |
| | 0 | 87 | | } |
| | 0 | 88 | | await SendToTelegram(user); |
| | 0 | 89 | | } |
| | | 90 | | |
| | | 91 | | /// <summary> |
| | | 92 | | /// Отправляет сообщение в телеграмм при создании нового пользователя в БД |
| | | 93 | | /// </summary> |
| | | 94 | | /// <param name="usr"></param> |
| | | 95 | | /// <returns></returns> |
| | | 96 | | private async Task SendToTelegram(User usr) |
| | 0 | 97 | | { |
| | 0 | 98 | | if (isNewUser && await _commonUserService.CanSendToTelegram("#newclient")) |
| | 0 | 99 | | { |
| | 0 | 100 | | string textTelegram = |
| | 0 | 101 | | $"#newclient " + |
| | 0 | 102 | | $"\nВыполнен вход нового пользователя {usr.FirstName} {usr.LastName}. " + |
| | 0 | 103 | | $"\nКонтрагент: {usr.Contragent?.ShortName} " + |
| | 0 | 104 | | $"\nНомер телефона: {usr.Phone}"; |
| | 0 | 105 | | await Telegram.SendNotification(textTelegram); |
| | 0 | 106 | | } |
| | 0 | 107 | | } |
| | | 108 | | |
| | | 109 | | /// <summary> |
| | | 110 | | /// Синхронизирует пользователя с CRM |
| | | 111 | | /// </summary> |
| | | 112 | | /// <param name="tid">tid пользователя из токена</param> |
| | | 113 | | /// <returns>обновленную запись пользователя</returns> |
| | | 114 | | private async Task<User> SyncUserWithCrm(Guid tid) |
| | 0 | 115 | | { |
| | 0 | 116 | | User user = await _commonUserService.GetUser(tid); |
| | 0 | 117 | | bool needToAdd = false; |
| | 0 | 118 | | if (user == null) |
| | 0 | 119 | | { |
| | 0 | 120 | | user = new User { ExternalKey = tid }; |
| | 0 | 121 | | needToAdd = true; |
| | 0 | 122 | | } |
| | | 123 | | SyncResult syncRes; |
| | | 124 | | try |
| | 0 | 125 | | { |
| | 0 | 126 | | syncRes = await _crmService.Sync(user, true); //синхрониируемся с CRM |
| | 0 | 127 | | } |
| | 0 | 128 | | catch (Exception ex) |
| | 0 | 129 | | { |
| | 0 | 130 | | throw new SvetaException($"Ошибка при обновлении из CRM данных по пользователю с TID={tid}. {ex.Message} |
| | | 131 | | } |
| | | 132 | | |
| | 0 | 133 | | if (string.IsNullOrWhiteSpace(user?.FirstName)) |
| | 0 | 134 | | throw new SvetaException($"В CRM у пользователя с TID {tid} не указано имя", (int)ErrorCode.CrmIncorrect |
| | 0 | 135 | | if (string.IsNullOrWhiteSpace(user?.LastName)) |
| | 0 | 136 | | throw new SvetaException($"В CRM у пользователя с TID {tid} не указана фамилия", (int)ErrorCode.CrmIncor |
| | 0 | 137 | | if (syncRes.IsLoadedFromCRM() && needToAdd) //если притянули данные из CRM и надо создать запись |
| | 0 | 138 | | { |
| | 0 | 139 | | await _commonUserService.Create(user, serviceUserId); |
| | 0 | 140 | | isNewUser = true; |
| | 0 | 141 | | } |
| | 0 | 142 | | else if (syncRes.IsLoadedFromCRM()) //если притянули данные из CRM |
| | 0 | 143 | | { |
| | 0 | 144 | | await _commonUserService.Update(user, serviceUserId); |
| | 0 | 145 | | } |
| | 0 | 146 | | return user; |
| | 0 | 147 | | } |
| | | 148 | | |
| | | 149 | | /// <summary> |
| | | 150 | | /// Синхронизирует тип контрагента с CRM |
| | | 151 | | /// </summary> |
| | | 152 | | /// <param name="id">Гуид типа контрагента</param> |
| | | 153 | | /// <returns>обновленную запись типа</returns> |
| | | 154 | | private async Task<ContragentsKind> SyncContragentKindWithCrm(Guid id) |
| | 0 | 155 | | { |
| | 0 | 156 | | bool needToAdd = false; |
| | 0 | 157 | | ContragentsKind contrKind = await _commonContragentService.GetContragentKind(id); |
| | 0 | 158 | | if (contrKind == null) |
| | 0 | 159 | | { |
| | 0 | 160 | | contrKind = new ContragentsKind { ExternalKey = id }; |
| | 0 | 161 | | needToAdd = true; |
| | 0 | 162 | | } |
| | | 163 | | SyncResult syncRes; |
| | | 164 | | try |
| | 0 | 165 | | { |
| | 0 | 166 | | syncRes = await _crmService.Sync(contrKind, true); //синхрониируемся с CRM |
| | 0 | 167 | | } |
| | 0 | 168 | | catch (Exception ex) |
| | 0 | 169 | | { |
| | 0 | 170 | | throw new SvetaException($"Ошибка при обновлении из CRM данных по типу контрагента. Идентификатор типа { |
| | | 171 | | } |
| | | 172 | | |
| | 0 | 173 | | if (string.IsNullOrWhiteSpace(contrKind?.Name)) |
| | 0 | 174 | | throw new SvetaException($"В CRM у типа контрагента с ID {id} не указано название", (int)ErrorCode.CrmIn |
| | 0 | 175 | | if (syncRes.IsLoadedFromCRM() && needToAdd) //если притянули данные из CRM и надо создать запись |
| | 0 | 176 | | { |
| | 0 | 177 | | await _commonContragentService.CreateContragentKind(contrKind, serviceUserId); |
| | 0 | 178 | | } |
| | 0 | 179 | | else if (syncRes.IsLoadedFromCRM()) //если притянули данные из CRM |
| | 0 | 180 | | { |
| | 0 | 181 | | await _commonContragentService.UpdateContragentKind(contrKind, serviceUserId); |
| | 0 | 182 | | } |
| | 0 | 183 | | return contrKind; |
| | 0 | 184 | | } |
| | | 185 | | |
| | | 186 | | /// <summary> |
| | | 187 | | /// Синхронизирует контрагента с CRM |
| | | 188 | | /// </summary> |
| | | 189 | | /// <param name="tid">tid контрагента из токена</param> |
| | | 190 | | /// <returns>обновленную запись контрагента</returns> |
| | | 191 | | private async Task<Contragent> SyncContragentWithCrm(Guid tid) |
| | 0 | 192 | | { |
| | 0 | 193 | | Contragent contragent = await _commonContragentService.GetContragent(tid); |
| | 0 | 194 | | bool needToUpdate = false, needToAdd = false; |
| | 0 | 195 | | if (contragent == null) |
| | 0 | 196 | | { |
| | 0 | 197 | | contragent = new Contragent { ExternalKey = tid }; |
| | 0 | 198 | | needToAdd = true; |
| | 0 | 199 | | } |
| | | 200 | | SyncResult syncRes; |
| | | 201 | | try |
| | 0 | 202 | | { |
| | 0 | 203 | | syncRes = await _crmService.Sync(contragent, true); //синхрониируемся с CRM |
| | 0 | 204 | | } |
| | 0 | 205 | | catch (Exception ex) |
| | 0 | 206 | | { |
| | 0 | 207 | | throw new SvetaException($"Ошибка при обновлении из CRM данных по контрагенту с TID={tid}. {ex.Message}" |
| | | 208 | | } |
| | | 209 | | |
| | 0 | 210 | | if (string.IsNullOrWhiteSpace(contragent.ShortName)) |
| | 0 | 211 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указано короткое название", (in |
| | 0 | 212 | | if (string.IsNullOrWhiteSpace(contragent.FullName)) |
| | 0 | 213 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указано полное название", (int) |
| | 0 | 214 | | if (string.IsNullOrWhiteSpace(contragent.Inn)) |
| | 0 | 215 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан ИНН", (int)ErrorCode.Crm |
| | 0 | 216 | | if (string.IsNullOrWhiteSpace(contragent.Kpp)) |
| | 0 | 217 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан КПП", (int)ErrorCode.Crm |
| | 0 | 218 | | if (await _commonContragentService.ContragentInnKppExist(contragent)) |
| | 0 | 219 | | throw new SvetaException($"Контрагент с ИНН {contragent.Inn} и КПП {contragent.Kpp} уже существует", (in |
| | 0 | 220 | | if (string.IsNullOrWhiteSpace(contragent.Email)) |
| | 0 | 221 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан Email", (int)ErrorCode.C |
| | 0 | 222 | | if (string.IsNullOrWhiteSpace(contragent.TaxSystemCRM)) |
| | 0 | 223 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указана форма налогообложения", |
| | 0 | 224 | | if (string.IsNullOrWhiteSpace(contragent.Ogrn)) |
| | 0 | 225 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан ОГРН", (int)ErrorCode.Cr |
| | 0 | 226 | | if (string.IsNullOrWhiteSpace(contragent.PhoneNumber)) |
| | 0 | 227 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан телефон", (int)ErrorCode |
| | 0 | 228 | | if (string.IsNullOrWhiteSpace(contragent.WalletId)) |
| | 0 | 229 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан номер кошелька", (int)Er |
| | 0 | 230 | | if (string.IsNullOrWhiteSpace(contragent.WalletShortId)) |
| | 0 | 231 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан короткий номер кошелька" |
| | 0 | 232 | | if (string.IsNullOrWhiteSpace(contragent.ChiefAccountant)) |
| | 0 | 233 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан главный бухгалтер", (int |
| | | 234 | | |
| | 0 | 235 | | var accountValList = await _crmService.GetEntityByField("Account", "NrbTID", tid, new List<string> { "NrbSve |
| | 0 | 236 | | "NrbDaDataPhysicalAddress", "NrbDaDataRegistrationAddress", "NrbDaDataPhysicalRegion", "NrbDaDataRegistr |
| | 0 | 237 | | "NrbDaDataRegistrationZip", "NrbDaDataPhysicalDistrict", "NrbDaDataRegistrationDistrict", "NrbDaData |
| | 0 | 238 | | "NrbDaDataPhysicalStreet", "NrbDaDataRegistrationStreet", "NrbDaDataPhysicalBuilding1", "NrbDaDataRe |
| | 0 | 239 | | "NrbDaDataRegistrationBuilding2", "NrbDaDataPhysicalAptOffice", "NrbDaDataRegistrationAptOffice"}); |
| | | 240 | | |
| | 0 | 241 | | if (string.IsNullOrWhiteSpace(accountValList["NrbDaDataRegistrationAddress"].ToString())) |
| | 0 | 242 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан юридический адрес", (int |
| | 0 | 243 | | if (string.IsNullOrWhiteSpace(accountValList["NrbDaDataPhysicalAddress"].ToString())) |
| | 0 | 244 | | throw new SvetaException($"У контрагента {contragent.ShortName} в CRM не указан физический адрес", (int) |
| | | 245 | | |
| | 0 | 246 | | var ownerId = accountValList["NrbSvetaAuthorizedPersonId"].IsDefaultValueOrNull() ? throw new SvetaException |
| | 0 | 247 | | $"Полученное значение NrbSvetaAuthorizedPersonId={accountValList["NrbSvetaAuthorizedPersonId"]}", (int)E |
| | 0 | 248 | | : Guid.Parse(accountValList["NrbSvetaAuthorizedPersonId"].ToString()); |
| | 0 | 249 | | var ownerTid = await _crmService.GetValue<Guid>("Contact", "NrbTID", new Dictionary<string, object>() { { "I |
| | 0 | 250 | | if (ownerTid.IsDefaultValueOrNull()) |
| | 0 | 251 | | throw new SvetaException($"В CRM не найден пользователь с Id={ownerId}. Полученное значение NrbTID={owne |
| | 0 | 252 | | var userOwner = await SyncUserWithCrm(ownerTid); |
| | | 253 | | |
| | 0 | 254 | | var typeId = accountValList["TypeId"].IsDefaultValueOrNull() ? throw new SvetaException($"В CRM у контрагент |
| | 0 | 255 | | $"Полученное значение TypeId={accountValList["TypeId"]}", (int)ErrorCode.CrmNoRelation) |
| | 0 | 256 | | : Guid.Parse(accountValList["TypeId"].ToString()); |
| | 0 | 257 | | var type = await SyncContragentKindWithCrm(typeId); |
| | | 258 | | |
| | 0 | 259 | | var juridicalAddress = await _commonContragentService.GetAddress(accountValList["NrbDaDataRegistrationAddres |
| | 0 | 260 | | if (juridicalAddress == null) |
| | 0 | 261 | | { |
| | 0 | 262 | | juridicalAddress = new Address() |
| | 0 | 263 | | { |
| | 0 | 264 | | FullAddress = accountValList["NrbDaDataRegistrationAddress"].ToString(), |
| | 0 | 265 | | Region = accountValList["NrbDaDataRegistrationRegion"].ToString(), |
| | 0 | 266 | | Index = accountValList["NrbDaDataRegistrationZip"].ToString(), |
| | 0 | 267 | | District = accountValList["NrbDaDataRegistrationDistrict"].ToString(), |
| | 0 | 268 | | Locality = accountValList["NrbDaDataRegistrationLocality"].ToString(), |
| | 0 | 269 | | Street = accountValList["NrbDaDataRegistrationStreet"].ToString(), |
| | 0 | 270 | | House = accountValList["NrbDaDataRegistrationBuilding1"].ToString(), |
| | 0 | 271 | | Housing = accountValList["NrbDaDataRegistrationBuilding2"].ToString(), |
| | 0 | 272 | | Office = accountValList["NrbDaDataRegistrationAptOffice"].ToString() |
| | 0 | 273 | | }; |
| | 0 | 274 | | await _commonContragentService.CreateAddress(juridicalAddress, serviceUserId); //записываем адрес тут, а |
| | 0 | 275 | | } |
| | | 276 | | else |
| | 0 | 277 | | { |
| | 0 | 278 | | juridicalAddress.FullAddress = accountValList["NrbDaDataRegistrationAddress"].ToString(); |
| | 0 | 279 | | juridicalAddress.Region = accountValList["NrbDaDataRegistrationRegion"].ToString(); |
| | 0 | 280 | | juridicalAddress.Index = accountValList["NrbDaDataRegistrationZip"].ToString(); |
| | 0 | 281 | | juridicalAddress.District = accountValList["NrbDaDataRegistrationDistrict"].ToString(); |
| | 0 | 282 | | juridicalAddress.Locality = accountValList["NrbDaDataRegistrationLocality"].ToString(); |
| | 0 | 283 | | juridicalAddress.Street = accountValList["NrbDaDataRegistrationStreet"].ToString(); |
| | 0 | 284 | | juridicalAddress.House = accountValList["NrbDaDataRegistrationBuilding1"].ToString(); |
| | 0 | 285 | | juridicalAddress.Housing = accountValList["NrbDaDataRegistrationBuilding2"].ToString(); |
| | 0 | 286 | | juridicalAddress.Office = accountValList["NrbDaDataRegistrationAptOffice"].ToString(); |
| | 0 | 287 | | await _commonContragentService.UpdateAddress(juridicalAddress, serviceUserId); |
| | 0 | 288 | | } |
| | | 289 | | |
| | 0 | 290 | | var physicalAddress = await _commonContragentService.GetAddress(accountValList["NrbDaDataPhysicalAddress"].T |
| | 0 | 291 | | if (physicalAddress == null) |
| | 0 | 292 | | { |
| | 0 | 293 | | physicalAddress = new Address() |
| | 0 | 294 | | { |
| | 0 | 295 | | FullAddress = accountValList["NrbDaDataPhysicalAddress"].ToString(), |
| | 0 | 296 | | Region = accountValList["NrbDaDataPhysicalRegion"].ToString(), |
| | 0 | 297 | | Index = accountValList["NrbDaDataPhysicalZip"].ToString(), |
| | 0 | 298 | | District = accountValList["NrbDaDataPhysicalDistrict"].ToString(), |
| | 0 | 299 | | Locality = accountValList["NrbDaDataPhysicalLocality"].ToString(), |
| | 0 | 300 | | Street = accountValList["NrbDaDataPhysicalStreet"].ToString(), |
| | 0 | 301 | | House = accountValList["NrbDaDataPhysicalBuilding1"].ToString(), |
| | 0 | 302 | | Housing = accountValList["NrbDaDataPhysicalBuilding2"].ToString(), |
| | 0 | 303 | | Office = accountValList["NrbDaDataPhysicalAptOffice"].ToString() |
| | 0 | 304 | | }; |
| | 0 | 305 | | await _commonContragentService.CreateAddress(physicalAddress, serviceUserId); |
| | 0 | 306 | | } |
| | 0 | 307 | | else if (physicalAddress?.Id != juridicalAddress?.Id) //если юр и физ адреса разные, тогда обновляем. чтобы |
| | 0 | 308 | | { |
| | 0 | 309 | | physicalAddress.FullAddress = accountValList["NrbDaDataPhysicalAddress"].ToString(); |
| | 0 | 310 | | physicalAddress.Region = accountValList["NrbDaDataPhysicalRegion"].ToString(); |
| | 0 | 311 | | physicalAddress.Index = accountValList["NrbDaDataPhysicalZip"].ToString(); |
| | 0 | 312 | | physicalAddress.District = accountValList["NrbDaDataPhysicalDistrict"].ToString(); |
| | 0 | 313 | | physicalAddress.Locality = accountValList["NrbDaDataPhysicalLocality"].ToString(); |
| | 0 | 314 | | physicalAddress.Street = accountValList["NrbDaDataPhysicalStreet"].ToString(); |
| | 0 | 315 | | physicalAddress.House = accountValList["NrbDaDataPhysicalBuilding1"].ToString(); |
| | 0 | 316 | | physicalAddress.Housing = accountValList["NrbDaDataPhysicalBuilding2"].ToString(); |
| | 0 | 317 | | physicalAddress.Office = accountValList["NrbDaDataPhysicalAptOffice"].ToString(); |
| | 0 | 318 | | await _commonContragentService.UpdateAddress(physicalAddress, serviceUserId); |
| | 0 | 319 | | } |
| | | 320 | | |
| | 0 | 321 | | if (contragent.Owner?.Id != userOwner?.Id) //Если старый и новый владелец не равны, присваиваем |
| | 0 | 322 | | { |
| | 0 | 323 | | contragent.Owner = userOwner; |
| | 0 | 324 | | needToUpdate = true; |
| | 0 | 325 | | } |
| | 0 | 326 | | if (contragent.JuridicAddress?.Id != juridicalAddress?.Id) //Если старый и новый адрес не равны, присваиваем |
| | 0 | 327 | | { |
| | 0 | 328 | | contragent.JuridicAddress = juridicalAddress; |
| | 0 | 329 | | needToUpdate = true; |
| | 0 | 330 | | } |
| | 0 | 331 | | if (contragent.PhysicAddress?.Id != physicalAddress?.Id) //Если старый и новый адрес не равны, присваиваем |
| | 0 | 332 | | { |
| | 0 | 333 | | contragent.PhysicAddress = physicalAddress; |
| | 0 | 334 | | needToUpdate = true; |
| | 0 | 335 | | } |
| | 0 | 336 | | if (contragent.ContragentsKind?.Id != type?.Id) //Если старый и новый тип не равны, присваиваем |
| | 0 | 337 | | { |
| | 0 | 338 | | contragent.ContragentsKind = type; |
| | 0 | 339 | | needToUpdate = true; |
| | 0 | 340 | | } |
| | | 341 | | |
| | 0 | 342 | | if (syncRes.IsLoadedFromCRM() && needToAdd) //если притянули данные из CRM и надо создать запись |
| | 0 | 343 | | { |
| | 0 | 344 | | await _commonContragentService.Create(contragent, serviceUserId); |
| | 0 | 345 | | } |
| | 0 | 346 | | else if (syncRes.IsLoadedFromCRM() || needToUpdate) //если притянули данные из CRM или обновили связи у запи |
| | 0 | 347 | | { |
| | 0 | 348 | | await _commonContragentService.Update(contragent, serviceUserId); |
| | 0 | 349 | | } |
| | | 350 | | |
| | 0 | 351 | | return contragent; |
| | 0 | 352 | | } |
| | | 353 | | |
| | | 354 | | /// <summary> |
| | | 355 | | /// Синхронизирует всех пользователей контрагента |
| | | 356 | | /// </summary> |
| | | 357 | | /// <param name="contragentId">id контрагента</param> |
| | | 358 | | /// <returns></returns> |
| | | 359 | | public async Task SyncAllUsersByContragent(long contragentId) |
| | 0 | 360 | | { |
| | 0 | 361 | | if (!crmStatus || contragentId <= 0) |
| | 0 | 362 | | return; |
| | 0 | 363 | | isNewUser = false; |
| | 0 | 364 | | var contragent = await _commonContragentService.GetContragent(contragentId); |
| | 0 | 365 | | var contragentCrmId = await _crmService.GetValue<Guid>("Account", "Id", new Dictionary<string, object>() { { |
| | 0 | 366 | | if (contragentCrmId.IsDefaultValueOrNull()) |
| | 0 | 367 | | throw new SvetaException($"В CRM не найден контрагент с TID={contragent.ExternalKey}. Полученное значени |
| | | 368 | | //"NrbSvetaAccount/Id" - через слеш, так как пока так реализовано в софте террасофта обращение к ссылочным п |
| | 0 | 369 | | var usersTids = await _crmService.GetAllEntriesByFields("Contact", new Dictionary<string, object>() { { "Nrb |
| | 0 | 370 | | foreach (var item in usersTids) |
| | 0 | 371 | | { |
| | 0 | 372 | | var tid = Guid.Parse(item["NrbTID"].ToString()); |
| | 0 | 373 | | if (tid.IsDefaultValueOrNull()) |
| | 0 | 374 | | continue; |
| | 0 | 375 | | var user = await SyncUserWithCrm(tid); |
| | 0 | 376 | | if (user.Contragent?.Id != contragent?.Id) |
| | 0 | 377 | | { |
| | 0 | 378 | | user.Contragent = contragent; |
| | 0 | 379 | | await _commonUserService.Update(user, serviceUserId); |
| | 0 | 380 | | } |
| | 0 | 381 | | await SendToTelegram(user); |
| | 0 | 382 | | } |
| | 0 | 383 | | } |
| | | 384 | | } |
| | | 385 | | } |