Advertisement
Guest User

Untitled

a guest
Jul 24th, 2017
441
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.53 KB | None | 0 0
  1. <?php
  2.  
  3. ###############################################################################
  4. # ASTPP - Open Source VoIP Billing Solution
  5. #
  6. # Copyright (C) 2016 iNextrix Technologies Pvt. Ltd.
  7. # Samir Doshi <samir.doshi@inextrix.com>
  8. # ASTPP Version 3.0 and above
  9. # License https://www.gnu.org/licenses/agpl-3.0.html
  10. #
  11. # This program is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU Affero General Public License as
  13. # published by the Free Software Foundation, either version 3 of the
  14. # License, or (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU Affero General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU Affero General Public License
  22. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. ###############################################################################
  24.  
  25. class GenerateInvoice extends MX_Controller {
  26.  
  27. public static $global_config;
  28.  
  29. function __construct() {
  30. parent::__construct();
  31. $this->load->model("db_model");
  32. $this->load->library("astpp/common");
  33. $this->load->library('html2pdf');
  34. ini_set("memory_limit", "2048M");
  35. ini_set("max_execution_time", "259200");
  36. $this->get_system_config();
  37. }
  38.  
  39. function get_system_config() {
  40. $query = $this->db->get("system");
  41. $config = array();
  42. $result = $query->result_array();
  43. foreach ($result as $row) {
  44. $config[$row['name']] = $row['value'];
  45. }
  46. self::$global_config['system_config'] = $config;
  47. }
  48.  
  49. function getInvoiceData() {
  50. $where = array(
  51. "posttoexternal" => 1,
  52. "deleted" => "0",
  53. "status" => "0"
  54. );
  55. $query = $this->db_model->getSelect("*", "accounts", $where);
  56. if ($query->num_rows > 0) {
  57. $account_data = $query->result_array();
  58. foreach ($account_data as $data_key => $account_value) {
  59. $end_date = gmdate("Y-m-d") . " 23:59:59";
  60. $account_value['sweep_id'] = (int) $account_value['sweep_id'];
  61. switch ($account_value['sweep_id']) {
  62. case 0:
  63. $start_date = $this->validate_invoice_date($account_value);
  64. if (strtotime($start_date) >= strtotime(gmdate("Y-m-d H:i:s"))) {
  65. $start_date = gmdate("Y-m-d H:i:s");
  66. }
  67. $end_date = gmdate("Y-m-d 23:59:59", strtotime($start_date . " + 1 days"));
  68. $this->Generate_Daily_invoice($account_value, $start_date, $end_date);
  69. break;
  70. case 2:
  71. if (date("d") == $account_value['invoice_day']) {
  72. $start_date = $this->validate_invoice_date($account_value);
  73. if (strtotime($start_date) >= strtotime(gmdate("Y-m-d H:i:s"))) {
  74. $start_date = gmdate("Y-m-d H:i:s");
  75. }
  76. $end_date = gmdate("Y-m-d 23:59:59", strtotime($start_date . " + 1 month"));
  77. $this->Generate_Monthly_invoice($account_value, $start_date, $end_date);
  78. }
  79. break;
  80. }
  81. }
  82. $screen_path = getcwd() . "/cron";
  83. $screen_filename = "Email_Broadcast_" . strtotime('now');
  84. $command = "cd " . $screen_path . " && /usr/bin/screen -d -m -S $screen_filename php cron.php BroadcastEmail";
  85. exec($command);
  86. }
  87. }
  88.  
  89. function validate_invoice_date($account_value) {
  90. $last_invoice_date = $this->common->get_invoice_date("to_date", $account_value["id"], $account_value['reseller_id'], "to_date");
  91. $last_invoice_date = ($last_invoice_date) ? $last_invoice_date : $account_value['creation'];
  92. $last_invoice_date = gmdate("Y-m-d H:i:s", strtotime("+1 Second", strtotime($last_invoice_date)));
  93. return $last_invoice_date;
  94. }
  95.  
  96. /**
  97. * @param string $start_date
  98. * @param string $end_date
  99. */
  100. function Generate_Daily_invoice($account_value, $start_date, $end_date) {
  101. // echo "INVOICE SCRIPT-------start date :".$start_date."-------end date....".$end_date;
  102.  
  103. require_once('updateBalance.php');
  104. $updateBalance = new updateBalance();
  105. $updateBalance->process_subscriptions($account_value, $start_date, $end_date, TRUE);
  106. $updateBalance->process_DID_charges($account_value, $start_date, $end_date, TRUE);
  107. $this->process_invoice($account_value, $start_date, $end_date);
  108. }
  109.  
  110. /**
  111. * @param string $start_date
  112. * @param string $end_date
  113. */
  114. function Generate_Monthly_invoice($account_value, $start_date, $end_date) {
  115. require_once('updateBalance.php');
  116. $updateBalance = new updateBalance();
  117. $updateBalance->process_subscriptions($account_value, $start_date, $end_date, TRUE);
  118. $updateBalance->process_DID_charges($account_value, $start_date, $end_date, TRUE);
  119. $this->process_invoice($account_value, $start_date, $end_date);
  120. }
  121.  
  122. function process_invoice($accountdata, $start_date, $end_date) {
  123. //Get Invoice configuration using single query instead of multiple queries.
  124. $invoice_conf = array();
  125. $reseller_id = ($accountdata['reseller_id'] == 0) ? 1 : $accountdata['reseller_id'];
  126. $where = "accountid IN ('" . $reseller_id . "','1')";
  127. $this->db->select('*');
  128. $this->db->where($where);
  129. $this->db->order_by('accountid', 'desc');
  130. $this->db->limit(1);
  131. $invoice_conf = $this->db->get('invoice_conf');
  132. $invoice_conf = (array) $invoice_conf->first_row();
  133. /*******************************************************/
  134. $last_invoice_ID = $this->common->get_invoice_date("invoiceid", "", $accountdata['reseller_id']);
  135. if ($last_invoice_ID && $last_invoice_ID > 0) {
  136. $last_invoice_ID = ($last_invoice_ID + 1);
  137. } else {
  138. $last_invoice_ID = $invoice_conf['invoice_start_from'];
  139. }
  140. $last_invoice_ID = str_pad($last_invoice_ID, (strlen($last_invoice_ID) + 4), '0', STR_PAD_LEFT);
  141. $invoice_sub_total = $this->count_invoice_data($accountdata, $start_date, $end_date);
  142. if ($invoice_sub_total > 0) {
  143. $invoiceid = $this->create_invoice($accountdata, $start_date, $end_date, $last_invoice_ID, $invoice_conf['invoice_prefix'], $invoice_conf);
  144. $this->update_cdrs_data($accountdata['id'], $invoiceid, $start_date, $end_date);
  145. $sort_order = $this->common_model->apply_invoice_taxes($invoiceid, $accountdata, $start_date);
  146. $invoice_total = $this->set_invoice_total($invoiceid, $accountdata['id']);
  147. $this->download_invoice($invoiceid, $accountdata, $invoice_conf);
  148. } else {
  149. $invoiceid = $this->create_invoice($accountdata, $start_date, $end_date, $last_invoice_ID, $invoice_conf['invoice_prefix'], $invoice_conf);
  150. $sort_order = $this->common_model->apply_invoice_taxes($invoiceid, $accountdata, $start_date);
  151. $invoice_total = $this->set_invoice_total($invoiceid, $accountdata['id']);
  152. }
  153. }
  154.  
  155. function count_invoice_data($account, $start_date = "", $end_date = "") {
  156. $cdr_query = "";
  157. $inv_data_query = "";
  158. $cdr_query = "select calltype,sum(debit) as debit from cdrs where accountid = " . $account['id'];
  159. $cdr_query .= " AND callstart >='" . $start_date . "' AND callstart <= '" . $end_date . "' AND invoiceid=0 group by calltype";
  160. //echo $cdr_query;
  161. $cdr_data = $this->db->query($cdr_query);
  162. if ($cdr_data->num_rows > 0) {
  163. $cdr_data = $cdr_data->result_array();
  164. //echo '<pre>'; print_r($cdr_data); exit;
  165. foreach ($cdr_data as $cdrvalue) {
  166. $cdrvalue['debit'] = round($cdrvalue['debit'], self::$global_config['system_config']['decimal_points']);
  167.  
  168. $tempArr = array(
  169. "accountid" => $account['id'],
  170. "reseller_id" => $account['reseller_id'],
  171. "item_id" => "0",
  172. "description" => $cdrvalue['calltype'] . " CALLS for the period (" . date('Y-m-d', strtotime($start_date)) . " to " . date('Y-m-d', strtotime($end_date)),
  173. "debit" => $cdrvalue['debit'],
  174. "item_type" => $cdrvalue['calltype'],
  175. "created_date" => $end_date
  176. );
  177.  
  178. $this->db->insert("invoice_details", $tempArr);
  179. }
  180. }
  181.  
  182. $this->db->select('products.price');
  183. $this->db->select('products.name');
  184. $this->db->select('rent.count');
  185. $this->db->select('rent.payments');
  186. $this->db->select('rent.leftpayments');
  187. $this->db->select('rent.payment_type');
  188. $this->db->select('rent.id');
  189. $this->db->from('rent_products as rent');
  190. $this->db->join('products', 'products.id = rent.product_id', 'left');
  191. $this->db->where('rent.delete_at IS NULL');
  192. $this->db->where('products.delete_at IS NULL');
  193. $this->db->where('rent.user_id', $account['id']);
  194. $this->db->where("DATE(rent.last_payment) <=", date('Y-m-d', strtotime('- 1 month')));
  195.  
  196. $product_data = $this->db->get();
  197.  
  198. $product_data = $product_data->result_array();
  199. if ($product_data) {
  200. foreach ($product_data as $product) {
  201.  
  202. $update = array(
  203. 'last_payment' => date('Y-m-d H:i:s'),
  204. 'payments' => $product['payments'] + 1
  205. );
  206.  
  207. if ($product['payment_type'] == 2) {
  208. if ($product['leftpayments']) {
  209. $update['leftpayments'] = $product['leftpayments'] - 1;
  210.  
  211. if ($update['leftpayments'] == 0) {
  212. $this->db->where('id', $product['id']);
  213. $this->db->update('rent_products', array(
  214. 'delete_at' => date('Y-m-d H:i:s')
  215. ));
  216. }
  217. }
  218. }
  219.  
  220. $this->db->where('id', $product['id']);
  221. $this->db->update("rent_products", $update);
  222.  
  223. $formatted_start_date = date('Y-m-d', strtotime($start_date));
  224. $formatted_end_date = date('Y-m-d', strtotime($end_date));
  225.  
  226. $this->db->insert("invoice_details", array(
  227. "accountid" => $account['id'],
  228. "reseller_id" => $account['reseller_id'],
  229. "item_id" => "0",
  230. "description" => "{$product['name']} Service Payment for the period ({$formatted_start_date} to {$formatted_end_date}) x {$product['count']}",
  231. "debit" => round($product['price'], self::$global_config['system_config']['decimal_points']) * $product['count'],
  232. "item_type" => "PRODUCT",
  233. "created_date" => $end_date
  234. ));
  235.  
  236. if ($product['payment_type'] == 1) {
  237. $this->db->where('id', $product['id']);
  238. $this->db->update('rent_products', array(
  239. 'delete_at' => date('Y-m-d H:i:s')
  240. ));
  241. }
  242. }
  243. }
  244.  
  245. $inv_data_query = "select count(id) as count,sum(debit) as debit,sum(credit) as credit from invoice_details where accountid=" . $account['id'] . " AND created_date >='" . $start_date . "' AND created_date <= '" . $end_date . "' AND invoiceid=0 AND item_type != 'FREECALL'";
  246. //echo $inv_data_query;
  247. $invoice_data = $this->db->query($inv_data_query);
  248. if ($invoice_data->num_rows > 0) {
  249. $invoice_data = $invoice_data->result_array();
  250. foreach ($invoice_data as $data_value) {
  251. if ($data_value['count'] > 0) {
  252. $sub_total = ($data_value['debit'] - $data_value['credit']);
  253. $sub_total = round($sub_total, self::$global_config['system_config']['decimal_points']);
  254. return $sub_total;
  255. }
  256. }
  257. }
  258.  
  259. return "0";
  260. }
  261.  
  262. //Change Order of arguements
  263. function update_cdrs_data($accountid, $invoiceid, $start_date = "", $end_date = "") {
  264. $inv_data_query = "update invoice_details SET invoiceid = '" . $invoiceid . "' where accountid=" . $accountid;
  265. $inv_data_query .= " AND created_date >='" . $start_date . "' AND created_date <= '" . $end_date . "' AND invoiceid=0 AND item_type !='PAYMENT'";
  266. $this->db->query($inv_data_query);
  267. return true;
  268. }
  269.  
  270. /**
  271. * @param string $last_invoice_ID
  272. */
  273. function create_invoice($account, $from_date, $to_date, $last_invoice_ID, $INVprefix, $invoiceconf) {
  274. //$due_date = gmdate("Y-m-d H:i:s",strtotime($to_date." +".$invoiceconf['interval']." days"));
  275. if ($invoiceconf['interval'] > 0) {
  276. $due_date = gmdate("Y-m-d H:i:s", strtotime(gmdate("Y-m-d H:i:s") . " +" . $invoiceconf['interval'] . " days"));
  277. } else {
  278. $due_date = gmdate("Y-m-d H:i:s", strtotime(gmdate("Y-m-d H:i:s") . " +7 days"));
  279. }
  280. // echo "due daye-------".$due_date.'----------'.$to_date.'------------> Invoice interval'.$invoiceconf['interval'];
  281. $balance = ($account['credit_limit'] - $account['balance']);
  282. $automatic_flag = self::$global_config['system_config']['automatic_invoice'];
  283. if ($automatic_flag == 1) {
  284. $invoice_data = array(
  285. "accountid" => $account['id'],
  286. "invoice_prefix" => $INVprefix,
  287. "invoiceid" => $last_invoice_ID,
  288. "reseller_id" => $account['reseller_id'],
  289. "invoice_date" => gmdate("Y-m-d H:i:s"),
  290. "from_date" => $from_date,
  291. "to_date" => $to_date,
  292. "due_date" => $due_date,
  293. "status" => 1,
  294. "amount" => "0.00",
  295. "balance" => $balance
  296. );
  297. } else {
  298. $invoice_data = array(
  299. "accountid" => $account['id'],
  300. "invoice_prefix" => $INVprefix,
  301. "invoiceid" => $last_invoice_ID,
  302. "reseller_id" => $account['reseller_id'],
  303. "invoice_date" => gmdate("Y-m-d H:i:s"),
  304. "from_date" => $from_date,
  305. "to_date" => $to_date,
  306. "due_date" => $due_date,
  307. "status" => 1,
  308. "amount" => "0.00",
  309. "balance" => $balance,
  310. "confirm" => 1
  311. );
  312. }
  313. // echo "<pre>"; print_r($invoice_data); exit;
  314. $this->db->insert("invoices", $invoice_data);
  315. $invoiceid = $this->db->insert_id();
  316. if ($automatic_flag == 0) {
  317. $this->download_invoice($invoiceid, $account, $invoiceconf);
  318. }
  319. return $invoiceid;
  320. }
  321.  
  322. function set_invoice_total($invoiceid, $accountid) {
  323. $query = $this->db_model->getSelect("SUM(debit) as total", "invoice_details", array(
  324. "invoiceid" => $invoiceid,
  325. "item_type <>" => "FREECALL"
  326. ));
  327. $query = $query->result_array();
  328. $sub_total = $query["0"]["total"];
  329. $updateArr = array(
  330. "amount" => $sub_total
  331. );
  332. $this->db->where(array(
  333. "id" => $invoiceid
  334. ));
  335. $this->db->update("invoices", $updateArr);
  336.  
  337. $updateArr = array(
  338. "balance" => "0.00"
  339. );
  340. $this->db->where(array(
  341. "id" => $accountid
  342. ));
  343. $this->db->update("accounts", $updateArr);
  344.  
  345. return true;
  346. }
  347.  
  348. function download_invoice($invoiceid, $accountdata, $invoice_conf) {
  349. $invoicedata = $this->db_model->getSelect("*", "invoices", array(
  350. "id" => $invoiceid
  351. ));
  352. $invoicedata = $invoicedata->result_array();
  353. $invoicedata = $invoicedata[0];
  354. $FilePath = FCPATH . "invoices/" . $accountdata["id"] . '/' . $invoicedata['invoice_prefix'] . "" . $invoicedata['invoiceid'] . "_invoice.pdf";
  355. $Filenm = $invoicedata['invoice_prefix'] . "_" . $invoicedata['invoiceid'] . "_invoice.pdf";
  356. $this->common->get_invoice_template($invoicedata, $accountdata, false);
  357. if ($invoice_conf['invoice_notification']) {
  358. $this->send_email_notification($FilePath, $Filenm, $accountdata, $invoice_conf, $invoicedata);
  359. }
  360. }
  361.  
  362. /**
  363. * @param string $FilePath
  364. * @param string $Filenm
  365. */
  366. function send_email_notification($FilePath, $Filenm, $AccountData, $invoice_conf, $invData) {
  367. $TemplateData = array();
  368. $where = array(
  369. 'name' => 'email_new_invoice'
  370. );
  371. $EmailTemplate = $this->db_model->getSelect("*", "default_templates", $where);
  372. foreach ($EmailTemplate->result_array() as $TemplateVal) {
  373. $TemplateData = $TemplateVal;
  374. $TemplateData['subject'] = str_replace('#NAME#', $AccountData['first_name'] . " " . $AccountData['last_name'], $TemplateData['subject']);
  375. $TemplateData['subject'] = str_replace('#INVOICE_NUMBER#', $invData['invoice_prefix'] . $invData['invoiceid'], $TemplateData['subject']);
  376. $TemplateData['template'] = str_replace('#NAME#', $AccountData['first_name'] . " " . $AccountData['last_name'], $TemplateData['template']);
  377. $TemplateData['template'] = str_replace('#INVOICE_NUMBER#', $invData['invoice_prefix'] . $invData['invoiceid'], $TemplateData['template']);
  378. $TemplateData['template'] = str_replace('#AMOUNT#', $invData['amount'], $TemplateData['template']);
  379.  
  380. $TemplateData['template'] = str_replace("#COMPANY_EMAIL#", $invoice_conf['emailaddress'], $TemplateData['template']);
  381. $TemplateData['template'] = str_replace("#COMPANY_NAME#", $invoice_conf['company_name'], $TemplateData['template']);
  382. $TemplateData['template'] = str_replace("#COMPANY_WEBSITE#", $invoice_conf['website'], $TemplateData['template']);
  383. $TemplateData['template'] = str_replace("#INVOICE_DATE#", $invData['invoice_date'], $TemplateData['template']);
  384. $TemplateData['template'] = str_replace("#DUE_DATE#", $invData['due_date'], $TemplateData['template']);
  385. }
  386. $dir_path = getcwd() . "/attachments/";
  387. $path = $dir_path . $Filenm;
  388. $command = "cp " . $FilePath . " " . $path;
  389. exec($command);
  390. $email_array = array(
  391. 'accountid' => $AccountData['id'],
  392. 'subject' => $TemplateData['subject'],
  393. 'body' => $TemplateData['template'],
  394. 'from' => $invoice_conf['emailaddress'],
  395. 'to' => $AccountData['email'],
  396. 'status' => "1",
  397. 'attachment' => $Filenm,
  398. 'template' => ''
  399. );
  400. //echo "<pre>"; print_r($TemplateData); exit;
  401. $this->db->insert("mail_details", $email_array);
  402. }
  403. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement