File: /home/mostafedeg/public_html/erp/controllers/eBillRequests.php
<?php
include_once("../public/con_reedbean.php");
// $apiURL = "http://localhost:8888/eata/pi";
$apiURL = "https://try.al-ebda3.com/api";
//"https://invoice.gt4host.com/api"
$do = $_GET["do"];
if ($do == "activity") {
$response = CURL_eBill(array(), $apiURL . "/codes/activity", 'GET');
$receivedata = json_decode($response);
$return_arr = array();
foreach ($receivedata->data as $datan) {
$row_array = array();
$row_array['id'] = $datan->code;
$row_array['text'] = $datan->code . " - " . $datan->Desc_en . " - " . $datan->Desc_ar;
array_push($return_arr, $row_array);
}
echo json_encode($return_arr);
} elseif ($do == "tax-types") {
$response = CURL_eBill(array(), $apiURL . "/codes/tax-types", 'GET');
$receivedata = json_decode($response);
$return_arr = array();
foreach ($receivedata->data->tax_types as $datan) {
$row_array = array();
$row_array['id'] = $datan->Code;
$row_array['text'] = $datan->Code . " - " . $datan->Desc_en . " - " . $datan->Desc_ar;
array_push($return_arr, $row_array);
}
echo json_encode($return_arr);
} elseif ($do == "tax-subtypes") {
$typeid = filter_input(INPUT_POST, 'typeid');
$response = CURL_eBill(array(), $apiURL . "/codes/tax-types", 'GET');
$receivedata = json_decode($response);
$return_arr = array();
foreach ($receivedata->data->tax_sub_types as $datan) {
$row_array = array();
if ($typeid == $datan->TaxtypeReference) {
$row_array['id'] = $datan->Code;
$row_array['text'] = $datan->Code . " - " . $datan->Desc_en . " - " . $datan->Desc_ar;
array_push($return_arr, $row_array);
}
}
echo json_encode($return_arr);
// } elseif ($do == "tax_sub_types") {
// $response = CURL_eBill(array(), $apiURL . "/codes/tax-types",'GET');
// $receivedata = json_decode($response);
// $return_arr = array();
// foreach ($receivedata->data->tax_sub_types as $datan) {
// $row_array = array();
// $row_array['id'] = $datan->Code;
// $row_array['text'] = $datan->Code . " - " . $datan->Desc_en. " - " . $datan->Desc_ar. " - " . $datan->TaxtypeReference;
// array_push($return_arr, $row_array);
// }
// echo json_encode($return_arr);
// } elseif ($do == "non_tax_types") {
// $response = CURL_eBill(array(), $apiURL . "/codes/tax-types",'GET');
// $receivedata = json_decode($response);
// $return_arr = array();
// foreach ($receivedata->data->non_tax_types as $datan) {
// $row_array = array();
// $row_array['id'] = $datan->Code;
// $row_array['text'] = $datan->Code . " - " . $datan->Desc_en. " - " . $datan->Desc_ar;
// array_push($return_arr, $row_array);
// }
// echo json_encode($return_arr);
} elseif ($do == "unit-types") {
$response = CURL_eBill(array(), $apiURL . "/codes/unit-types");
$receivedata = json_decode($response);
$return_arr = array();
foreach ($receivedata->data as $datan) {
$row_array = array();
$row_array['id'] = $datan->code;
$row_array['text'] = $datan->code . " - " . $datan->desc_en . " - " . $datan->desc_ar;
array_push($return_arr, $row_array);
}
echo json_encode($return_arr);
} elseif ($do == "search_code") {
$etacodetype = filter_input(INPUT_POST, 'etacodetype');
$etacodelookupvalue = filter_input(INPUT_POST, 'etacodelookupvalue');
$etaparentlevelname = filter_input(INPUT_POST, 'etaparentlevelname');
$etacodeid = filter_input(INPUT_POST, 'etacodeid');
$etacodetype = 'GS1';
$response = CURL_eBill(array(), $apiURL . "/v1/product/codes?code_type=$etacodetype", 'GET');
$receivedata = json_decode($response);
if ($receivedata->code == 200) {
echo json_encode($receivedata->data);
} else {
echo '0';
}
} elseif ($do == "epdf") {
$uuid = filter_input(INPUT_POST, 'uuid');
$sellbillid = filter_input(INPUT_POST, 'sellbillid');
$response = CURL_eBill(array(), $apiURL . "/v1/bill/$uuid/print/pdf", 'GET');
$receivedata = json_decode($response);
if ($receivedata->success) {
echo json_encode($receivedata->data->bill_url);
} else {
echo '0';
}
} elseif ($do == "bills") {
$eexport = filter_input(INPUT_POST, 'eexport');
$emport = filter_input(INPUT_POST, 'emport');
$eTaxNum = filter_input(INPUT_POST, 'eTaxNum');
$client = filter_input(INPUT_POST, 'client');
$pageNo = filter_input(INPUT_POST, 'pageNo');
$pageSize = filter_input(INPUT_POST, 'pageSize');
$ands = '';
if ($eexport) {
$ands .= "&issuerId=$eTaxNum";
}
if ($emport) {
$ands .= "&receiverId=$eTaxNum";
}
if ($client) {
$ands .= "&receiverId=$client";
}
if ($pageNo) {
$ands .= "&pageNo=$pageNo";
}
if ($pageSize) {
$ands .= "&pageSize=$pageSize";
}
$response = CURL_eBill(array(), $apiURL . "/v1/bill?$ands");
echo $response;
} elseif ($do == "bills_detail") {
$uuid = filter_input(INPUT_POST, 'uuid');
$response = CURL_eBill(array(), $apiURL . "/v1/bill/$uuid");
echo $response;
} elseif ($do == "cancel") {
$uuid = filter_input(INPUT_POST, 'uuid');
$sellbillid = filter_input(INPUT_POST, 'sellbillid');
$cancelreason = filter_input(INPUT_POST, 'cancelreason');
if ($cancelreason == 0) {
$cancelreason = 'Wrong buyer details';
} else {
$cancelreason = 'Wrong invoice details';
}
$response = CURL_eBill(json_encode(array("uid" => $uuid, "reason" => $cancelreason)), $apiURL . "/v1/bill/cancel", 'PUT');
$receivedata = json_decode($response);
if ($receivedata->success) {
$etasellbillstatus = R::dispense('etasellbillstatus');
$etasellbillstatus->today = date("Y-m-d H:i:s");
$etasellbillstatus->estatus = -1;
$etasellbillstatus->sellbillid = $sellbillid;
$etasellbillstatus->submissionid = 0;
$etasellbillstatus->accepteddocuments = 'تم الحذ بنجاح';
$etasellbillstatus->rejecteddocuments = '';
R::store($etasellbillstatus);
echo '1';
R::exec("UPDATE `sellbill` SET `ereason`='تم الحذف بنجاح', `estatus`= -3 WHERE sellbillid = $sellbillid ");
} else {
$etasellbillstatus = R::dispense('etasellbillstatus');
$etasellbillstatus->today = date("Y-m-d H:i:s");
$etasellbillstatus->estatus = -1;
$etasellbillstatus->sellbillid = $sellbillid;
$etasellbillstatus->submissionid = 0;
$etasellbillstatus->accepteddocuments = '';
$etasellbillstatus->rejecteddocuments = json_encode($receivedata->error->details[0]->message);
R::store($etasellbillstatus);
R::exec("UPDATE `sellbill` SET `ereason`='هناك مشكلة اثناء الحذف', `estatus`= -4 WHERE sellbillid = $sellbillid ");
echo '0';
}
} elseif ($do == "etsellbill") {
$programsettings = R::getRow("SELECT * FROM `programsettings`");
$ebillsetting = R::getRow("SELECT * FROM `ebillsetting`");
$sellbillid = filter_input(INPUT_POST, 'sellbillid');
$sellbill = R::getRow("SELECT * FROM `sellbill`where sellbillid =?", [$sellbillid]);
$sellbilldetails = R::getAll("SELECT * FROM `sellbilldetail`where sellbillid =?", [$sellbillid]);
$eclientsetting = R::findOne('eclientsetting', 'clientid = ?', [$sellbill['sellbillclientid']]);
$totalsArr = array();
$totalsArr['totalSalesAmount'] = $totalsArr['totalDiscountAmount'] = $totalsArr['netAmount'] = $totalsArr['totalAmount'] = 0;
$invoiceLines = array();
$taxTotalsArr = array();
foreach ($sellbilldetails as $sellbilldetail) {
$product = R::getRow("SELECT * FROM `product` where productId =? ", [$sellbilldetail['sellbilldetailproductid']]);
$productunit = R::getRow("SELECT * FROM `productunit` where productid =? ", [$sellbilldetail['sellbilldetailproductid']]);
$protaxableItems = R::getAll("SELECT * FROM `sellbilldetailtax`where sellbilldetailid = ?",
[$sellbilldetail['sellbilldetailid']]);
$taxtotal = 0;
$taxableItems = [];
foreach ($protaxableItems as $protaxableItem) {
$protaxableItem['amount'] = round($protaxableItem['amount'], 2);
$protaxableItem['rate'] = round($protaxableItem['rate'], 2);
$taxableItems[] = [
"taxType" => $protaxableItem['type'],
"amount" => (float) $protaxableItem['amount'],
"subType" => $protaxableItem['subtype'],
"rate" => (float) $protaxableItem['rate']
];
$taxtotal += $protaxableItem['amount'];
if (!isset($taxTotalsArr[$protaxableItem['type']])) {
$taxTotalsArr[$protaxableItem['type']] = array("taxType" => $protaxableItem['type'],
"amount" => (float) $protaxableItem['amount']);
} else {
$taxTotalsArr[$protaxableItem['type']]['amount'] += $protaxableItem['amount'];
}
}
$sellbilldetail['sellbilldetailquantity'] = round($sellbilldetail['sellbilldetailquantity'], 2);
$sellbilldetail['sellbilldetailprice'] = round($sellbilldetail['sellbilldetailprice'], 2);
$sellbilldetail['discountvalue'] = round($sellbilldetail['discountvalue'], 2);
$sellbilldetail['sellbilldetailtotalprice'] = round($sellbilldetail['sellbilldetailtotalprice'], 2);
$array = array(
"description" => $product['productName'],
"itemType" => $product['TypeOfBarcodeInTax'],
"itemCode" => $product['barcodeInTax'],
"unitType" => $productunit['unitInTax'],
"quantity" => (float) $sellbilldetail['sellbilldetailquantity'],
"internalCode" => $product['productId'],
"unitValue" => array(
"currencySold" => "EGP",
"amountEGP" => (float) $sellbilldetail['sellbilldetailprice']
),
"salesTotal" => (float) ($sellbilldetail['sellbilldetailprice'] * $sellbilldetail['sellbilldetailquantity']), //total without discount nor tax
"discount" => [//we can use rate or amount
"rate" => 0, //$sellbilldetail['discounttype'], //percentage
"amount" => (float) $sellbilldetail['discountvalue']//value
],
"valueDifference" => 0,
"netTotal" => (float) $sellbilldetail['sellbilldetailtotalprice'], //total including discount
"totalTaxableFees" => 0,
"total" => $sellbilldetail['sellbilldetailtotalprice'] + $taxtotal, //total including discount and tax
"itemsDiscount" => 0,
);
if (!empty($taxableItems)) {
$array["taxableItems"] = $taxableItems;
}
$totalsArr['totalSalesAmount'] += $array["salesTotal"]; //sum of total without discount
$totalsArr['totalDiscountAmount'] += $array["discount"]["amount"]; //sum of discount
$totalsArr['netAmount'] += $array["netTotal"]; //sum including discount
$totalsArr['totalAmount'] += $array["total"]; //sum including discount and tax
array_push($invoiceLines, $array);
}
$documents[] = array(
'issuer' => array(
'address' => array(
"branchID" => $ebillsetting['eTaxNumBranch'],
"country" => "EG",
"governate" => $ebillsetting['eGovernorate'],
"regionCity" => $ebillsetting['eCity'],
"street" => $ebillsetting['eStreet'],
"buildingNumber" => $ebillsetting['eBuildingNum']
),
"type" => $programsettings['typebill'],
"id" => $ebillsetting['eTaxNum'],
"name" => $ebillsetting['eCompanyNameInTaxCard']
),
'receiver' => array(
'address' => array(
"country" => "EG",
"governate" => $eclientsetting->egovernorate,
"regionCity" => $eclientsetting->ecity,
"street" => $eclientsetting->estreet,
"buildingNumber" => $eclientsetting->ebuilding_num,
// "postalCode": $eclientsetting->postalCode,
// "floor": $eclientsetting->floor,
// "room": $eclientsetting->room,
// "landmark": $eclientsetting->landmark,
// "additionalInformation": $eclientsetting->additionalInformation,
),
"type" => $eclientsetting->etax_type,
"id" => $eclientsetting->etax_num,
"name" => $eclientsetting->clientname
),
'dateTimeIssued' => $sellbill['sellbilldate'],
'taxpayerActivityCode' => $ebillsetting['eTaxTypeNum'],
'internalID' => $sellbill['sellbillid'],
'invoiceLines' => $invoiceLines,
"totalSalesAmount" => (float) $totalsArr['totalSalesAmount'],
"totalItemsDiscountAmount" => 0,
"extraDiscountAmount" => 0,
"totalDiscountAmount" => $totalsArr['totalDiscountAmount'],
"taxTotals" => array_values($taxTotalsArr),
"netAmount" => (float) $totalsArr['netAmount'],
"totalAmount" => (float) $totalsArr['totalAmount'],
);
/*
// $documents = [
// [
// "issuer"=> [
// "address"=> [
// "branchID"=> "0",
// "country"=> "EG",
// "governate"=> "Dakahlia",
// "regionCity"=> "El Mansoura 1",
// "street"=> "0 ش الصديق من ش جيهان ",
// "buildingNumber"=> "57"
// ],
// "type"=>"B",
// "id"=> "577218573",
// "name"=>"كابيتال هيلث كير"
// ],
// "receiver"=> [
// "address"=> [
// "country"=> "EG",
// "governate"=> "الدقهلية",
// "regionCity"=> "قسم ثانى لمنصورة",
// "street"=> "شارع المنتزه ثان المنصوره الدقهليه",
// "buildingNumber"=> "3",
// "postalCode"=> "68030",
// "floor"=> "1",
// "room"=> "123",
// "landmark"=> "7660 Melody Trail",
// "additionalInformation"=> "beside Townhall"
// ],
// "type"=> "B",
// "id"=> "728850877",
// "name"=> "بداية فارم للادوية"
// ],
// "dateTimeIssued"=> "2023-03-02 14:01:00",
// "taxpayerActivityCode"=> "4772",
// "internalID"=> "150542623051",
// "invoiceLines"=> [
// [
// "description"=> "روتاركس لقاح ثلاجة",
// "itemType"=> "GS1",
// "itemCode"=> "10005845",
// "unitType"=> "BOX",
// "quantity"=> 500,
// "internalCode"=> "IC0",
// "unitValue"=> [
// "currencySold"=> "EGP",
// "amountEGP"=> 257.3
// ],
// "salesTotal"=> 128650,
// "discount"=> [
// "rate"=> 0,
// "amount"=> 1000
// ],
// "valueDifference"=> 0,
// "netTotal"=> 127650,
// "taxableItems"=> [
// "taxType"=> "T1",
// "amount"=> 17871,
// "subType"=> "V009",
// "rate"=> 14
// ],
// "totalTaxableFees"=> 0,
// "total"=> 145521,
// "itemsDiscount"=> 0
// ],
// [
// "description"=> "سينفلوراكس لقاح ثلاجة",
// "itemType"=> "GS1",
// "itemCode"=> "10005845",
// "unitType"=> "BOX",
// "quantity"=> 400,
// "internalCode"=> "IC0",
// "salesTotal"=> 116200,
// "total"=> 116200,
// "valueDifference"=> 0,
// "totalTaxableFees"=> 0,
// "netTotal"=> 116200,
// "itemsDiscount"=> 0,
// "unitValue"=> [
// "currencySold"=> "EGP",
// "amountEGP"=> 290.5
// ]
// ],
// [
// "description"=> "بريفنار 13 - فيال لايرتجع - ثلاجة",
// "itemType"=> "GS1",
// "itemCode"=> "10005845",
// "unitType"=> "BOX",
// "quantity"=> 100,
// "internalCode"=> "IC0",
// "salesTotal"=> 40670,
// "total"=> 40670,
// "valueDifference"=> 0,
// "totalTaxableFees"=> 0,
// "netTotal"=> 40670,
// "itemsDiscount"=> 0,
// "unitValue"=> [
// "currencySold"=> "EGP",
// "amountEGP"=> 406.7
// ]
// ],
// [
// "description"=> "نيمتركس فيال ثلاجة",
// "itemType"=> "GS1",
// "itemCode"=> "10005845",
// "unitType"=> "BOX",
// "quantity"=> 50,
// "internalCode"=> "IC0",
// "salesTotal"=> 15272,
// "total"=> 15272,
// "valueDifference"=> 0,
// "totalTaxableFees"=> 0,
// "netTotal"=> 15272,
// "itemsDiscount"=> 0,
// "unitValue"=> [
// "currencySold"=> "EGP",
// "amountEGP"=> 305.44
// ]
// ],
// [
// "description"=> "هافركس لقاح 720 اطفال ثلاجة",
// "itemType"=> "GS1",
// "itemCode"=> "10005845",
// "unitType"=> "BOX",
// "quantity"=> 100,
// "internalCode"=> "IC0",
// "salesTotal"=> 20999,
// "total"=> 20999,
// "valueDifference"=> 0,
// "totalTaxableFees"=> 0,
// "netTotal"=> 20999,
// "itemsDiscount"=> 0,
// "unitValue"=> [
// "currencySold"=> "EGP",
// "amountEGP"=> 209.99
// ]
// ],
// [
// "description"=> "هافركس لقاح 1440",
// "itemType"=> "GS1",
// "itemCode"=> "10005845",
// "unitType"=> "BOX",
// "quantity"=> 20,
// "internalCode"=> "IC0",
// "salesTotal"=> 5776.8,
// "total"=> 5776.8,
// "valueDifference"=> 0,
// "totalTaxableFees"=> 0,
// "netTotal"=> 5776.8,
// "itemsDiscount"=> 0,
// "unitValue"=> [
// "currencySold"=> "EGP",
// "amountEGP"=> 288.84
// ]
// ]
// ],
// "totalSalesAmount"=> 327567.8,
// "totalItemsDiscountAmount"=> 0,
// "extraDiscountAmount"=> 0,
// "totalDiscountAmount"=> 1000,
// "taxTotals"=> [
// [
// "taxType"=> "T1",
// "amount"=> 17871
// ]
// ],
// "netAmount"=> 326567.8,
// "totalAmount"=> 344438.8
// ]
// ]; */
/* print_r($documents);
exit(); */
$data = array('documents' => $documents);
$alter_data = json_encode($data, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
// print_r($alter_data);
// exit();
$responsedata = CURL_eBill($alter_data, $apiURL . "/v1/bill", 'POST');
$receivedata = json_decode($responsedata);
// print_r($receivedata);
// exit();
if ($receivedata->code >= 200 && $receivedata->code < 300) {
if ($receivedata->data->acceptedDocuments) {
$uuid = $receivedata->data->acceptedDocuments[0]->uuid;
R::exec("UPDATE `sellbill` SET `ereason`= 'تم قبول الفاتوره', `estatus`= '$uuid' WHERE sellbillid = $sellbillid ");
$etasellbillstatus = R::dispense('etasellbillstatus');
$etasellbillstatus->today = date("Y-m-d H:i:s");
$etasellbillstatus->estatus = $uuid;
$etasellbillstatus->sellbillid = $sellbillid;
$etasellbillstatus->submissionid = $receivedata->data->submissionId;
$etasellbillstatus->accepteddocuments = json_encode($receivedata->data->acceptedDocuments);
$etasellbillstatus->rejecteddocuments = '';
$etasellbillstatus->errors = '';
R::store($etasellbillstatus);
echo '1';
} else {
R::exec("UPDATE `sellbill` SET `ereason`= 'تم رفض الفاتوره', `estatus`= -1 WHERE sellbillid = $sellbillid ");
$etasellbillstatus = R::dispense('etasellbillstatus');
$etasellbillstatus->today = date("Y-m-d H:i:s");
$etasellbillstatus->estatus = -1;
$etasellbillstatus->sellbillid = $sellbillid;
$etasellbillstatus->submissionid = $receivedata->data->submissionId;
$etasellbillstatus->accepteddocuments = '';
$etasellbillstatus->rejecteddocuments = json_encode($receivedata->data->rejectedDocuments);
$etasellbillstatus->rejectedmassage = $receivedata->data->rejectedDocuments->details->message;
$etasellbillstatus->errors = '';
R::store($etasellbillstatus);
echo '2';
}
} else {
R::exec("UPDATE `sellbill` SET `ereason`='حدثا خطأ اثناء الارسال', `estatus`= -2 WHERE sellbillid = $sellbillid ");
$etasellbillstatus = R::dispense('etasellbillstatus');
$etasellbillstatus->today = date("Y-m-d H:i:s");
$etasellbillstatus->estatus = -2;
$etasellbillstatus->sellbillid = $sellbillid;
$etasellbillstatus->submissionid = 0;
$etasellbillstatus->accepteddocuments = '';
$etasellbillstatus->rejecteddocuments = '';
$etasellbillstatus->errors = json_encode($receivedata->error);
R::store($etasellbillstatus);
echo '3';
}
}
//****************** Functions ************************//
////it is defined in config now to be available to all
//function isJson($string) {
// json_decode($string);
// return json_last_error() === JSON_ERROR_NONE;
//}
function CURL_eBill($data_arr, $url, $method = 'GET') {
// ##preparing session data
// //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
// $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $url;
//
// ##appending necessary data
// $data_arr['curlpost'] = '1';
// $data_arr['sessionlist'] = json_encode($_SESSION);
// set post fields
// $post = [
// 'data_arr' => json_encode($data_arr), //encode it as it is array
// ];
$post = $data_arr;
$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJldGEtYnJva2VyIiwiYXVkIjoiZXRhLWJyb2tlciIsImp0aSI6IkpXVG4xblZIeVUiLCJpYXQiOjE2NTU1NDIwNjMuODkyMX0.M6MZ1qojF5GqFYb-7CA3DBA90Th9hCFv3VCC9WwdpvU";
header('Content-Type: application/json'); // Specify the type of data
$ch = curl_init($url);
//header
$authorization = "Authorization: Bearer $token";
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', $authorization)); // Inject the token into the
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
//Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
//setting them to false.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
//curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
// execute!
$response = curl_exec($ch);
if ($response === false) {
echo 'Error : ' . curl_error($ch);
}
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
//var_dump($response);
//print_r($response);
return $response;
}
?>