c# - Quickbooks 在线会计 - 如何在发票中添加多个行项目?

标签 c# quickbooks-online

使用以下代码,我想创建多个行项目以显示在新发票中。

如何在发票中创建与自定义应用程序中的多个订单项目相对应的多个行项目?

对订单中有 4 个项目的 OrderItems 运行以下代码,仅显示发票中的一项。价格和名称正确,但产品数量不正确。只有一个出现。

我相信此行是添加订单项的正确行。但它实际上添加了订单项吗?

invoice.Line = new Line[] { invoiceLine };

代码

var orderItems = order.OrderItems;

foreach (var orderItem in orderItems)
{
    //Line
    Line invoiceLine = new Line();

    //Line Description
    invoiceLine.Description = itemRepository.Get(i=>i.ItemID == orderItem.ItemID).First().FullDescription;

    //Line Amount
    invoiceLine.Amount = orderItem.Price * orderItem.Quantity;
    invoiceLine.AmountSpecified = true;

    //Line Detail Type
    invoiceLine.DetailType = LineDetailTypeEnum.SalesItemLineDetail;
    invoiceLine.DetailTypeSpecified = true;

    //Line Sales Item Line Detail
    SalesItemLineDetail lineSalesItemLineDetail = new SalesItemLineDetail();

    //Line Sales Item Line Detail - ItemRef
    lineSalesItemLineDetail.ItemRef = new ReferenceType()
    {
        name = itemRepository.Get(
            i=>i.ItemID == orderItem.ItemID).First().FullDescription,
            Value = item.Id
    };

    //Line Sales Item Line Detail - UnitPrice
    lineSalesItemLineDetail.AnyIntuitObject = orderItem.Price;//33m;
    lineSalesItemLineDetail.ItemElementName = ItemChoiceType.UnitPrice;

    //Line Sales Item Line Detail - Qty
    lineSalesItemLineDetail.Qty = orderItem.Quantity;//10;
    lineSalesItemLineDetail.QtySpecified = true;

    //Line Sales Item Line Detail - TaxCodeRef
    //For US companies, this can be 'TAX' or 'NON
    lineSalesItemLineDetail.TaxCodeRef = new ReferenceType()
    {
        Value = "TAX"
    };

    //Line Sales Item Line Detail - ServiceDate 
    lineSalesItemLineDetail.ServiceDate = DateTime.Now.Date;
    lineSalesItemLineDetail.ServiceDateSpecified = true;

    //Assign Sales Item Line Detail to Line Item
    invoiceLine.AnyIntuitObject = lineSalesItemLineDetail;

    //Assign Line Item to Invoice
    invoice.Line = new Line[] { invoiceLine };

}

编辑:

OAuthRequestValidator reqValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerKeySecret);
            ServiceContext qboContextoAuth = new ServiceContext(realmId, IntuitServicesType.QBO, reqValidator);
            var service = new DataService(qboContextoAuth);

            //Find Customer
            var customerQueryService = new QueryService<Customer>(qboContextoAuth);
            Customer customer = customerQueryService.ExecuteIdsQuery("Select * From Customer Where DisplayName = 'John Doe' StartPosition 1 MaxResults 1").FirstOrDefault();

            //Find Tax Code for Invoice - Searching for a tax code named 'StateSalesTax' in this example
            var stateTaxCodeQueryService = new QueryService<TaxCode>(qboContextoAuth);
            TaxCode stateTaxCode = stateTaxCodeQueryService.ExecuteIdsQuery("Select * From TaxCode Where Name='Los Angeles' StartPosition 1 MaxResults 1").FirstOrDefault();

            //Find Item
            var itemQueryService = new QueryService<Item>(qboContextoAuth);
            Item item = itemQueryService.ExecuteIdsQuery("Select * From Item StartPosition 1").FirstOrDefault();


            //Find Account - Accounts Receivable account required
            var accountQueryService = new QueryService<Account>(qboContextoAuth);
            Account account = accountQueryService.ExecuteIdsQuery("Select * From Account Where AccountType='Accounts Receivable' StartPosition 1 MaxResults 1").FirstOrDefault();

            //Find Term
            var termQueryService = new QueryService<Term>(qboContextoAuth);
            Term term = termQueryService.ExecuteIdsQuery("Select * From Term StartPosition 1 MaxResults 1").FirstOrDefault();

            Invoice invoice = new Invoice();

            //DocNumber - QBO Only, otherwise use DocNumber
            invoice.AutoDocNumber = true;
            invoice.AutoDocNumberSpecified = true;

            //TxnDate
            invoice.TxnDate = DateTime.Now.Date;
            invoice.TxnDateSpecified = true;

            //PrivateNote
            invoice.PrivateNote = "This is a private note";


            var orderItems = order.OrderItems;

            int idx = 0;

            var lines = new List<Line>();

            foreach (var orderItem in orderItems)
            {
                //Line
                Line invoiceLine = new Line();
                //Line Description
                invoiceLine.Description = itemRepository.Get(i => i.ItemID == orderItem.ItemID).First().FullDescription;
                //Line Amount
                invoiceLine.Amount = orderItem.Price * orderItem.Quantity;
                invoiceLine.AmountSpecified = true;
                //Line Detail Type
                invoiceLine.DetailType = LineDetailTypeEnum.SalesItemLineDetail;
                invoiceLine.DetailTypeSpecified = true;
                //Line Sales Item Line Detail


                SalesItemLineDetail lineSalesItemLineDetail = new SalesItemLineDetail();


                //Line Sales Item Line Detail - ItemRef
                lineSalesItemLineDetail.ItemRef = new ReferenceType()
                {
                    name = itemRepository.Get(i => i.ItemID == orderItem.ItemID).First().FullDescription,
                    Value = (idx + 1).ToString()
                };
                //Line Sales Item Line Detail - UnitPrice
                lineSalesItemLineDetail.AnyIntuitObject = orderItem.Price;//33m;
                lineSalesItemLineDetail.ItemElementName = ItemChoiceType.UnitPrice;
                //Line Sales Item Line Detail - Qty
                lineSalesItemLineDetail.Qty = orderItem.Quantity;//10;
                lineSalesItemLineDetail.QtySpecified = true;
                //Line Sales Item Line Detail - TaxCodeRef
                //For US companies, this can be 'TAX' or 'NON

                lineSalesItemLineDetail.TaxCodeRef = new ReferenceType()
                {
                    Value = "TAX"
                };
                //Line Sales Item Line Detail - ServiceDate 
                lineSalesItemLineDetail.ServiceDate = DateTime.Now.Date;
                lineSalesItemLineDetail.ServiceDateSpecified = true;
                //Assign Sales Item Line Detail to Line Item
                invoiceLine.AnyIntuitObject = lineSalesItemLineDetail;
                //Assign Line Item to Invoice
                //invoice.Line = new Line[] { invoiceLine };
                lines.Add(invoiceLine);

                //TxnTaxDetail
                TxnTaxDetail txnTaxDetail = new TxnTaxDetail();
                txnTaxDetail.TxnTaxCodeRef = new ReferenceType()
                {
                    name = stateTaxCode.Name,
                    Value = stateTaxCode.Id
                };
                Line taxLine = new Line();
                taxLine.DetailType = LineDetailTypeEnum.TaxLineDetail;
                TaxLineDetail taxLineDetail = new TaxLineDetail();
                //Assigning the fist Tax Rate in this Tax Code
                taxLineDetail.TaxRateRef = stateTaxCode.SalesTaxRateList.TaxRateDetail[0].TaxRateRef;
                taxLine.AnyIntuitObject = taxLineDetail;
                txnTaxDetail.TaxLine = new Line[] { taxLine };
                invoice.TxnTaxDetail = txnTaxDetail;

                idx++;
            }
            //Customer (Client)
            invoice.CustomerRef = new ReferenceType()
            {
                name = customer.DisplayName,
                Value = customer.Id
            };
            var _user = userRepository.Get(u => u.UserID == order.CreatedUserID, includeProperties: "ContactMethod, ContactMethod.Addresses, Location, Location.Organization").FirstOrDefault();

            if (_user != null)
            {
                var addresses = _user.ContactMethod.Addresses.Where(a => a.StatusCode == Convert.ToByte(StatusCodes.Active) && a.IsPrimary).ToList();


                var _billingAddress = addresses.Where(a => a.AddressTypeId == Convert.ToByte(AddressTypes.Billing)).FirstOrDefault();
                var _shippingAddress = addresses.Where(a => a.AddressTypeId == Convert.ToByte(AddressTypes.Shipping)).FirstOrDefault();


                //Billing Address
                PhysicalAddress billAddr = new PhysicalAddress();
                billAddr.Line1 = _billingAddress.Address1;
                billAddr.Line2 = _billingAddress.Address2;
                billAddr.City = _billingAddress.City;
                billAddr.CountrySubDivisionCode = _billingAddress.State;
                billAddr.Country = _billingAddress.Country;
                billAddr.PostalCode = _billingAddress.ZipCode;
                billAddr.Note = "Billing Address Note";
                invoice.BillAddr = billAddr;

                //Shipping Address
                PhysicalAddress shipAddr = new PhysicalAddress();
                shipAddr.Line1 = _shippingAddress.Address1;
                shipAddr.City = _shippingAddress.City;
                shipAddr.CountrySubDivisionCode = _shippingAddress.City;
                shipAddr.Country = _shippingAddress.Country;
                shipAddr.PostalCode = _shippingAddress.ZipCode;
                shipAddr.Note = "Shipping Address Note";
                invoice.ShipAddr = shipAddr;

            }

            invoice.Line = lines.ToArray();

            //SalesTermRef
            invoice.SalesTermRef = new ReferenceType()
            {
                name = term.Name,
                Value = term.Id
            };

            //DueDate
            invoice.DueDate = DateTime.Now.AddDays(30).Date;
            invoice.DueDateSpecified = true;

            //ARAccountRef
            invoice.ARAccountRef = new ReferenceType()
            {
                name = account.Name,
                Value = account.Id
            };

            Invoice invoiceAdded = service.Add(invoice);

            return invoiceAdded;

最佳答案

当前每次循环执行此行时

invoice.Line = new Line[] { invoiceLine };

它通过分配一个新数组来覆盖以前的值。一旦存在基于您当前代码的订单商品,数组中将始终存在一项。

将行存储在列表中,然后在处理所有订单项后转换为数组。

var orderItems = order.OrderItems;
var lines = new List<Line>();
foreach (var orderItem in orderItems) {
    //Line
    Line invoiceLine = new Line();

    //...code removed for brevity

    lines.Add(invoiceLine);
}    
//Assign Line Items to Invoice
invoice.Line = lines.ToArray();

或者另一个选项是在创建订单项之前创建数组并在创建订单项时填充它。

var orderItems = order.OrderItems;
var lineCount = orderItems.Count();
//Creating Line array before
invoice.Line = new Line[lineCount];   
for (int index = 0; index < lineCount; index++) {
    //Order item
    var orderItem = orderItems[index];
    //Line
    Line invoiceLine = new Line();

    //...code removed for brevity

    //Assign Line Item to Invoice
    invoice.Line[index] = invoiceLine;
}   

更新:

获取项目引用并设置必要的值

var itemRef = itemRepository.Get(i => i.ItemID == orderItem.ItemID).FirstOrDefault();
if (itemRef != null) {
    //Line Sales Item Line Detail - ItemRef
    lineSalesItemLineDetail.ItemRef = new ReferenceType() {
        Name = itemRef.FullDescription,
        Value = itemRef.ItemID 
    };
}

关于c# - Quickbooks 在线会计 - 如何在发票中添加多个行项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45174403/

相关文章:

c# - 调整子项大小时保持滚动查看器的相对滚动条偏移量

intuit-partner-platform - 无法使用 .NET SDK 将 TaxService 添加到 QBO

c# - 为什么不能从扩展类型的基类中调用扩展方法?

c# - 如何根据切换按钮的状态放置工具提示,WPF

php - Foreach 循环不会将 Quickbooks 中的所有记录插入 MySQL 数据库。

asp.net - 将 ASP.NET 应用程序连接到 QuickBooks Online Edition

php - 如何使用 QuickBooks_IPP 显示发票中一行中的每个项目?

asp.net - Intuit 合作伙伴平台 (IPP) QuickBooks Online (QBO) BlueDot Menu ASPX 页面未在 Internet Explorer (IE) 中呈现

c# - Stopwatch.Frequency 在同一台 PC 上的不同值

c# - ScriptResource.axd 没有加载到 asp.net 中? 500 URL 重写模块错误