Xero Api - Expense Mark as Paid - xero-api

Using Xero.Api for Xero accounting, I am looking to update expenses from Authorised to Paid. At present, I am getting the following error:
"Invalid status change. An expense claim with status 'AUTHORISED', cannot be updated to have the status 'PAID'"
Is this possible to do through the API, if so what are the minimum field changes so this is processed?
Many thanks.
public static void SetExpensePaid(Xero.Api.Example.Applications.Private.Core api,List<Guid> guids)
{
var account = api.Accounts.Find();
var bank = account.Where(x => x.Name == "Bank").FirstOrDefault();
foreach (var g in guids)
{
var exp =api.ExpenseClaims.Find(g);
var amount = exp.AmountDue;
exp.AmountPaid = amount;
exp.AmountDue = 0;
exp.Status = Xero.Api.Core.Model.Status.ExpenseClaimStatus.Paid;
Payment payment = new Payment()
{
Account = bank,
BankAmount = (decimal?)amount,
Date = DateTime.Today,
IsReconciled = false,
Amount = (decimal?)amount
};
api.Payments.Create(payment);
exp.Payments.Add(payment);
api.ExpenseClaims.Update(exp);
}
}

For anyone else wondering, managed to get a response from Xero....
Normally, for invoices or credit notes, you need to make full payments to them using the Payments endpoint to mark them as PAID.
Unfortunately, you cannot pay an expense claim via the Xero API at this time. Payment needs to be done in the Xero app.
https://developer.xero.com/documentation/api/expense-claims#POST
So can't be done at present.

Related

multi store, manual activation account with prestashop

I use multi-store option with prestashop. I would like to pass customers in the second store to manual activation after registration.
Actually I set $customer->active = 0; in authentication.php.
all registration customer in both websites are inactive after registration.
Is there a way to set $customer->active = 0; just for one website.
I think to get shop_id but I don't know how to develop my idea.
In Prestashop 1.6 :
You can get the id_shop with the Context object.
So, I think you can do something like this :
If you know the id_shop (suppose the id_shop = 1)
if (Context::getContext()->shop->id == 1) {
$customer->active = 0;
} else {
$customer->active = 1;
}
Hope it helps.
EDIT
Updated answer to get the id_shop from context because the Customer object doesn't handle it until it's added.
RE-EDIT
In the Customer class (/classes/Customer.php) customize the add() function.
Add this line around the line 212 (after the "last_passwd_gen" declaration) :
$this->active = ($this->id_shop == 3) ? false : true;
But the best solution for you is to create an override of the function.

How can check history information for a certain customer by using scripting in NetSuite?

I want to create a Script in NetSuite which needs some history information from a customer. In fact the information I need is to know if the user has purchased an item.
For this, I would need in some way to access to the history of this customer.
Pablo.
Try including this function and passing customer's internalID and item internalID
function hasPurchasedBefore(customerInternalID, itemInternalID){
var results = [];
var filters = [];
var columns = [];
filters.push(new nlobjSearchFilter('internalidnumber', 'customermain', 'equalto', [customerInternalID]))
filters.push(new nlobjSearchFilter('anylineitem', null, 'anyof', [itemInternalID]));
filters.push(new nlobjSearchFilter('type', null, 'anyof', ['CustInvc']));
columns.push(new nlobjSearchColumn('internalid', null, 'GROUP'));
results = nlapiSearchRecord('transaction', null, filters, columns);
if (results && results.length){
return true;
}
return false;
}
Example:
var record = nlapiLoadRecord(nlapiGetRecordType(),nlapiGetRecordId());
var customerInternalID = record.getFieldValue('entity');
var itemInternalID = record.getLineItemValue('item', 'item', 1); //Gets line 1 item Internal ID
if( hasPurchasedBefore(customerInternalID, itemInternalID) ) {
//Has bought something before
}
You could use a saved search nlapiLoadSearch or nlapiCreateSearch for invoices, filtered by customer, and also reporting invoice items (or just a particular item). Using nlapiCreateSearch can be tricky to use, so I'd recommend building the saved search using the UI, then load it using nlapiLoadSeach(type, id)
This will give you an array of invoices/customers that bought your item.

Error while creating sales order using JCO with BAPI_SALESORDER_CREATEFROMDAT2

I am trying to create a sales order using BAPI_SALESORDER_CREATEFROMDAT2 butI am getting error “No customer master record exists for customer 99” when I tried to create a sales order for customer 99(example) with the partner Role ‘AG’,’WE’ where both ‘sold-to-party and ship-to-party’ are mandatory fields.
If I send “SP” it will ask me to define ‘sold-to-party and ship-to-party’ ,Please let me know if I have to send some different partner roles to be able to create a sales order.
public static void createSalesOrder() {
try {
JCoDestination destination = JCoDestinationManager.getDestination("ABAP_AS_WITH_POOL");
JCoFunction functionCreateOrder = destination.getRepository().getFunction("BAPI_SALESORDER_CREATEFROMDAT2");
JCoFunction functionTransComit = destination.getRepository().getFunction("BAPI_TRANSACTION_COMMIT");
JCoStructure orderHeaderIn = functionCreateOrder.getImportParameterList().getStructure("ORDER_HEADER_IN");
orderHeaderIn.setValue("SALES_ORG", "2000");
orderHeaderIn.setValue("DISTR_CHAN", "20");
orderHeaderIn.setValue("DIVISION", "20");
orderHeaderIn.setValue("DOC_TYPE", "ZAR");
JCoTable orderPartners = functionCreateOrder.getTableParameterList().getTable("ORDER_PARTNERS");
// WE,AG,SP,PH
// AG Sold to Party
// WE Ship to Party
orderPartners.appendRows(1);
orderPartners.setValue("PARTN_ROLE", "AG");
orderPartners.setValue("PARTN_NUMB", "99");
orderPartners.appendRows(1);
orderPartners.setValue("PARTN_ROLE", "WE");
orderPartners.setValue("PARTN_NUMB", "99");
System.out.println(orderPartners);
JCoTable orderItemsIn = functionCreateOrder.getTableParameterList().getTable("ORDER_ITEMS_IN");
orderItemsIn.appendRow();
orderItemsIn.setValue("MATERIAL", "PEN_ARN");
System.out.println(orderItemsIn);
JCoTable orderSchedulesIn = functionCreateOrder.getTableParameterList().getTable("ORDER_SCHEDULES_IN");
orderSchedulesIn.appendRow();
orderSchedulesIn.setValue("REQ_QTY", "1");
System.out.println(orderSchedulesIn);
functionCreateOrder.execute(destination);
functionTransComit.execute(destination);
// System.out.println(functionCreateOrder);
JCoTable returnTable = functionCreateOrder.getTableParameterList().getTable("RETURN");
System.out.println(returnTable.getString("MESSAGE"));
System.out.println("sales order number is : "
+ functionCreateOrder.getExportParameterList().getValue("SALESDOCUMENT"));
} catch (JCoException ex) {
System.out.println(ex.getMessage());
} finally {
System.out.println("Creating sales order ends");
}
}
Issue was with the partner number , adding 000000000 leading the partner number will solve the issue .

CRM 2013 Updating the Quote Product section

Has anyone tried to create a plugin that updates the record's values in the Quote Product form? I created one, because I need a custom formula that calculates the Extended Amount field, but there are automatic calculations in the CRM that fill these fields. This doesn't allow me to update the formula of calculation at all.
What my plugin do, is:
Gets the values from the fields Price per unit, Quantity and Discount % (which is a custom field);
Calculates the value that I need;
Sets it at the extended amount field.
But, none of this works because I get a "Business Process Error";
Basically this error tells me that I can't use the record's guid to access it.
Here is my code:
protected void ExecutePostQuoteProductUpdate(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
Guid quoteProductID = (Guid)((Entity)context.InputParameters["Target"]).Id;
ColumnSet set = new ColumnSet();
set.AllColumns = true;
var quote = service.Retrieve("quotedetail", quoteProductID, set);
var priceperunit = quote.Attributes["priceperunit"];
var teamleader = quote.Attributes["new_disc"];
var manualdiscountamount = quote.Attributes["manualdiscountamount"];
var volumediscountamount = quote.Attributes["volumediscountamount"];
var VAT = (int)quote.Attributes["new_vat"];
var discountamount = (double)priceperunit * (double)teamleader / 100;
var baseamount = (double)priceperunit - discountamount;
var tax = baseamount * VAT / 100;
var extendedamount = baseamount + tax;
quote.Attributes["new_discountamount"] = discountamount;
quote.Attributes["baseamount"] = baseamount;
quote.Attributes["tax"] = tax;
quote["description"] = priceperunit;
quote.Attributes["extendedamount"] = extendedamount;
service.Update(quote);
}
Please, tell me if there is a way to access those fields and use/set them.
Thanks in Advance!
:/
You cannot update extendedamount directly - instead if you use the built-in fields which automatically calculate it then CRM will take care of this for you.
Those fields are: baseamount, quantity, discountamount, and tax. These are Money fields so you will need to store them as such:
quote.Attributes["baseamount"] = new Money(baseamount); // Money and decimal numbers use the "decimal" datatype and not double.
As for your custom calculation, you just need to convert the percentage stored in your custom field into the actual amount and assign it to the discountamount attribute. Something like:
var discountamount = (decimal)priceperunit * (decimal)teamleader / 100;
// Assigning the actual discount amount will automatically recalculate the extended amount on the line.
// No need to recalculate all fields.
quote.Attributes["discountamount"] = new Money(discountamount);
Note that tax may need to be recalculated to reflect the discount, but the process should work exactly the same.

Creating Invoice & Capturing on Shipment

We've got some API integrations that will periodically create shipments for orders.
What I'd like to do is create an observer to also create an appropriate invoice & capture payment when this shipment is created. I have this tied to sales_order_shipment_save_after:
public function autoInvoice($observer){
$shipment = $observer->getEvent()->getShipment();
$order = $shipment->getOrder();
$items = $shipment->getItemsCollection();
$qty = array();
foreach($items as $item)
$qty[$item['order_item_id']] = $item['qty'];
$invoice = Mage::getModel('sales/order_invoice_api');
$invoiceId = $invoice->create($order->getIncrementId(), $qty);
$invoice->capture($invoiceId);
}
(The code for the actual capture is somewhat naive, but bear with me.)
What's strange is that this code works just fine -- the shipment is created, the invoice is created and marked as 'Paid.' However, the order itself stays in limbo and retains a status 'Pending.'
Looking into it further, the items on the order itself have the correct quantities for both Ordered and Shipped, but there's no listing of the quantity Invoiced. I think this is what's causing the status hangup. It's as though the qty_invoiced on the sales_order_item table is getting reverted somehow.
Again, the Invoice shows the right items, so I'm quite confused here.
Any ideas?
This is indeed a very interesting one #bahoo.
maybe try:
$shipment = $observer->getEvent()->getShipment();
$order = $shipment->getOrder();
$qty = array();
$invoice = Mage::getModel('sales/order_invoice_api');
$invoiceId = $invoice->create($order->getIncrementId(), $qty);
$invoice->capture($invoiceId);
After lots of testing using the API, I found if I created the invoice first, then the shipment, Magento Enterprise 1.13.01. would correctly set the order status to Complete. Trying to make the shipment first, then the invoice, would result in the Pending Order status remaining even if all items had been invoiced and shipped.
The bridging system code below uses information about orders placed in Magento, routed to the bridging system via an Observer on checkout_submit_all_after, sent to NetSuite via web services, and fulfilled in NetSuite. The bridging system gets sales order fulfillments from NetSuite via web service, and saves items shipped, package, and tracking information, to use in the code below.
Code shows creating invoice, then shipment and tracking.
Note that while testing, I just saw Magento incorrectly create an invoice for all three items in an order, even though it was passed an array that just contained two of the items. Magento did correctly create a shipment record for just the two items. Puzzling that the invoice API and the shipment API when passed the same array of items and quantities have such different behavior. Anyone else seen this?
$proxy = new SoapClient($proxyUrl); /* V2 version */
$sessionId = $proxy->login($apiUser, $apiKey);
try
{ /* try to create invoice in Magento */
$invoiceIncrementId = $proxy->salesOrderInvoiceCreate($sessionId, $orderIncrementId, $shipItemsQty, 'invoice created', false, false);
}
catch( SoapFault $fault )
{
$error = $fault->getMessage(); /* will return 'Cannot do invoice for order' if invoice already exists for these items */
}
if (!stristr($error,'Cannot do invoice') and !empty($error))
{ /* some other invoicing problem, log what returned, on to next order */
$ins = "insert into order_error_log values(NULL, ".$orderId.", '".date("Y-m-d H:i:s")."', '".$program."', '".$error."')";
$result = $mysqli->query($ins);
$upd = "update orders set orderStatusId = ".ERROR_ADDING_MAGENTO_INVOICE.",
dateStatusUpdated = '".date("Y-m-d H:i:s")."'
where id = ".$orderId;
$result = $mysqli->query($upd);
continue;
}
if ((stristr($error,'Cannot do invoice') or empty($error)) and $complete)
{ /* if all fulfilled, may change status */
$upd = "update orders set orderStatusId = ".STORE_INVOICE_CREATED.",
dateStatusUpdated = '".date("Y-m-d H:i:s")."'
where id = ".$orderId;
$result = $mysqli->query($upd);
}
/* send Magento salesOrderShipmentCreate and get returned shipment Id, re-using proxy login and session */
$comment = 'Fulfillment(s) shipped on: '.$netsuiteShipDate;
try
{ /* returns value such as string(9) "100002515" */
$shipmentIncrementId = $proxy->salesOrderShipmentCreate($sessionId, $orderIncrementId, $shipItemsQty, $comment);
}
catch( SoapFault $fault )
{
$error = $fault->getMessage().': SOAP error received when trying to add shipment to Magento for morocco order id '.$orderId.
' store order id '.$orderIncrementId.' with items qty array of: '.var_dump($itemsQty);
$ins = "insert into order_error_log values(NULL, ".$orderId.", '".date("Y-m-d H:i:s")."', '".$program."', '".$error."')";
$result = $mysqli->query($ins);
$upd = "update orders set orderStatusId = ".MAGENTO_SOAP_EXCEPTION.",
dateStatusUpdated = '".date("Y-m-d H:i:s")."'
where id = ".$orderId;
$result = $mysqli->query($upd);
continue; /* on to next order */
}
/* Using that shipmentId, send info re each package shipped for these fulfillments to Magento via salesOrderShipmentAddTrack. */
foreach ($packageIds as $packageId => $package)
{
try
{
$trackingNumberId = $proxy->salesOrderShipmentAddTrack($sessionId, $shipmentIncrementId,
$package['carrier'], 'tracking number', $package['trackNumber']);
}
catch( SoapFault $fault )
{
$error = $fault->getMessage().': SOAP error received when trying to add tracking number '.$package['trackNumber'].' to
Magento for morocco order id '.$orderId.' store order id '.$orderIncrementId;;
$ins = "insert into order_error_log values(NULL, ".$orderId.", '".date("Y-m-d H:i:s")."', '".$program."', '".$error."')";
$result = $mysqli->query($ins);
$upd = "update orders set orderStatusId = ".MAGENTO_SOAP_EXCEPTION.",
dateStatusUpdated = '".date("Y-m-d H:i:s")."'
where id = ".$orderId;
$result = $mysqli->query($upd);
continue;
}
}