예제 #1
0
        public override int SaveOrUpdateInvoice(Invoice invoice)
        {
            if (invoice != null && invoice.ID > 0)
                ResetCache(invoice.ID);

            return base.SaveOrUpdateInvoice(invoice);
        }
 public static InvoiceFormattedData GetDataAfterLinesUpdated(Invoice invoice)
 {
     if (invoice.JsonData != null)
     {
         var oldData = ReadData(invoice.JsonData);
         return CreateDataAfterLinesUpdated(invoice, oldData);
     }
     else
     {
         return CreateData(invoice, 0, 0);
     }
 }
예제 #3
0
 public InvoiceBaseWrapper(Invoice invoice)
     : base(invoice.ID)
 {
     Status = new InvoiceStatusWrapper(invoice.Status);
     Number = invoice.Number;
     IssueDate = (ApiDateTime) invoice.IssueDate;
     TemplateType = invoice.TemplateType;
     DueDate = (ApiDateTime) invoice.DueDate;
     Currency = !String.IsNullOrEmpty(invoice.Currency) ?
         new CurrencyInfoWrapper(CurrencyProvider.Get(invoice.Currency)) :
         new CurrencyInfoWrapper(Global.TenantSettings.DefaultCurrency);
     ExchangeRate = invoice.ExchangeRate;
     Language = invoice.Language;
     PurchaseOrderNumber = invoice.PurchaseOrderNumber;
     Terms = invoice.Terms;
     Description = invoice.Description;
     FileID = invoice.FileID;
     CreateOn = (ApiDateTime)invoice.CreateOn;
     CreateBy = EmployeeWraper.Get(invoice.CreateBy);
     CanEdit = CRMSecurity.CanEdit(invoice);
     CanDelete = CRMSecurity.CanDelete(invoice);
 }
        public static void DataInvoicesDetailsView(BasePage page, Invoice targetInvoice)
        {
            if(targetInvoice == null)
                return;

            var script = String.Format(@"var invoiceData = '{0}';", Global.EncodeTo64(targetInvoice.JsonData));

            var apiServer = new Api.ApiServer();
            var apiUrl = String.Format("{0}crm/invoice/{1}.json",SetupInfo.WebApiBaseUrl, targetInvoice.ID);
            var invoice = apiServer.GetApiResponse(apiUrl, "GET");

            page.RegisterInlineScript(script, onReady: false);
            page.JsonPublisher(invoice, "invoice");
        }
예제 #5
0
 public void UpdateInvoiceJsonData(Invoice invoice, int billingAddressID, int deliveryAddressID)
 {
     invoice.JsonData = JsonConvert.SerializeObject(InvoiceFormattedData.GetData(invoice, billingAddressID, deliveryAddressID));
     Global.DaoFactory.GetInvoiceDao().UpdateInvoiceJsonData(invoice.ID, invoice.JsonData);
 }
예제 #6
0
        public virtual int SaveOrUpdateInvoice(Invoice invoice)
        {
            _cache.Insert(_invoiceCacheKey, String.Empty);

            using (var db = GetDb())
            {
                return SaveOrUpdateInvoice(invoice, db);
            }
        }
예제 #7
0
        private static ASC.Files.Core.File SaveFile(Invoice data, string url)
        {
            ASC.Files.Core.File file = null;

            var request = (HttpWebRequest)WebRequest.Create(url);

            using (var response = request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    if (stream != null)
                    {
                        var document = new ASC.Files.Core.File
                        {
                            Title = string.Format("{0}{1}", data.Number, FormatPdf),
                            FolderID = Global.DaoFactory.GetFileDao().GetRoot(),
                            ContentLength = response.ContentLength
                        };

                        if (data.GetInvoiceFile() != null)
                        {
                            document.ID = data.FileID;
                        }

                        file = Global.DaoFactory.GetFileDao().SaveFile(document, stream);
                    }
                }
            }

            return file;
        }
예제 #8
0
 public static ASC.Files.Core.File CreateFile(Invoice data)
 {
     var log = log4net.LogManager.GetLogger("ASC.CRM");
     try
     {
         using (var docxStream = GetStreamDocx(data))
         {
             var urlToFile = GetUrlToFile(docxStream);
             return SaveFile(data, urlToFile);
         }
     }
     catch (Exception e)
     {
         log.Error(e);
         throw;
     }
 }
예제 #9
0
 public static void MakePublic(Invoice invoice)
 {
     MakePublic((ISecurityObjectId)invoice);
 }
예제 #10
0
 public static bool CanDelete(Invoice invoice)
 {
     return (IsAdmin || invoice.CreateBy == SecurityContext.CurrentAccount.ID);
 }
예제 #11
0
 public static bool CanEdit(Invoice invoice)
 {
     return (IsAdmin || invoice.CreateBy == SecurityContext.CurrentAccount.ID) && invoice.Status == InvoiceStatus.Draft;
 }
예제 #12
0
        public static bool CanAccessTo(Invoice invoice)
        {
            if (IsAdmin || invoice.CreateBy == SecurityContext.CurrentAccount.ID) return true;

            if (invoice.ContactID > 0)
                return CanAccessTo(Global.DaoFactory.GetContactDao().GetByID(invoice.ContactID));

            if (invoice.EntityType == EntityType.Opportunity)
                return CanAccessTo(Global.DaoFactory.GetDealDao().GetByID(invoice.EntityID));

            return false;
        }
예제 #13
0
 public static void SetAccessTo(Invoice invoice, List<Guid> subjectID)
 {
     SetAccessTo((ISecurityObjectId)invoice, subjectID);
 }
예제 #14
0
 public void UpdateInvoiceJsonDataAfterLinesUpdated(Invoice invoice)
 {
     var jsonData = InvoiceFormattedData.GetDataAfterLinesUpdated(invoice);
     if (jsonData.LogoBase64Id != 0)
     {
         jsonData.LogoBase64 = null;
     }
     Global.DaoFactory.GetInvoiceDao().UpdateInvoiceJsonData(invoice.ID, invoice.JsonData);
 }
예제 #15
0
 public void UpdateInvoiceJsonData(Invoice invoice, int billingAddressID, int deliveryAddressID)
 {
     var jsonData = InvoiceFormattedData.GetData(invoice, billingAddressID, deliveryAddressID);
     if (jsonData.LogoBase64Id != 0)
     {
         jsonData.LogoBase64 = null;
     }
     invoice.JsonData = JsonConvert.SerializeObject(jsonData);
     Global.DaoFactory.GetInvoiceDao().UpdateInvoiceJsonData(invoice.ID, invoice.JsonData);
 }
예제 #16
0
        private static InvoiceFormattedData CreateDataAfterLinesUpdated(Invoice invoice, InvoiceFormattedData invoiceOldData)
        {
            var data = invoiceOldData;

            var cultureInfo = string.IsNullOrEmpty(invoice.Language) ? CultureInfo.CurrentCulture : CultureInfo.GetCultureInfo(invoice.Language);

            #region TableBodyRows, TableFooterRows, TableTotalRow

            data.TableBodyRows = new List<List<string>>();

            var invoiceLines = invoice.GetInvoiceLines();
            var invoiceTaxes = new Dictionary<int, decimal>();

            decimal subtotal = 0;
            decimal discount = 0;
            decimal amount = 0;

            foreach (var line in invoiceLines)
            {
                var item = Global.DaoFactory.GetInvoiceItemDao().GetByID(line.InvoiceItemID);
                var tax1 = line.InvoiceTax1ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax1ID) : null;
                var tax2 = line.InvoiceTax2ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax2ID) : null;

                var subtotalValue = Math.Round(line.Quantity * line.Price, 2);
                var discountValue = Math.Round(subtotalValue * line.Discount / 100, 2);

                var rate = 0;
                if (tax1 != null)
                {
                    rate += tax1.Rate;
                    if (invoiceTaxes.ContainsKey(tax1.ID))
                    {
                        invoiceTaxes[tax1.ID] = invoiceTaxes[tax1.ID] + Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2);
                    }
                    else
                    {
                        invoiceTaxes.Add(tax1.ID, Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2));
                    }
                }
                if (tax2 != null)
                {
                    rate += tax2.Rate;
                    if (invoiceTaxes.ContainsKey(tax2.ID))
                    {
                        invoiceTaxes[tax2.ID] = invoiceTaxes[tax2.ID] + Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2);
                    }
                    else
                    {
                        invoiceTaxes.Add(tax2.ID, Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2));
                    }
                }

                decimal taxValue = Math.Round((subtotalValue - discountValue) * rate / 100, 2);
                decimal amountValue = Math.Round(subtotalValue - discountValue + taxValue, 2);

                subtotal += subtotalValue;
                discount += discountValue;
                amount += amountValue;

                data.TableBodyRows.Add(new List<string>
                    {
                        item.Title + (string.IsNullOrEmpty(line.Description) ? string.Empty : ": " +line.Description),
                        line.Quantity.ToString(CultureInfo.InvariantCulture),
                        line.Price.ToString(CultureInfo.InvariantCulture),
                        line.Discount.ToString(CultureInfo.InvariantCulture),
                        tax1 != null ? tax1.Name : string.Empty,
                        tax2 != null ? tax2.Name : string.Empty,
                        (subtotalValue-discountValue).ToString(CultureInfo.InvariantCulture)
                    });
            }

            data.TableFooterRows = new List<Tuple<string, string>>();
            data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Subtotal", cultureInfo), (subtotal - discount).ToString(CultureInfo.InvariantCulture)));

            foreach (var invoiceTax in invoiceTaxes)
            {
                var iTax = Global.DaoFactory.GetInvoiceTaxDao().GetByID(invoiceTax.Key);
                data.TableFooterRows.Add(new Tuple<string, string>(string.Format("{0} ({1}%)", iTax.Name, iTax.Rate), invoiceTax.Value.ToString(CultureInfo.InvariantCulture)));
            }

            //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture)));

            data.TableTotalRow = new Tuple<string, string>(string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo), invoice.Currency), amount.ToString(CultureInfo.InvariantCulture));


            #endregion


            return data;
        }
예제 #17
0
 public static InvoiceFormattedData GetData(Invoice invoice, int billingAddressID, int deliveryAddressID)
 {
     return invoice.JsonData != null ? ReadData(invoice.JsonData) : CreateData(invoice, billingAddressID, deliveryAddressID);
 }
예제 #18
0
 public static bool IsPrivate(Invoice invoice)
 {
     return IsPrivate((ISecurityObjectId)invoice);
 }
예제 #19
0
        private static InvoiceFormattedData CreateData(Invoice invoice, int billingAddressID, int deliveryAddressID)
        {
            var data = new InvoiceFormattedData();
            var sb = new StringBuilder();
            var list = new List<string>();
            var cultureInfo = string.IsNullOrEmpty(invoice.Language) ? CultureInfo.CurrentCulture : CultureInfo.GetCultureInfo(invoice.Language);


            #region TemplateType

            data.TemplateType = (int)invoice.TemplateType;

            #endregion


            #region Seller, LogoBase64, LogoSrcFormat

            var invoiceSettings = Global.DaoFactory.GetInvoiceDao().GetSettings();

            if (!string.IsNullOrEmpty(invoiceSettings.CompanyName))
            {
                sb.Append(invoiceSettings.CompanyName);
            }

            if (!string.IsNullOrEmpty(invoiceSettings.CompanyAddress))
            {
                var obj = JObject.Parse(invoiceSettings.CompanyAddress);

                var str = obj.Value<string>("country");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                str = obj.Value<string>("state");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                str = obj.Value<string>("city");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                str = obj.Value<string>("street");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                str = obj.Value<string>("zip");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                if (list.Count > 0)
                {
                    sb.AppendLine();
                    sb.Append(string.Join(", ", list));
                }
            }

            data.Seller = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Seller", cultureInfo), sb.ToString());

            if (invoiceSettings.CompanyLogoID != 0)
            {
                data.LogoBase64Id = invoiceSettings.CompanyLogoID;
                //data.LogoBase64 = OrganisationLogoManager.GetOrganisationLogoBase64(invoiceSettings.CompanyLogoID);
                data.LogoSrcFormat = OrganisationLogoManager.OrganisationLogoSrcFormat;
            }

            #endregion


            #region Number

            data.Number = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Invoice", cultureInfo), invoice.Number);

            #endregion


            #region Invoice

            data.Invoice = new List<Tuple<string, string>>();
            data.Invoice.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("IssueDate", cultureInfo), invoice.IssueDate.ToShortDateString()));
            if (!string.IsNullOrEmpty(invoice.PurchaseOrderNumber))
            {
                data.Invoice.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("PONumber", cultureInfo), invoice.PurchaseOrderNumber));
            }
            data.Invoice.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("DueDate", cultureInfo), invoice.DueDate.ToShortDateString()));

            #endregion


            #region Customer

            var customer = Global.DaoFactory.GetContactDao().GetByID(invoice.ContactID);

            if (customer != null)
            {
                sb = new StringBuilder();

                sb.Append(customer.GetTitle());

                var billingAddress = billingAddressID != 0 ? Global.DaoFactory.GetContactInfoDao().GetByID(billingAddressID) : null;
                if (billingAddress != null && billingAddress.InfoType == ContactInfoType.Address && billingAddress.Category == (int)AddressCategory.Billing)
                {
                    list = new List<string>();

                    var obj = JObject.Parse(billingAddress.Data);

                    var str = obj.Value<string>("country");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("state");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("city");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("street");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("zip");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    if (list.Count > 0)
                    {
                        sb.AppendLine();
                        sb.Append(string.Join(", ", list));
                    }
                }

                data.Customer = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("BillTo", cultureInfo), sb.ToString());
            }

            #endregion


            #region TableHeaderRow, TableBodyRows, TableFooterRows, TableTotalRow

            data.TableHeaderRow = new List<string>
                {
                    CRMInvoiceResource.ResourceManager.GetString("ItemCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("QuantityCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("PriceCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("DiscountCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("TaxCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("TaxCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("AmountCol", cultureInfo)
                };

            data.TableBodyRows = new List<List<string>>();

            var invoiceLines = invoice.GetInvoiceLines();
            var invoiceTaxes = new Dictionary<int, decimal>();

            decimal subtotal = 0;
            decimal discount = 0;
            decimal amount = 0;

            foreach (var line in invoiceLines)
            {
                var item = Global.DaoFactory.GetInvoiceItemDao().GetByID(line.InvoiceItemID);
                var tax1 = line.InvoiceTax1ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax1ID) : null;
                var tax2 = line.InvoiceTax2ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax2ID) : null;

                var subtotalValue = Math.Round(line.Quantity * line.Price, 2);
                var discountValue = Math.Round(subtotalValue * line.Discount / 100, 2);

                var rate = 0;
                if (tax1 != null)
                {
                    rate += tax1.Rate;
                    if (invoiceTaxes.ContainsKey(tax1.ID))
                    {
                        invoiceTaxes[tax1.ID] = invoiceTaxes[tax1.ID] + Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2);
                    }
                    else
                    {
                        invoiceTaxes.Add(tax1.ID, Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2));
                    }
                }
                if (tax2 != null)
                {
                    rate += tax2.Rate;
                    if (invoiceTaxes.ContainsKey(tax2.ID))
                    {
                        invoiceTaxes[tax2.ID] = invoiceTaxes[tax2.ID] + Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2);
                    }
                    else
                    {
                        invoiceTaxes.Add(tax2.ID, Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2));
                    }
                }

                decimal taxValue = Math.Round((subtotalValue - discountValue) * rate / 100, 2);
                decimal amountValue = Math.Round(subtotalValue - discountValue + taxValue, 2);

                subtotal += subtotalValue;
                discount += discountValue;
                amount += amountValue;

                data.TableBodyRows.Add(new List<string>
                    {
                        item.Title + (string.IsNullOrEmpty(line.Description) ? string.Empty : ": " +line.Description),
                        line.Quantity.ToString(CultureInfo.InvariantCulture),
                        line.Price.ToString(CultureInfo.InvariantCulture),
                        line.Discount.ToString(CultureInfo.InvariantCulture),
                        tax1 != null ? tax1.Name : string.Empty,
                        tax2 != null ? tax2.Name : string.Empty,
                        (subtotalValue-discountValue).ToString(CultureInfo.InvariantCulture)
                    });
            }

            data.TableFooterRows = new List<Tuple<string, string>>();
            data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Subtotal", cultureInfo), (subtotal - discount).ToString(CultureInfo.InvariantCulture)));

            foreach (var invoiceTax in invoiceTaxes)
            {
                var iTax = Global.DaoFactory.GetInvoiceTaxDao().GetByID(invoiceTax.Key);
                data.TableFooterRows.Add(new Tuple<string, string>(string.Format("{0} ({1}%)", iTax.Name, iTax.Rate), invoiceTax.Value.ToString(CultureInfo.InvariantCulture)));
            }

            //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture)));

            data.TableTotalRow = new Tuple<string, string>(string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo), invoice.Currency), amount.ToString(CultureInfo.InvariantCulture));


            #endregion


            #region Terms

            data.Terms = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Terms", cultureInfo), invoice.Terms);

            #endregion


            #region Notes

            if (!string.IsNullOrEmpty(invoice.Description))
            {
                data.Notes = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("ClientNotes", cultureInfo), invoice.Description);
            }

            #endregion


            #region Consignee

            var consignee = Global.DaoFactory.GetContactDao().GetByID(invoice.ConsigneeID);

            if (consignee != null)
            {
                sb = new StringBuilder();

                sb.Append(consignee.GetTitle());

                var deliveryAddress = deliveryAddressID != 0 ? Global.DaoFactory.GetContactInfoDao().GetByID(deliveryAddressID) : null;
                if (deliveryAddress != null && deliveryAddress.InfoType == ContactInfoType.Address && deliveryAddress.Category == (int)AddressCategory.Postal)
                {
                    list = new List<string>();

                    var obj = JObject.Parse(deliveryAddress.Data);

                    var str = obj.Value<string>("country");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("state");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("city");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("street");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("zip");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    if (list.Count > 0)
                    {
                        sb.AppendLine();
                        sb.Append(string.Join(", ", list));
                    }
                }

                data.Consignee = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("ShipTo", cultureInfo), sb.ToString());
            }

            #endregion

            #region Addresses

            data.BillingAddressID = billingAddressID;
            data.DeliveryAddressID = deliveryAddressID;

            #endregion

            return data;
        }
예제 #20
0
 public static Dictionary<Guid, string> GetAccessSubjectTo(Invoice invoice)
 {
     return GetAccessSubjectTo((ISecurityObjectId)invoice);
 }
        private Invoice GetInvoice()
        {
            var dao = Global.DaoFactory;

            var invoice = new Invoice();

            if (ActionType == InvoiceActionType.Edit)
            {
                invoice.ID = TargetInvoice.ID;
                invoice.Number = TargetInvoice.Number;
                invoice.FileID = TargetInvoice.FileID;
            }
            else
            {
                invoice.Number = Request["invoiceNumber"];
                if (dao.GetInvoiceDao().IsExist(invoice.Number))
                    throw new Exception(CRMErrorsResource.InvoiceNumberBusy);
            }

            DateTime issueDate;
            if (!DateTime.TryParse(Request["invoiceIssueDate"], out issueDate))
                throw new Exception("invalid issueDate");
            invoice.IssueDate = issueDate;

            invoice.ContactID = Convert.ToInt32(Request["invoiceContactID"]);
            if (invoice.ContactID <= 0) throw new Exception(CRMErrorsResource.InvoiceContactNotFound);
            var contact = dao.GetContactDao().GetByID(invoice.ContactID);
            if (contact == null || !CRMSecurity.CanAccessTo(contact))
            {
                throw new Exception(CRMErrorsResource.InvoiceContactNotFound);
            }

            invoice.ConsigneeID = Convert.ToInt32(Request["invoiceConsigneeID"]);
            if (invoice.ConsigneeID > 0)
            {
                var consignee = dao.GetContactDao().GetByID(invoice.ConsigneeID);
                if (consignee == null || !CRMSecurity.CanAccessTo(consignee))
                {
                    throw new Exception(CRMErrorsResource.InvoiceConsigneeNotFound);
                }
            }
            else
            {
                invoice.ConsigneeID = 0;
            }


            invoice.EntityType = EntityType.Opportunity;

            invoice.EntityID = Convert.ToInt32(Request["invoiceOpportunityID"]);
            if (invoice.EntityID > 0)
            {
                var deal = dao.GetDealDao().GetByID(invoice.EntityID);
                if (deal == null || !CRMSecurity.CanAccessTo(deal))
                    throw new Exception(CRMErrorsResource.DealNotFound);

                var dealMembers = dao.GetDealDao().GetMembers(invoice.EntityID);
                if (!dealMembers.Contains(invoice.ContactID))
                    throw new Exception("contact doesn't have this opportunity");
            }

            DateTime dueDate;
            if (!DateTime.TryParse(Request["invoiceDueDate"], out dueDate))
                throw new Exception(CRMErrorsResource.InvoiceDueDateInvalid);
            if (issueDate > dueDate)
                throw new Exception(CRMErrorsResource.InvoiceIssueMoreThanDue);
            invoice.DueDate = dueDate;

            invoice.Language = Request["invoiceLanguage"];
            if (string.IsNullOrEmpty(invoice.Language) || SetupInfo.EnabledCultures.All(c => c.Name != invoice.Language))
                throw new Exception(CRMErrorsResource.LanguageNotFound);

            invoice.Currency = Request["invoiceCurrency"];
            if (string.IsNullOrEmpty(invoice.Currency))
            {
                throw new Exception(CRMErrorsResource.CurrencyNotFound);
            }
            else
            {
                invoice.Currency = invoice.Currency.ToUpper();
                if (CurrencyProvider.Get(invoice.Currency) == null)
                {
                    throw new Exception(CRMErrorsResource.CurrencyNotFound);
                }
            }

            invoice.ExchangeRate = Convert.ToDecimal(Request["invoiceExchangeRate"], new CultureInfo("en-US"));
            if (invoice.ExchangeRate <= 0)
                throw new Exception(CRMErrorsResource.ExchangeRateNotSet);

            invoice.PurchaseOrderNumber = Request["invoicePurchaseOrderNumber"];

            invoice.Terms = Request["invoiceTerms"];
            if (string.IsNullOrEmpty(invoice.Terms))
                throw new Exception(CRMErrorsResource.InvoiceTermsNotFound);

            invoice.Description = Request["invoiceDescription"];

            invoice.Status = InvoiceStatus.Draft;

            invoice.TemplateType = InvoiceTemplateType.Eur;

            return invoice;
        }
예제 #22
0
 public static List<Guid> GetAccessSubjectGuidsTo(Invoice invoice)
 {
     return GetAccessSubjectGuidsTo((ISecurityObjectId)invoice);
 }
예제 #23
0
        public static ConverterData StartCreationFileAsync(Invoice data)
        {
            using (var docxStream = GetStreamDocx(data))
            {
                var documentService = new DocumentService(StudioKeySettings.GetKey(), StudioKeySettings.GetSKey(), TenantStatisticsProvider.GetUsersCount());
                var revisionId = DocumentService.GenerateRevisionId(Guid.NewGuid().ToString());

                var externalUri = documentService.GetExternalUri(FilesLinkUtility.DocServiceStorageUrl, docxStream, "text/plain", revisionId);

                string urlToFile;
                documentService.GetConvertedUri(FilesLinkUtility.DocServiceConverterUrl, externalUri, FormatDocx, FormatPdf, revisionId, true, out urlToFile);

                return new ConverterData
                    {
                        ConverterUrl = FilesLinkUtility.DocServiceConverterUrl,
                        StorageUrl = externalUri,
                        RevisionId = revisionId,
                        InvoiceId = data.ID,
                        UrlToFile = urlToFile
                    };
            }
        }
예제 #24
0
 public static void DemandAccessTo(Invoice invoice)
 {
     if (!CanAccessTo(invoice)) throw CreateSecurityException();
 }
예제 #25
0
        private static Stream GetStreamDocx(Invoice data)
        {
            var invoiceData = InvoiceFormattedData.GetData(data, 0, 0);
            var logo = new byte[] {};

            if (!string.IsNullOrEmpty(invoiceData.LogoBase64))
            {
                logo = Convert.FromBase64String(invoiceData.LogoBase64);
            }
            else if (invoiceData.LogoBase64Id != 0)
            {
                logo = Convert.FromBase64String(OrganisationLogoManager.GetOrganisationLogoBase64(invoiceData.LogoBase64Id));
            }

            using (var zip = ZipFile.Read(TemplatePath))
            {
                var documentXmlStream = new MemoryStream();
                foreach (var entry in zip.Entries.Where(entry => entry.FileName == DocumentXml))
                {
                    entry.Extract(documentXmlStream);
                }
                documentXmlStream.Position = 0;
                zip.RemoveEntry(DocumentXml);
                var document = new XmlDocument();
                document.Load(documentXmlStream);
                var documentStr = GenerateDocumentXml(document, invoiceData, logo);
                zip.AddEntry(DocumentXml, documentStr, Encoding.UTF8);

                if (logo.Length > 0)
                {
                    zip.UpdateEntry(DocumentLogoImage, logo);
                }

                var streamZip = new MemoryStream();
                zip.Save(streamZip);
                streamZip.Seek(0, SeekOrigin.Begin);
                streamZip.Flush();
                return streamZip;
            }

        }
예제 #26
0
 public static void DemandEdit(Invoice invoice)
 {
     if (!CanEdit(invoice)) throw CreateSecurityException();
 }
예제 #27
0
        private int SaveOrUpdateInvoice(Invoice invoice, DbManager db)
        {
            if (String.IsNullOrEmpty(invoice.Number) ||
                invoice.IssueDate == DateTime.MinValue ||
                invoice.ContactID <= 0 ||
                invoice.DueDate == DateTime.MinValue ||
                String.IsNullOrEmpty(invoice.Currency) ||
                invoice.ExchangeRate <= 0 ||
                String.IsNullOrEmpty(invoice.Terms))
                throw new ArgumentException();


            if (!IsExist(invoice.ID, db))
            {
                if (IsExist(invoice.Number, db))
                    throw new ArgumentException();

                invoice.ID = db.ExecuteScalar<int>(
                               Insert("crm_invoice")
                              .InColumnValue("id", 0)
                              .InColumnValue("status", (int)invoice.Status)
                              .InColumnValue("number", invoice.Number)
                              .InColumnValue("issue_date", TenantUtil.DateTimeToUtc(invoice.IssueDate))
                              .InColumnValue("template_type", invoice.TemplateType)
                              .InColumnValue("contact_id", invoice.ContactID)
                              .InColumnValue("consignee_id", invoice.ConsigneeID)
                              .InColumnValue("entity_type", (int)invoice.EntityType)
                              .InColumnValue("entity_id", invoice.EntityID)
                              .InColumnValue("due_date", TenantUtil.DateTimeToUtc(invoice.DueDate))
                              .InColumnValue("language", invoice.Language)
                              .InColumnValue("currency", invoice.Currency)
                              .InColumnValue("exchange_rate", invoice.ExchangeRate)
                              .InColumnValue("purchase_order_number", invoice.PurchaseOrderNumber)
                              .InColumnValue("terms", invoice.Terms)
                              .InColumnValue("description", invoice.Description)
                              .InColumnValue("json_data", null)
                              .InColumnValue("file_id", 0)
                              .InColumnValue("create_on", DateTime.UtcNow)
                              .InColumnValue("create_by", SecurityContext.CurrentAccount.ID)
                              .InColumnValue("last_modifed_on", DateTime.UtcNow)
                              .InColumnValue("last_modifed_by", SecurityContext.CurrentAccount.ID)
                              .Identity(1, 0, true));
            }
            else
            {

                var oldInvoice = db.ExecuteList(GetInvoiceSqlQuery(Exp.Eq("id", invoice.ID), null))
                    .ConvertAll(ToInvoice)
                    .FirstOrDefault();

                CRMSecurity.DemandEdit(oldInvoice);

                if (oldInvoice.ContactID != invoice.ContactID) {
                    oldInvoice.FileID = 0;
                }

                db.ExecuteNonQuery(
                    Update("crm_invoice")
                        .Set("status", (int) invoice.Status)
                        .Set("issue_date", TenantUtil.DateTimeToUtc(invoice.IssueDate))
                        .Set("template_type", invoice.TemplateType)
                        .Set("contact_id", invoice.ContactID)
                        .Set("consignee_id", invoice.ConsigneeID)
                        .Set("entity_type", (int) invoice.EntityType)
                        .Set("entity_id", invoice.EntityID)
                        .Set("due_date", TenantUtil.DateTimeToUtc(invoice.DueDate))
                        .Set("language", invoice.Language)
                        .Set("currency", invoice.Currency)
                        .Set("exchange_rate", invoice.ExchangeRate)
                        .Set("purchase_order_number", invoice.PurchaseOrderNumber)
                        .Set("terms", invoice.Terms)
                        .Set("description", invoice.Description)
                        .Set("json_data", null)
                        .Set("file_id", oldInvoice.FileID)
                        .Set("last_modifed_on", DateTime.UtcNow)
                        .Set("last_modifed_by", SecurityContext.CurrentAccount.ID)
                        .Where(Exp.Eq("id", invoice.ID)));
            }

            return invoice.ID;
        }
예제 #28
0
 public static void DemandDelete(Invoice invoice)
 {
     if (!CanDelete(invoice)) throw CreateSecurityException();
 }
예제 #29
0
        public static void DemandCreateOrUpdate(Invoice invoice)
        {
            if (invoice.IssueDate == DateTime.MinValue ||
                invoice.ContactID <= 0 ||
                invoice.DueDate == DateTime.MinValue ||
                String.IsNullOrEmpty(invoice.Currency) ||
                invoice.ExchangeRate <= 0 ||
                String.IsNullOrEmpty(invoice.Terms) ||
                String.IsNullOrEmpty(invoice.Currency))
                    throw new ArgumentException();

            var contact = Global.DaoFactory.GetContactDao().GetByID(invoice.ContactID);
            if (contact == null) throw new ArgumentException();
            DemandAccessTo(contact);

            if (invoice.ConsigneeID != 0 && invoice.ConsigneeID != invoice.ContactID)
            {
                var consignee = Global.DaoFactory.GetContactDao().GetByID(invoice.ConsigneeID);
                if (consignee == null) throw new ArgumentException();
                DemandAccessTo(consignee);
            }

            if (invoice.EntityID != 0)
            {
                var deal = Global.DaoFactory.GetDealDao().GetByID(invoice.EntityID);
                if (deal == null) throw new ArgumentException();
                DemandAccessTo(deal);

                var dealMembers = Global.DaoFactory.GetDealDao().GetMembers(invoice.EntityID);
                if (!dealMembers.Contains(invoice.ContactID))
                    throw new ArgumentException();
            }

            if (CurrencyProvider.Get(invoice.Currency.ToUpper()) == null)
            {
                throw new ArgumentException();
            }
        }
        public static void DataInvoicesActionView(BasePage page, Invoice targetInvoice)
        {
            var invoiceItems = Global.DaoFactory.GetInvoiceItemDao().GetAll();
            var invoiceItemsJson = JsonConvert.SerializeObject(invoiceItems.ConvertAll(item => new
                {
                    id = item.ID,
                    title = item.Title,
                    stockKeepingUnit = item.StockKeepingUnit,
                    description = item.Description,
                    price = item.Price,
                    quantity = item.Quantity,
                    stockQuantity = item.StockQuantity,
                    trackInventory = item.TrackInventory,
                    invoiceTax1ID = item.InvoiceTax1ID,
                    invoiceTax2ID = item.InvoiceTax2ID
                }));

            var invoiceTaxes = Global.DaoFactory.GetInvoiceTaxDao().GetAll();
            var invoiceTaxesJson = JsonConvert.SerializeObject(invoiceTaxes.ConvertAll(item => new
                {
                    id = item.ID,
                    name = item.Name,
                    rate = item.Rate,
                    description = item.Description
                }));

            var invoiceSettings = Global.TenantSettings.InvoiceSetting ?? InvoiceSetting.DefaultSettings;
            var invoiceSettingsJson = JsonConvert.SerializeObject(new
                {
                    autogenerated = invoiceSettings.Autogenerated,
                    prefix = invoiceSettings.Prefix,
                    number = invoiceSettings.Number,
                    terms = invoiceSettings.Terms
                });

            var presetContactsJson = string.Empty;
            var presetContactID = UrlParameters.ContactID;
            if (targetInvoice == null && presetContactID != 0)
            {
                var targetContact = Global.DaoFactory.GetContactDao().GetByID(presetContactID);
                if (targetContact != null)
                {
                    presetContactsJson = JsonConvert.SerializeObject(new
                    {
                        id = targetContact.ID,
                        displayName = targetContact.GetTitle().HtmlEncode().ReplaceSingleQuote(),
                        smallFotoUrl = ContactPhotoManager.GetSmallSizePhoto(targetContact.ID, targetContact is Company),
                        currencyAbbreviation = targetContact.Currency
                    });
                }
            }

            var currencyRates = Global.DaoFactory.GetCurrencyRateDao().GetAll();
            var currencyRatesJson = JsonConvert.SerializeObject(currencyRates.ConvertAll(item => new
            {
                id = item.ID,
                fromCurrency = item.FromCurrency,
                toCurrency = item.ToCurrency,
                rate = item.Rate
            }));

            var apiServer = new Api.ApiServer();
            const string apiUrlFormat = "{0}crm/contact/{1}/data.json";

            var contactInfoData = string.Empty;
            var consigneeInfoData = string.Empty;
            
            if(targetInvoice != null)
            {
                if (targetInvoice.ContactID > 0)
                {
                    contactInfoData = apiServer.GetApiResponse(String.Format(apiUrlFormat, SetupInfo.WebApiBaseUrl, targetInvoice.ContactID), "GET");
                }
                if (targetInvoice.ConsigneeID > 0)
                {
                    consigneeInfoData = apiServer.GetApiResponse(String.Format(apiUrlFormat, SetupInfo.WebApiBaseUrl, targetInvoice.ConsigneeID), "GET");
                }
            } else if (presetContactID != 0)
            {
                contactInfoData = apiServer.GetApiResponse(String.Format(apiUrlFormat, SetupInfo.WebApiBaseUrl, presetContactID), "GET");
            }

            var apiUrl = String.Format("{0}crm/invoice/{1}.json",
                                       SetupInfo.WebApiBaseUrl,
                                       targetInvoice != null ? targetInvoice.ID.ToString(CultureInfo.InvariantCulture) : "sample");
            var invoiceData = apiServer.GetApiResponse(apiUrl, "GET");

            var script = String.Format(@"
                                        var invoiceItems = '{0}';
                                        var invoiceTaxes = '{1}';
                                        var invoiceSettings = '{2}';
                                        var invoicePresetContact = '{3}';
                                        var currencyRates = '{4}';
                                        var invoiceJsonData = '{5}'; ",
                                       Global.EncodeTo64(invoiceItemsJson),
                                       Global.EncodeTo64(invoiceTaxesJson),
                                       Global.EncodeTo64(invoiceSettingsJson),
                                       Global.EncodeTo64(presetContactsJson),
                                       Global.EncodeTo64(currencyRatesJson),
                                       targetInvoice != null ? Global.EncodeTo64(targetInvoice.JsonData) : ""
                );

            page.RegisterInlineScript(script, onReady: false);
            page.JsonPublisher(contactInfoData, "invoiceContactInfo");
            page.JsonPublisher(consigneeInfoData, "invoiceConsigneeInfo");
            page.JsonPublisher(invoiceData, "invoice");
        }