Active Collab API — получение следующего номера счета

Я использую Active Collab 5.8.7 с PHP 5.6. Я использую API для создания счета. Я следую за API в этот документация. Моя проблема заключается в том, что для публикации требуется номер счета-фактуры, и я не могу сказать, каким должен быть следующий номер счета.

Я хотел бы знать, есть ли способ использовать API, чтобы получить следующий номер счета-фактуры или добавить счет-фактуру и позволить системе выбрать номер счета-фактуры для вас.

В настоящее время я использую случайную последовательность символов, когда создаю счет через API, а затем, когда мы пытаемся добавить счет вручную, поле номера счета пустое. Должен быть более простой и последовательный способ обработки номеров счетов.

Спасибо,
Larry

0

Решение

Я понял это самостоятельно и хотел опубликовать это здесь на тот случай, если это кому-то понадобится:

//get next invoice number
function get_next_ac_invoice_number($client) {
//get all invoices
$result = $client->get('/reports/run?type=InvoicesFilter')->getJson();
$invoices = $result['all']['invoices'];
usort($invoices,'sortbyInvoiceId');
$next_invoice_id = strval(intval(explode('-',$invoices[0]['number'])[0]) + 1) . '-' . date("Y");
return $next_invoice_id;
}
function sortbyInvoiceId($a,$b){
if ($a == $b) {
return 0;
}
return ($b < $a) ? -1 : 1;
}

РЕДАКТИРОВАТЬ ФЕВРАЛЬ 22 ’17

Для Брэйнтри здесь куча беспорядка, но вы должны быть в состоянии понять суть этого. Я хотел бы убедиться в том, что вы очищаете мусор AC перед публикацией, так как следующая функция идентификатора счета не будет возвращать поврежденные счета и вызовет ошибку идентификатора дублирующего счета.

//get next invoice number
function get_next_ac_invoice_number($client) {

#get all invoices
$trashit = $client->delete('/trash');
$result = $client->get('/reports/run?type=InvoicesFilter')->getJson();
$invoices = $result['all']['invoices'];
usort($invoices,'sortbyInvoiceId');
$next_invoice_id = strval(intval(explode('-',$invoices[0]['number'])[0]) + 1) . '-' . date("Y");
return $next_invoice_id;
}

//creates an invoice in active collab
function create_ac_invoice($customer, $subscription, $transaction, $client) {
//get the next invoice ID
get_next_ac_invoice_number($client);
$plans = Braintree_Plan::all();
$plan;
foreach ($plans AS $myplan) {
if (strtolower($myplan->id) == strtolower($subscription->planId)) {
$plan = $myplan;
}
}

if (isset($transaction->discounts[0])) {
$result = $client->post('invoices', [
'company_id' => $customer['company_id'],
'number' => get_next_ac_invoice_number($client),
'items' => [
[
'description' => $plan->name . " - " . $plan->description,
'quantity' => 1,
'unit_cost' => $subscription->price
],
[
'description' => 'Promo Code Discount - ' . $transaction->discounts[0]->name,
'quantity' => 1,
'unit_cost' => (float) $transaction->discounts[0]->amount * -1
]
],
'private_note' => 'Auto-generated by Braintree'
]);
} else {
$result = $client->post('invoices', [
'company_id' => $customer['company_id'],
'number' => get_next_ac_invoice_number($client),
'items' => [
[
'description' => $plan->name . " - " . $plan->description,
'quantity' => 1,
'unit_cost' => $subscription->price
]
],
'private_note' => 'Auto-generated by Braintree'
]);
}

$invoice = $result->getJson();
if (isset($invoice['message'])) {
//we have an error, let's log and send email
$dump = print_r($invoice, true) . print_r($customer, true) . print_r($subscription, true);
logit('ERROR', $dump);
sendEmail($dump, 'Braintree Webhook Error Creating AC Invoice');
}

//mark the invoice as paid
$result = $client->post('payments', [

'parent_type' => 'Invoice',
'parent_id' => $invoice['single']['id'],
'amount' => getTotalCost($subscription, $transaction),
'comment' => 'Paid in full'
]);
$result = $result->getJson();
if (isset($result['message'])) {
//we have an error, let's log and send email
$dump = print_r($invoice, true) . print_r($customer, true) . print_r($subscription, true);
logit('ERROR', $dump);
sendEmail($dump, 'Braintree Webhook Error Creating AC Payment');
}
//send the invoice
$result = $client->put('invoices/' . $invoice['single']['id'] . '/send', [
'recipients' => [
$customer['email']
],
'subject' => "New Invoice",
'message' => "Thanks!",
'allow_payments' => 2
]);
$result = $result->getJson();
if (isset($result['message'])) {
//we have an error, let's log and send email
$dump = print_r($invoice, true) . print_r($customer, true) . print_r($subscription, true);
logit('ERROR', $dump);
sendEmail($dump, 'Braintree Webhook Error Sending AC Invoice Email');
}

return $invoice;
}
0

Другие решения

Других решений пока нет …