public override void Execute(IServiceProvider serviceProvider) { base.Execute(serviceProvider); try { lys_invoice createdInvoice = GetTargetAs <Entity>().ToEntity <lys_invoice>(); IOrganizationService currentUserService = CreateService(); // 5.1 if (createdInvoice.lys_type == null) { createdInvoice.lys_type = lys_invoice_lys_type.Ruchnoe_sozdanie; } NavInvoiceHandler invoiceHandler = new NavInvoiceHandler(currentUserService, TraceService); // 5.4 invoiceHandler.UpdateInvoiceDate(createdInvoice, true); } catch (EntityHandlerException e) { TraceService.Trace(e.ToString()); throw new InvalidPluginExecutionException(e.Message); } catch (Exception e) { TraceService.Trace(e.ToString()); throw new InvalidPluginExecutionException("Возникла ошибка, см. журнал для подробностей."); } }
/* * Checks if sum of all related agreement's paid invoices is bigger than it's own sum. * * invoice - lys_invoice. * * Returns true if sum of all related agreement's paid invoices <= agreement sum; false otherwise. */ private bool ValidateRelatedAgreementInvoicesSum(lys_invoice invoice) { lys_agreement relatedAgreement = new lys_agreement(); BaseRepository <lys_invoice> invoiceRepo = new BaseRepository <lys_invoice>(Service, lys_invoice.EntityLogicalName); // Checking if invoice contains related agreement ID. If not, obtaining it from CRM. if (invoice.lys_dogovorid != null) { relatedAgreement.Id = invoice.lys_dogovorid.Id; } else { relatedAgreement.Id = invoiceRepo.Get(invoice.Id, new ColumnSet(lys_invoice.Fields.lys_dogovorid)).lys_dogovorid.Id; } // Getting related agreement sum. BaseRepository <lys_agreement> agreementRepo = new BaseRepository <lys_agreement>(Service, lys_agreement.EntityLogicalName); relatedAgreement = agreementRepo.Get(relatedAgreement.Id, new ColumnSet(lys_agreement.Fields.lys_summ)); TracingService.Trace($"relatedAgreementId={relatedAgreement.Id}, invoiceId={invoice.Id}"); // Getting related paid invoices sum. Decimal totalPaidInvoiceSum = GetRelatedNavInvoicesSum(relatedAgreement.Id); return(totalPaidInvoiceSum <= relatedAgreement.lys_summ.Value); }
public override void Execute(IServiceProvider serviceProvider) { base.Execute(serviceProvider); try { lys_invoice createdInvoice = GetTargetAs <Entity>().ToEntity <lys_invoice>(); IOrganizationService currentUserService = CreateService(); NavInvoiceHandler invoiceHandler = new NavInvoiceHandler(currentUserService, TraceService); // 5.3 // 5.5 invoiceHandler.UpdateRelatedAgreementFactData(createdInvoice); } catch (EntityHandlerException e) { TraceService.Trace(e.ToString()); throw new InvalidPluginExecutionException(e.Message); } catch (Exception e) { TraceService.Trace(e.ToString()); throw new InvalidPluginExecutionException("Возникла ошибка, см. журнал для подробностей."); } }
/* * Updates lys_fact and lys_factsum fields of invoice's related agreement based on all it's related paid invoices. * * invoice - lys_invoice; * invoicesToExclude - IDs of lys_invoices to exclude from the related invoices list. * * Returns true if updated, false otherwise. */ public bool UpdateRelatedAgreementFactData(lys_invoice invoice, params Guid[] invoicesToExclude) { Guid relatedAgreementId; BaseRepository <lys_invoice> invoiceRepo = new BaseRepository <lys_invoice>(Service, lys_invoice.EntityLogicalName); BaseRepository <lys_agreement> agreementRepo = new BaseRepository <lys_agreement>(Service, lys_agreement.EntityLogicalName); // Checking if invoice contains related agreement ID. If not, obtaining it from CRM.) if (invoice.lys_dogovorid != null) { relatedAgreementId = invoice.lys_dogovorid.Id; } else { relatedAgreementId = invoiceRepo.Get(invoice.Id, new ColumnSet(lys_invoice.Fields.lys_dogovorid)).lys_dogovorid.Id; } TracingService.Trace($"relatedAgreementId={relatedAgreementId}"); // Obtaining related agreement sum from CRM. lys_agreement relatedAgreement = agreementRepo.Get(relatedAgreementId, new ColumnSet(lys_agreement.Fields.lys_summ)); // Getting total paid invoices sum. Decimal totalPaidInvoiceSum = GetRelatedNavInvoicesSum(relatedAgreementId, invoicesToExclude); relatedAgreement.lys_factsumma = new Money(totalPaidInvoiceSum); relatedAgreement.lys_fact = relatedAgreement.lys_summ.Value == totalPaidInvoiceSum; // Updating related agreement. agreementRepo.Update(relatedAgreement); TracingService.Trace($"Updated agreement with ID={relatedAgreementId}, totalPaidInvoiceSum={totalPaidInvoiceSum}, lys_fact={relatedAgreement.lys_fact}."); return(true); }
/* * Validates sum of all related agreement's paid invoices and updates invoice's lys_paydate on success. * * invoice - lys_invoice; * skipDbUpdate - if true, then no data will be written to DB. */ public void UpdateInvoiceDate(lys_invoice invoice, bool skipDbUpdate = false) { if (!ValidateRelatedAgreementInvoicesSum(invoice)) { throw new EntityHandlerException("Сумма созданных счетов превышает сумму связанного договора."); } TracingService.Trace("invoices sum validated, setting lys_paydate to current DateTime."); invoice.lys_paydate = DateTime.Now; if (skipDbUpdate) { return; } BaseRepository <lys_invoice> invoiceRepo = new BaseRepository <lys_invoice>(Service, lys_invoice.EntityLogicalName); invoiceRepo.Update(invoice); TracingService.Trace($"Updated invoice with ID={invoice.Id} in DB."); }
public override void Execute(IServiceProvider serviceProvider) { base.Execute(serviceProvider); if (PluginExecutionContext.Depth > 1) { // Recursive update. return; } try { lys_invoice updatedInvoice = GetTargetAs <Entity>().ToEntity <lys_invoice>(); IOrganizationService currentUserService = CreateService(); NavInvoiceHandler invoiceHandler = new NavInvoiceHandler(currentUserService, TraceService); // 5.3 // 5.5. invoiceHandler.UpdateRelatedAgreementFactData(updatedInvoice); // 5.4 invoiceHandler.UpdateInvoiceDate(updatedInvoice); } catch (EntityHandlerException e) { TraceService.Trace(e.ToString()); throw new InvalidPluginExecutionException(e.Message); } catch (Exception e) { TraceService.Trace(e.ToString()); throw; //throw new InvalidPluginExecutionException(Properties.strings.ErrorMessage); } }
/* * Creates new related lys_invoice if there are no other related invoices for the agreement. * * agreement - lys_agreement. */ public void CreateFirstRelatedInvoice(lys_agreement agreement, Guid emailNotificationSenderId) { TracingService.Trace($"agreementId={agreement.Id}"); if (HasRelatedInvoices(agreement)) { return; } // Checking if agreement contains required data. If not, obtaining it from CRM. if (agreement.lys_name == null || agreement.lys_summ == null || agreement.lys_contact == null) { BaseRepository <lys_agreement> agreementRepo = new BaseRepository <lys_agreement>(Service, lys_agreement.EntityLogicalName); agreement = agreementRepo.Get(agreement.Id, new ColumnSet(lys_agreement.Fields.lys_name, lys_agreement.Fields.lys_summ, lys_agreement.Fields.lys_contact)); } // Creating new invoice. lys_invoice newRelatedInvoice = new lys_invoice(); newRelatedInvoice.lys_name = string.Format("Счет для договора {0}", agreement.lys_name); newRelatedInvoice.lys_paydate = newRelatedInvoice.lys_date = DateTime.Now; newRelatedInvoice.lys_dogovorid = new EntityReference(lys_agreement.EntityLogicalName, agreement.Id); newRelatedInvoice.lys_fact = false; newRelatedInvoice.lys_type = lys_invoice_lys_type.Avtomaticheskoe_sozdanie; newRelatedInvoice.lys_amount = agreement.lys_summ; BaseRepository <lys_invoice> invoiceRepo = new BaseRepository <lys_invoice>(Service, lys_invoice.EntityLogicalName); Guid createdInvoiceId = invoiceRepo.Insert(newRelatedInvoice); TracingService.Trace($"Created new related lys_invoice with ID={createdInvoiceId} for agreementId={agreement.Id}"); // Getting agreement's related contact. BaseRepository <Contact> contactRepo = new BaseRepository <Contact>(Service, Contact.EntityLogicalName); Contact relatedContact = contactRepo.Get(agreement.lys_contact.Id, new ColumnSet(Contact.Fields.FullName, Contact.Fields.EMailAddress1, Contact.Fields.DoNotBulkEMail)); // Sending email to related contact if they hasn't opted out of emails and their email address is set. if (relatedContact.DoNotBulkEMail.HasValue && !relatedContact.DoNotBulkEMail.Value && relatedContact.EMailAddress1 != null) { // Forming Email message. ActivityParty senderParty = new ActivityParty(); senderParty.PartyId = new EntityReference(SystemUser.EntityLogicalName, emailNotificationSenderId); ActivityParty receiverParty = new ActivityParty(); receiverParty.PartyId = new EntityReference(Contact.EntityLogicalName, relatedContact.Id); Email emailMessage = new Email(); emailMessage.Subject = string.Format("Вам выставлен счет для оплаты договора {0}", agreement.lys_name); emailMessage.From = new[] { senderParty }; emailMessage.To = new[] { receiverParty }; emailMessage.Description = string.Format("Уважаемый(ая) {0}, по вашему договору {1} выставлен счет на сумму {2}.", relatedContact.FullName, agreement.lys_name, agreement.lys_summ.Value.ToString("0.##")); // Sending Email. SendEmailRequest emailRequest = new SendEmailRequest(); emailRequest.EmailId = Service.Create(emailMessage); // Creating Email Entity and getting its ID emailRequest.IssueSend = true; // Actually sending the email. emailRequest.TrackingToken = ""; Service.Execute(emailRequest); TracingService.Trace($"Sent notification email to related contact with ID={relatedContact.Id} at email={relatedContact.EMailAddress1}"); } }
public void CreateRelatedCreditInvoices(lys_agreement agreement) { TracingService.Trace($"agreementId={agreement.Id}"); BaseRepository <lys_agreement> agreementRepo = new BaseRepository <lys_agreement>(Service, lys_agreement.EntityLogicalName); BaseRepository <lys_invoice> invoiceRepo = new BaseRepository <lys_invoice>(Service, lys_invoice.EntityLogicalName); // Retrieving all related invoices. QueryExpression query = new QueryExpression(); query.ColumnSet = new ColumnSet(lys_invoice.Fields.lys_type, lys_invoice.Fields.lys_fact); query.Criteria.AddCondition(lys_invoice.Fields.lys_dogovorid, ConditionOperator.Equal, agreement.Id); EntityCollection relatedInvoices = invoiceRepo.GetMultiple(query); TracingService.Trace($"[lys_invoices] ec={relatedInvoices}, ec.Entities={relatedInvoices.Entities}, ec.Entities.Count={relatedInvoices.Entities.Count}"); // Checking if there are any paid or manually created related invoices. foreach (Entity entity in relatedInvoices.Entities) { lys_invoice invoice = (lys_invoice)entity; if (invoice.lys_fact == true || invoice.lys_type == lys_invoice_lys_type.Ruchnoe_sozdanie) { return; } } // Checking if agreement contains required data. If not, obtaining it from CRM. if (agreement.lys_creditid == null || agreement.lys_creditperiod == null || agreement.lys_creditamount == null || agreement.lys_name == null) { agreement = agreementRepo.Get(agreement.Id, new ColumnSet(lys_agreement.Fields.lys_creditid, lys_agreement.Fields.lys_creditperiod, lys_agreement.Fields.lys_creditamount, lys_agreement.Fields.lys_name)); // Checking if agreement has all required optional fields set. if (agreement.lys_creditid == null || agreement.lys_creditperiod == null || agreement.lys_creditamount == null) { return; } } // Deleting all existing automatically created related invoices. foreach (Entity entity in relatedInvoices.Entities) { invoiceRepo.Delete(entity.Id); } // Creating new related invoices based on the credit information. int creditPeriodMonths = agreement.lys_creditperiod.Value * 12; Decimal monthlyCreditAmount = agreement.lys_creditamount.Value / creditPeriodMonths; DateTime nextInvoiceDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1); for (int i = 0; i < creditPeriodMonths; ++i) { lys_invoice newRelatedInvoice = new lys_invoice(); newRelatedInvoice.lys_name = string.Format("Кредитный счет #{0} для договора {1}", i + 1, agreement.lys_name); newRelatedInvoice.lys_date = nextInvoiceDate; newRelatedInvoice.lys_paydate = newRelatedInvoice.lys_date; newRelatedInvoice.lys_dogovorid = agreement.ToEntityReference(); newRelatedInvoice.lys_fact = false; newRelatedInvoice.lys_type = lys_invoice_lys_type.Avtomaticheskoe_sozdanie; newRelatedInvoice.lys_amount = new Money(monthlyCreditAmount); invoiceRepo.Insert(newRelatedInvoice); nextInvoiceDate = nextInvoiceDate.AddMonths(1); } // Updating agreement's payment plan date. lys_agreement agreementToUpdate = new lys_agreement(); agreementToUpdate.Id = agreement.Id; agreementToUpdate.lys_paymentplandate = DateTime.Now.AddDays(1); agreementRepo.Update(agreementToUpdate); TracingService.Trace($"Created {creditPeriodMonths} new lys_invoices related to lys_agreement with ID={agreement.Id}"); }