timesheet source code
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1643 Zeilen
60KB

  1. <?php
  2. /**
  3. * Plugin Name: Acare Advanced Office
  4. * Plugin URI: http://biukop.com.au/acaresydney/timesheets
  5. * Description: Advanced Office system, timesheet, Payroll for AcareSydney
  6. * Version: 2.1
  7. * Author: Biukop Intelligence
  8. * Author URI: http://biukop.com.au/
  9. */
  10. namespace Biukop;
  11. use XeroPHP\Models\Accounting\Address;
  12. use XeroPHP\Models\Accounting\Payment;
  13. require_once(dirname(__FILE__) . '/autoload.php');
  14. require_once (ABSPATH . 'wp-includes/pluggable.php');
  15. class AcareOffice{
  16. private $acare_ndis_registration = "4050024758";
  17. private $nonce; //for ajax verification
  18. private $pages = array('time-sheets', 'user-list');
  19. private $bts_user_id = 0;
  20. private $bts_week_id = 1; //week 1, we will try to calculate current week;
  21. private $xero ;
  22. private $db;
  23. private $table_name; //default to job_table
  24. private $job_table;
  25. private $allowance_table;
  26. private $addr_table;
  27. private $ndis_table;
  28. private $apiv1;
  29. private $ndis_price;
  30. public function __construct() {
  31. $this->setup_db_name();
  32. $this->class_loader();
  33. $this->apiv1 = new Apiv1($this, $this->job_table);
  34. //$this->check_csv_download();
  35. add_option( "acare_ts_db_version", "1.0" );
  36. register_activation_hook( __FILE__, array($this, 'db_install') );
  37. //add_action('init', array($this, 'class_loader'));
  38. add_action('init', array($this, 'check_csv_download'));
  39. add_action('wp', array($this, 'check_auth'));
  40. add_action('wp_enqueue_scripts', array($this, 'register_js_css'), 99);
  41. add_filter('show_admin_bar', '__return_false');
  42. //ts-xx for sync single user
  43. add_shortcode( 'ts-sync-users', array($this, 'sync_users'));
  44. //bts-xx for webpage
  45. add_shortcode( 'bts_staff_item', array($this, 'bts_staff_item'));
  46. add_shortcode( 'bts_client_item', array($this, 'bts_client_item'));
  47. add_shortcode( 'bts_job_item', array($this, 'bts_job_item'));
  48. add_shortcode( 'bts_rate_options', array($this, 'bts_rate_options'));
  49. add_shortcode( 'bts_select_staff', array($this, 'bts_select_staff'));
  50. add_shortcode( 'bts_select_client', array($this, 'bts_select_client'));
  51. add_shortcode( 'bts_type_of_service', array($this, 'bts_type_of_service'));
  52. add_shortcode( 'bts_staff_job_summary', array($this, 'bts_staff_job_summary'));
  53. add_shortcode( 'bts_feedback_card', array($this, 'bts_feedback_card'));
  54. add_shortcode( 'bb_timesheet_canvas', array($this, 'bb_timesheet_canvas'));
  55. add_shortcode( 'bts_staff_hours_template', array($this, 'bts_staff_hours_template'));
  56. add_shortcode( 'bts_client_invoice_template', array($this, 'bts_client_invoice_template'));
  57. add_shortcode( 'bts_csv_template', array($this, 'bts_csv_template'));
  58. add_shortcode( 'bts_invoiced_client', array($this, 'bts_invoiced_client'));
  59. //user profile page
  60. add_shortcode( 'bts_user_name', array($this,'bts_user_name'));
  61. add_action('wp_ajax_list_staff', array($this,'list_staff' ));
  62. add_action('wp_ajax_list_client', array($this,'list_client' ));
  63. add_action('wp_ajax_list_tos', array($this,'list_tos' ));
  64. add_action('wp_ajax_save_job', array($this,'save_job' ));
  65. add_action('wp_ajax_list_job', array($this,'list_job' ));
  66. add_action('wp_ajax_delete_job', array($this,'delete_job' ));
  67. add_action('wp_ajax_email_job', array($this,'email_job' ));
  68. add_action('wp_ajax_email_feedback_url', array($this,'email_feedback_url' ));
  69. add_action('wp_ajax_earnings_rate', array($this,'get_payitem_earnings_rate' ));
  70. add_action('wp_ajax_nopriv_earnings_rate', array($this,'get_payitem_earnings_rate' ));
  71. add_action('wp_ajax_list_job_by_staff', array($this,'list_job_by_staff' ));
  72. add_action('wp_ajax_nopriv_list_job_by_staff', array($this,'list_job_by_staff' ));
  73. add_action('wp_ajax_staff_ack_job', array($this,'staff_ack_job' ));
  74. add_action('wp_ajax_nopriv_staff_ack_job', array($this,'staff_ack_job' ));
  75. add_action('wp_ajax_list_job_by_client', array($this,'list_job_by_client' ));
  76. add_action('wp_ajax_nopriv_list_job_by_client', array($this,'list_job_by_client' ));
  77. add_action('wp_ajax_client_ack_job', array($this,'client_ack_job' ));
  78. add_action('wp_ajax_nopriv_client_ack_job', array($this,'client_ack_job' ));
  79. add_action('wp_ajax_get_timesheet_from_xero', array($this,'get_timesheet_from_xero' ));
  80. add_action('wp_ajax_approve_all_timesheet', array($this,'approve_all_timesheet' ));
  81. add_action('wp_ajax_get_invoice_item', array($this,'get_invoice_item' ));
  82. add_action('wp_ajax_create_invoice_in_xero', array($this,'create_invoice_in_xero' ));
  83. // hook add_rewrite_rules function into rewrite_rules_array
  84. add_filter('rewrite_rules_array', array($this,'my_add_rewrite_rules'));
  85. // hook add_query_vars function into query_vars
  86. add_filter('query_vars', array($this,'add_query_vars'));
  87. }
  88. private function setup_db_name()
  89. {
  90. global $wpdb;
  91. $this->db = $wpdb;
  92. $this->table_name = $wpdb->prefix . 'acare_ts'; //for backward compatability;
  93. $this->job_table = $wpdb->prefix . 'acare_ts';
  94. $this->allowance_table = $wpdb->prefix . 'acare_allowance';
  95. $this->addr_table = $wpdb->prefix . 'acare_addr_distance';
  96. $this->ndis_table = $wpdb->prefix . 'acare_ndis_price';
  97. }
  98. /**
  99. * Autoload the custom theme classes
  100. */
  101. public function class_loader()
  102. {
  103. // Create a new instance of the autoloader
  104. $loader = new \Psr4AutoloaderClass();
  105. // Register this instance
  106. $loader->register();
  107. // Add our namespace and the folder it maps to
  108. $loader->addNamespace('\XeroPHP', dirname(__FILE__) . '/xero-php-master/src/XeroPHP');
  109. $loader->addNamespace('\Biukop', dirname(__FILE__) . '/' );
  110. $this->xero = new Xero();
  111. $this->xero->init_wp();
  112. //$abc = new AddrMap("01515b52-6936-46b2-a000-9ad4cd7a5b50", "0768db6d-e5f4-4b45-89a2-29f7e8d2953c");
  113. //$abc = new AddrMap("122eb1d0-d8c4-4fc3-8bf8-b7825bee1a01", "0768db6d-e5f4-4b45-89a2-29f7e8d2953c");
  114. }
  115. public function check_csv_download()
  116. {
  117. $method = $_SERVER['REQUEST_METHOD'];
  118. if ( $method != "POST")
  119. return;
  120. global $wpdb;
  121. $url = $_SERVER['REQUEST_URI'];
  122. if ($url != "/ndiscsv/"){
  123. return;
  124. }
  125. $clients= $_POST['clients'];
  126. $start = $_POST['start'];;
  127. $finish = $_POST['finish'];;
  128. $filename="{$start}___{$finish}.csv";
  129. header("Expires: 0");
  130. header("Cache-Control: no-cache, no-store, must-revalidate");
  131. header('Cache-Control: pre-check=0, post-check=0, max-age=0', false);
  132. header("Pragma: no-cache");
  133. header("Content-type: text/csv");
  134. header("Content-Disposition:attachment; filename=$filename");
  135. header("Content-Type: application/force-download");
  136. //readfile(dirname(__FILE__) . "/img/circle.png");
  137. $clients_in = "'" . implode("','", $clients) . "'";
  138. $sql = "SELECT * from $this->table_name WHERE client in ($clients_in) and start >='$start 00:00:00' and start<='$finish 23:59:59'";
  139. $results = $wpdb->get_results($sql);
  140. $csv_header = "RegistrationNumber,NDISNumber,SupportsDeliveredFrom,SupportsDeliveredTo,SupportNumber,ClaimReference,Quantity,Hours,UnitPrice,GSTCode,AuthorisedBy,ParticipantApproved,InKindFundingProgram,ClaimType,CancellationReason\n";
  141. echo $csv_header;
  142. foreach($results as $r)
  143. {
  144. echo $this->ndis_csv_line($r);
  145. }
  146. //echo $sql;
  147. exit();
  148. }
  149. private function get_ndis_price()
  150. {//help to ensure ndis_price is only build once per call
  151. if ( ! $this->ndis_price instanceof NdisPrice )
  152. $this->ndis_price = new NdisPrice();
  153. return $this->ndis_price;
  154. }
  155. private function ndis_csv_line($record)
  156. {
  157. $str = "";
  158. $price = $price = $this->get_ndis_price();
  159. $registration = $this->acare_ndis_registration;
  160. $ndisnumber = $this->get_client_ndis_account($record->client);
  161. $date = new \DateTime($record->start);
  162. $start = $date->format("Y-m-d");
  163. $date = new \Datetime($record->finish);
  164. $finish = $date->format("Y-m-d");
  165. $quantity = $this->get_job_hours($record->start, $record->finish);
  166. $hours = $quantity;
  167. $unitprice = $this->get_ndis_price()->get_tos_price($record->tos);
  168. $authorizedby="helen";
  169. $participant_approved = "";
  170. $GST = $this->get_client_GST($record->client);
  171. $in_kind_program = $this->get_client_in_kind_program($record->client);
  172. $ClaimType = "";// standard;
  173. $CancellationReason="";
  174. return "$registration,$ndisnumber,$start,$finish,$record->tos,REC_{$record->id},$quantity,$hours,$unitprice,$GST,$authorizedby,$participant_approved,$in_kind_program,$ClaimType,$CancellationReason\n";
  175. }
  176. private function get_client_ndis_account($client)
  177. {
  178. $user = get_user_by('login', $client);
  179. return get_user_meta($user->ID,'account',true);
  180. }
  181. private function get_client_in_kind_program($client)
  182. {
  183. $user = get_user_by('login', $client);
  184. return get_user_meta($user->ID,'in_kind_prog',true);
  185. }
  186. private function get_client_GST($client)
  187. {
  188. $user = get_user_by('login', $client);
  189. $str = get_user_meta($user->ID,'gst',true);
  190. if ($str == "")
  191. return "P2";
  192. return $str;
  193. }
  194. //init database
  195. public function db_install () {
  196. global $wpdb;
  197. $charset_collate = $wpdb->get_charset_collate();
  198. //table name: timesheets jobs
  199. $table_name = $this->table_name;
  200. $sql = "CREATE TABLE $table_name (
  201. id INT NOT NULL AUTO_INCREMENT,
  202. tos VARCHAR(45) NULL,
  203. start DATETIME NULL,
  204. finish DATETIME NULL,
  205. rate VARCHAR(45) NULL,
  206. staff VARCHAR(45) NULL,
  207. client VARCHAR(45) NULL,
  208. ack TINYINT(4) NULL,
  209. rating INT(4) NULL DEFAULT 0,
  210. PRIMARY KEY (id)
  211. ) $charset_collate;";
  212. //addr distance
  213. $addr_table = $this->addr_table;
  214. $sql_addr = "CREATE TABLE $addr_table (
  215. id INT NOT NULL AUTO_INCREMENT,
  216. origin VARCHAR(1024) NULL,
  217. destination VARCHAR(1024) NULL,
  218. response VARCHAR(40960) NULL,
  219. distance INT NULL,
  220. PRIMARY KEY (id)
  221. ) $charset_collate;";
  222. $ndis_table = $this->ndis_table;
  223. $sql_ndis_price = "
  224. CREATE TABLE $ndis_table (
  225. code VARCHAR(45) NOT NULL,
  226. name VARCHAR(45) NULL,
  227. level INT NULL,
  228. unit VARCHAR(45) NULL,
  229. price FLOAT NULL,
  230. year INT NOT NULL,
  231. PRIMARY KEY (code, year)
  232. )$charset_collate;";
  233. //create database
  234. require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
  235. dbDelta( $sql );
  236. dbDelta( $sql_addr);
  237. dbDelta( $sql_ndis_price);
  238. }
  239. //
  240. //query var
  241. public function add_query_vars($aVars) {
  242. $aVars[] = "bts_user_id"; // represents the name of the product category as shown in the URL
  243. $aVars[] = "bts_week_id"; // represents the name of the product category as shown in the URL
  244. $aVars[] = "bts_job_start"; // represents the name of the product category as shown in the URL
  245. $aVars[] = "bts_job_finish"; // represents the name of the product category as shown in the URL
  246. return $aVars;
  247. }
  248. //for customer profile and broker trans
  249. public function my_add_rewrite_rules($aRules) {
  250. $aNewRules = array(
  251. 'user/([^/]+)/?$' => 'index.php?pagename=user&bts_user_id=$matches[1]',
  252. 'task/week-([^/]+)/?$' => 'index.php?pagename=task&bts_week_id=$matches[1]',
  253. 'task/start-([^/]+)/finish-([^/]+)/?$' => 'index.php?pagename=task&bts_job_start=$matches[1]&bts_job_finish=$matches[2]',
  254. 'task/([^/]+)/?$' => 'index.php?pagename=task&bts_user_id=$matches[1]',
  255. 'task/([^/]+)/week-([^/]+)/?$' => 'index.php?pagename=task&bts_user_id=$matches[1]&bts_week_id=$matches[2]',
  256. 'task/([^/]+)/start-([^/]+)/finish-([^/]+)/?$' => 'index.php?pagename=task&bts_user_id=$matches[1]&bts_job_start=$matches[2]&bts_job_finish=$matches[3]',
  257. 'feedback_card/week-([^/]+)/?$' => 'index.php?pagename=feedback_card&bts_week_id=$matches[1]',
  258. 'feedback_card/start-([^/]+)/finish-([^/]+)/?$' => 'index.php?pagename=feedback_card&bts_job_start=$matches[1]&bts_job_finish=$matches[2]',
  259. 'feedback_card/([^/]+)/?$' => 'index.php?pagename=feedback_card&bts_user_id=$matches[1]',
  260. 'feedback_card/([^/]+)/week-([^/]+)/?$' => 'index.php?pagename=feedback_card&bts_user_id=$matches[1]&bts_week_id=$matches[2]',
  261. 'feedback_card/([^/]+)/start-([^/]+)/finish-([^/]+)/?$' => 'index.php?pagename=feedback_card&bts_user_id=$matches[1]&bts_job_start=$matches[2]&bts_job_finish=$matches[3]',
  262. 'ndiscsv/start-([^/]+)/finish-([^/]+)/?$' => 'index.php?pagename=ndiscsv&bts_job_start=$matches[1]&bts_job_finish=$matches[2]',
  263. );
  264. $aRules = $aNewRules + $aRules;
  265. return $aRules;
  266. }
  267. //
  268. //
  269. ///check auth
  270. public function check_auth(){
  271. global $pagename;
  272. switch($pagename){
  273. case 'task':
  274. $this->cauth_task();
  275. break;
  276. case 'time-sheets':
  277. $this->cauth_time_sheet();
  278. break;
  279. case 'feedback_card':
  280. $this->cauth_feedback_card();
  281. break;
  282. }
  283. }
  284. private function cauth_task(){
  285. $login = get_query_var( 'bts_user_id' );
  286. $this->bts_job_start = get_query_var( 'bts_job_start' );
  287. $this->bts_job_finish = get_query_var( 'bts_job_finish' );
  288. $this->bts_week_id = get_query_var('bts_week_id');
  289. $redirect_url = $this->get_redirect_url_for_task();
  290. // wp_send_json(array(
  291. // 'week'=> $week,
  292. // 'userid'=>$login,
  293. // 'job_start' => $this->bts_job_start,
  294. // 'job_finish' => $this->bts_job_finish,
  295. // 'redirect' => $redirect_url,
  296. // ));
  297. if ($login != "")//perform autologin, and redirect
  298. {
  299. $staff = get_user_by('login', $login);
  300. if ($this->is_staff($staff)){//is valid staff;
  301. $current = wp_get_current_user();
  302. if($current->ID != $staff->ID){
  303. wp_logout();
  304. wp_set_current_user($staff->ID, $staff->display_name); //this is a must
  305. wp_set_auth_cookie($staff->ID, true);//only with this, wordpress calls login + redirect and lost week-%d
  306. }
  307. }
  308. wp_redirect($redirect_url);
  309. return;
  310. }
  311. //no auto login is required if reach here.
  312. $current = wp_get_current_user();
  313. if ($this->is_admin($current)){
  314. wp_redirect("/time-sheets/");
  315. return;
  316. }
  317. if (!$this->is_staff($current) && ! $this->is_admin($current))
  318. {
  319. wp_logout();
  320. wp_redirect("/login/");
  321. return;
  322. }
  323. }
  324. private function cauth_feedback_card(){
  325. $login = get_query_var( 'bts_user_id' );
  326. $this->bts_job_start = get_query_var( 'bts_job_start' );
  327. $this->bts_job_finish = get_query_var( 'bts_job_finish' );
  328. $this->bts_week_id = get_query_var('bts_week_id');
  329. $redirect_url = $this->get_redirect_url_for_feedback_card();
  330. if ($login != "")//perform autologin, and redirect
  331. {
  332. $client = get_user_by('login', $login);
  333. if ($this->is_client($client)){//is valid client;
  334. $current = wp_get_current_user();
  335. if($current->ID != $client->ID){
  336. wp_logout();
  337. wp_set_current_user($client->ID, $client->display_name); //this is a must
  338. wp_set_auth_cookie($client->ID, true);//only with this, wordpress calls login + redirect and lost week-%d
  339. }
  340. }
  341. wp_redirect($redirect_url);
  342. return;
  343. }
  344. //no auto login is required if reach here.
  345. $current = wp_get_current_user();
  346. if ($this->is_admin($current)){
  347. wp_redirect("/time-sheets/");
  348. return;
  349. }
  350. if (!$this->is_client($current) && ! $this->is_admin($current))
  351. {
  352. wp_logout();
  353. wp_redirect("/login/");
  354. return;
  355. }
  356. }
  357. private function get_week_id()
  358. {
  359. $week = get_query_var( 'bts_week_id' );
  360. $week_id = intval($week);
  361. if ($week_id == 0 || $week_id >53 ||$week_id < 1)
  362. return $this->get_current_week_id();
  363. else
  364. return $week;
  365. }
  366. private function get_current_week_id()
  367. {
  368. $now = new \DateTime();
  369. $week = $now->format("W");
  370. return $week;
  371. }
  372. private function get_redirect_url_for_task()
  373. {
  374. if ($this->bts_week_id != "")
  375. return "/task/week-" . $this->bts_week_id . "/";
  376. if ($this->bts_job_start!="" && $this->bts_job_finish !="")
  377. return "/task/start-" . $this->bts_job_start . "/finish-" .$this->bts_job_finish . "/";
  378. return '/task/';
  379. }
  380. private function get_redirect_url_for_feedback_card()
  381. {
  382. if ($this->bts_week_id != "")
  383. return "/feedback_card/week-" . $this->bts_week_id . "/";
  384. if ($this->bts_job_start!="" && $this->bts_job_finish !="")
  385. return "/feedback_card/start-" . $this->bts_job_start . "/finish-" .$this->bts_job_finish . "/";
  386. return '/feedback_card/';
  387. }
  388. private function cauth_time_sheet()
  389. {
  390. $current = wp_get_current_user();
  391. if ($current->ID == 0 ) { //visitor not logged in
  392. wp_redirect("/wp-login.php?");
  393. return;
  394. }
  395. if ($this->is_staff($current)){
  396. wp_redirect("/task");
  397. return;
  398. }
  399. if ($this->is_admin($current)){
  400. //proceed
  401. return;
  402. }
  403. if ($this->is_client($current)){
  404. wp_redirect("/service");
  405. return;
  406. }
  407. //everything else
  408. wp_redirect("/?invalid-access");
  409. }
  410. ///
  411. // enqueue / register css /js
  412. //
  413. public function register_js_css() {
  414. $this->nonce = wp_create_nonce('acaresydney');
  415. $this->bts_user_id = get_query_var( 'bts_user_id' ) ;
  416. $this->register_bts_js();
  417. $this->register_timesheet_js_css();
  418. $this->register_office_js_css();
  419. $this->register_task_js_css();
  420. $this->register_feedback_card_js_css();
  421. $this->register_xeroc_js_css();
  422. }
  423. private function register_bts_js()
  424. {
  425. wp_enqueue_style( 'bts', plugins_url('css/ts.css', __FILE__));
  426. wp_enqueue_script('bts', plugins_url('js/ts.js', __FILE__), array('jquery', 'jquery-ui-core'));
  427. wp_localize_script( 'bts', 'bts1', array(
  428. 'ajax_url' => admin_url( 'admin-ajax.php' ),
  429. 'nonce' => $this->nonce, // It is common practice to comma after
  430. 'display_name' => wp_get_current_user()->display_name,
  431. 'anonymous' => !is_user_logged_in(),
  432. 'me'=> get_current_user_id(),
  433. 'userid'=> $this->bts_user_id,
  434. 'load_user_img'=> plugins_url('img/loading_user.gif', __FILE__),
  435. 'load_job_img'=> plugins_url('img/loading_job.gif', __FILE__),
  436. 'driving' => "259ee8e8-a1e5-42e4-9c14-517543ecdc4b",
  437. 'high_pay_keywords' => ['sat ', 'sun ', 'high ', 'public holiday'], //space is important
  438. ) );
  439. }
  440. private function register_timesheet_js_css(){
  441. global $pagename;
  442. if ($pagename != 'time-sheets'){
  443. return;
  444. }
  445. wp_enqueue_style( 'bts_ts', plugins_url('css/bts_timesheet.css', __FILE__));
  446. wp_enqueue_script( 'bts_ts', plugins_url('js/bts_timesheet.js', __FILE__), array( 'jquery' , 'bts' ));
  447. wp_enqueue_script('mustache', plugins_url('js/mustache.min.js', __FILE__), array('jquery'));
  448. global $wp_scripts;
  449. wp_enqueue_script('jquery-ui-datepicker');
  450. // get registered script object for jquery-ui
  451. //$ui = $wp_scripts->query('jquery-ui-core');
  452. // tell WordPress to load the Smoothness theme from Google CDN
  453. //$protocol = is_ssl() ? 'https' : 'http';
  454. // $url = "$protocol://ajax.googleapis.com/ajax/libs/jqueryui/{$ui->ver}/themes/smoothness/jquery-ui.min.css";
  455. $url = plugins_url('jquery-ui-1.11.4.theme/jquery-ui.min.css', __FILE__);
  456. wp_enqueue_style('jquery-ui-smoothness', $url, false, null);
  457. }
  458. private function register_office_js_css(){
  459. global $pagename;
  460. if ($pagename != 'office'){
  461. return;
  462. }
  463. wp_enqueue_style( 'bts_office', plugins_url('css/bts_office.css', __FILE__));
  464. wp_enqueue_script( 'bts_office', plugins_url('js/bts_office.js', __FILE__), array( 'jquery' , 'bts' ));
  465. wp_enqueue_script('mustache', plugins_url('js/mustache.min.js', __FILE__), array('jquery'));
  466. global $wp_scripts;
  467. wp_enqueue_script('jquery-ui-datepicker');
  468. // get registered script object for jquery-ui
  469. //$ui = $wp_scripts->query('jquery-ui-core');
  470. // tell WordPress to load the Smoothness theme from Google CDN
  471. //$protocol = is_ssl() ? 'https' : 'http';
  472. // $url = "$protocol://ajax.googleapis.com/ajax/libs/jqueryui/{$ui->ver}/themes/smoothness/jquery-ui.min.css";
  473. $url = plugins_url('jquery-ui-1.11.4.theme/jquery-ui.min.css', __FILE__);
  474. wp_enqueue_style('jquery-ui-smoothness', $url, false, null);
  475. }
  476. private function register_task_js_css(){
  477. global $pagename;
  478. if ($pagename != 'task'){
  479. return;
  480. }
  481. $this->bts_job_start = get_query_var( 'bts_job_start' );
  482. $this->bts_job_finish = get_query_var( 'bts_job_finish' );
  483. $this->bts_week_id = get_query_var('bts_week_id');
  484. wp_enqueue_style( 'bts_task', plugins_url('css/bts_task.css', __FILE__));
  485. wp_enqueue_script( 'bts_task', plugins_url('js/bts_task.js', __FILE__), array( 'jquery' , 'bts' ));
  486. wp_enqueue_script('mustache', plugins_url('js/mustache.min.js', __FILE__), array('jquery'));
  487. wp_localize_script('bts_task','bts_task1',array(
  488. 'ajax_url' => admin_url( 'admin-ajax.php' ),
  489. 'nonce' => wp_create_nonce('bts_task'),
  490. 'week_id' => $this->bts_week_id,
  491. 'bts_job_start' => $this->bts_job_start,
  492. 'bts_job_finish' => $this->bts_job_finish,
  493. ) );
  494. }
  495. private function register_feedback_card_js_css()
  496. {
  497. global $pagename;
  498. if ($pagename != 'feedback_card'){
  499. return;
  500. }
  501. $this->bts_job_start = get_query_var( 'bts_job_start' );
  502. $this->bts_job_finish = get_query_var( 'bts_job_finish' );
  503. $this->bts_week_id = get_query_var('bts_week_id');
  504. wp_enqueue_style( 'feedback_card', plugins_url('css/feedback_card.css', __FILE__));
  505. wp_enqueue_script( 'feedback_card', plugins_url('js/feedback_card.js', __FILE__), array( 'jquery' , 'bts' ));
  506. wp_enqueue_script('mustache', plugins_url('js/mustache.min.js', __FILE__), array('jquery'));
  507. wp_localize_script('feedback_card','feedback_card',array(
  508. 'ajax_url' => admin_url( 'admin-ajax.php' ),
  509. 'nonce' => wp_create_nonce('feedback_card'),
  510. 'week_id' => $this->bts_week_id,
  511. 'bts_job_start' => $this->bts_job_start,
  512. 'bts_job_finish' => $this->bts_job_finish,
  513. ) );
  514. }
  515. private function register_xeroc_js_css(){
  516. global $pagename;
  517. if ($pagename != 'xeroc'){
  518. return;
  519. }
  520. wp_enqueue_style( 'bts_xeroc', plugins_url('css/xeroc.css', __FILE__));
  521. wp_enqueue_script( 'bts_xeroc', plugins_url('js/xeroc.js', __FILE__), array( 'jquery' , 'bts' ));
  522. wp_enqueue_script('mustache', plugins_url('js/mustache.min.js', __FILE__), array('jquery'));
  523. wp_enqueue_script('scrollintoview', plugins_url('js/scrollintoview.js', __FILE__), array('jquery'));
  524. global $wp_scripts;
  525. wp_enqueue_script('jquery-ui-datepicker');
  526. $url = plugins_url('jquery-ui-1.11.4.theme/jquery-ui.min.css', __FILE__);
  527. wp_enqueue_style('jquery-ui-smoothness', $url, false, null);
  528. }
  529. public function sync_users()
  530. {
  531. //dummy sync
  532. return;
  533. }
  534. // Usage: `wp sync_users --mininterval=123
  535. public function sync_user_cli($args = array(), $assoc_args = array()){
  536. $arguments = wp_parse_args( $assoc_args, array(
  537. 'mininterval' => 600,
  538. 'employeeonly' => false,
  539. 'clientsonly' => false,
  540. ) );
  541. $this->xero->sync_users($arguments['mininterval'], $arguments['employeeonly'], $arguments['clientsonly']);
  542. return;
  543. }
  544. public function email_jobs($args = array(), $assoc_args = array()){
  545. $users = get_users(array('role' => 'staff'));
  546. foreach ($users as $u){
  547. $n = new UserJob($u->user_login);
  548. $resp = $n->list_jobs_by_staff("2019-07-22 00:00:00", "2019-07-28 23:59:59");
  549. if ($resp['status']=='success' && $resp['job_count'] >0 ){
  550. if( $u->user_login != "9aa3308e-cc19-4c21-a110-f2c6abec4337" )
  551. continue;
  552. $msg = sprintf("Staff = %s, Login=%s, email=%s Job=%d\n", $u->display_name, $u->user_login, $u->user_email, $resp['job_count']);
  553. echo $msg;
  554. $this->send_email_with_job_link($u, "2019-07-22", "2019-07-28");
  555. }
  556. }
  557. return;
  558. }
  559. public function produce_invoice($args = array(), $assoc_args = array())
  560. {
  561. $users = get_users(array('role' => 'client'));
  562. foreach ($users as $u)
  563. {
  564. $pay = get_user_meta($u->id, 'payment',true);
  565. echo sprintf("%s: %s\n", $u->display_name, $pay);
  566. }
  567. }
  568. private function send_email_with_job_link($staff, $start, $finish)
  569. {
  570. $message = file_get_contents(plugin_dir_path(__FILE__) . "/html/email_job.html");
  571. $message = str_ireplace("{{display_name}}", $staff->display_name, $message);
  572. $message = str_ireplace("{{user_login}}", $staff->user_login, $message);
  573. $message = str_ireplace("{{job_start}}", $start, $message);
  574. $message = str_ireplace("{{job_finish}}", $finish, $message);
  575. $headers = ['Bcc: patrick@biukop.com.au, timesheet@acaresydney.com.au'];
  576. $subject = $staff->display_name . " Job arrangement $start ~ $finish";
  577. //wp_mail("sp@lawipac.com", $subject, $message, $headers);
  578. //wp_mail("timesheet@acaresydney.com.au", $subject, $message, $headers);
  579. wp_mail($staff->user_email, $subject, $message, $headers);
  580. }
  581. private function send_email_feedback_url($client)
  582. {
  583. $message = file_get_contents(plugin_dir_path(__FILE__) . "/html/email_feedback_url.html");
  584. $message = str_ireplace("{{display_name}}", $client->display_name, $message);
  585. $message = str_ireplace("{{user_login}}", $client->user_login, $message);
  586. $headers = ['Bcc: helenwang41@hotmail.com, timesheet@acaresydney.com.au'];
  587. $subject = $client->display_name . " Feedback Link";
  588. wp_mail( "helen@acaresydney.com.au", $subject, $message, $headers);
  589. //wp_mail( "patrick@biukop.com.au", $subject, $message, $headers);
  590. }
  591. public function bts_staff_item($attr){
  592. return $this->template('staff_item', 'staff.html');
  593. }
  594. public function bts_client_item($attr){
  595. return $this->template('client_item', 'client.html');
  596. }
  597. public function bts_job_item($attr){
  598. $html =$this->template('job_item', 'job.html');
  599. //$html = str_replace('[bts-tos-options]', $this->bts_tos_options([]), $html);
  600. $html = do_shortcode($html);
  601. return $html;
  602. }
  603. public function bts_rate_options($attr){
  604. $result = "<select> \n";
  605. $options = get_option('bts_payitem_earnings_rate');
  606. foreach($options as $o){
  607. if ($o['CurrentRecord'] !='true')
  608. continue;
  609. if ($o['RateType'] != 'RATEPERUNIT')
  610. continue;
  611. if (stripos($o['TypeOfUnits'],'hour') != false) //unit contains hour Hour
  612. continue;
  613. $result.=sprintf("<option value='%s'> $%3.2f-%s</option>",
  614. $o['EarningsRateID'], $o['RatePerUnit'], $o['Name']);
  615. }
  616. $result .="</select>";
  617. return $result;
  618. }
  619. private function get_rate_name_by_id($id)
  620. {
  621. $options = get_option('bts_payitem_earnings_rate');
  622. foreach($options as $o){
  623. if ( $o['EarningsRateID'] == $id )
  624. return sprintf("$%3.2f-%s", $o['RatePerUnit'], $o['Name']);
  625. }
  626. }
  627. public function bts_select_staff($attr){
  628. $result = "<select> \n";
  629. $staff = $this->get_people_by_role('staff');
  630. foreach ($staff as $u){
  631. $result .= sprintf("<option value=%s> %s</option>", $u->user_login, $u->first_name . " " . $u->last_name);
  632. }
  633. $result .="</select>";
  634. return $result;
  635. }
  636. public function bts_select_client($attr){
  637. $result = "<select> \n";
  638. $staff = $this->get_people_by_role('client');
  639. foreach ($staff as $u){
  640. $result .= sprintf("<option value=%s> %s</option>", $u->user_login, $u->display_name);
  641. }
  642. $result .="</select>";
  643. return $result;
  644. }
  645. public function bts_type_of_service($attr){
  646. $n = new NdisPrice(2019);
  647. return $n->get_html();
  648. }
  649. public function bts_user_name($attr)
  650. {
  651. $user = wp_get_current_user();
  652. return $user->display_name;
  653. }
  654. public function bts_staff_job_summary($attr)
  655. {
  656. $result ="<span>
  657. If there is more than one job, please click on 'confirm' to make sure it is included in your payment.
  658. </span>";
  659. return $result;
  660. }
  661. public function bts_feedback_card($attr)
  662. {
  663. return $this->template('bts_feedback_card', 'feedback_card.html');
  664. }
  665. public function bb_timesheet_canvas($attr)
  666. {
  667. return file_get_contents(plugin_dir_path(__FILE__) . "/html/timesheet.html");
  668. }
  669. public function bts_staff_hours_template($attr){
  670. return $this->template('bts_staff_hours_template', 'bts_staff_hours_template.html');
  671. }
  672. public function bts_client_invoice_template($attr){
  673. return $this->template('bts_client_invoice_template', 'bts_client_invoice_template.html');
  674. }
  675. public function bts_csv_template($attr){
  676. return $this->template('bts_csv_template', 'bts_csv_template.html');
  677. }
  678. public function bts_invoiced_client($attr)
  679. {
  680. $attr = shortcode_atts([
  681. 'preferred' => 'true',
  682. ], $attr);
  683. $result = "";
  684. $users = $users = get_users(array('role' => 'client'));
  685. $row = <<<ZOT
  686. <tr id="nameonly_%s" data-client-id='%s' class="invoice_nameonly_row %s">
  687. <td class="client_nameonly" data-client-id='%s'>
  688. <i class="vc_tta-icon fa fa-plus-square"></i> %s
  689. </td>
  690. </tr>
  691. <tr id="dummyui_%s" data-client-id='%s' class="invoice_nameonly_row_dummy %s">
  692. <td class="client_nameonly" data-client-id='%s'>
  693. <i class="vc_tta-icon fa fa-plus-square"></i> %s is loading .... please wait...
  694. </td>
  695. </tr>
  696. ZOT;
  697. foreach ($users as $u)
  698. {
  699. $payment = get_user_meta($u->ID, 'payment', true);
  700. if ( $attr['preferred'] == 'true' ){
  701. if( $payment == 'invoice' ){
  702. $invoice_preferred = "invoice_preferred";
  703. $result .= sprintf($row,
  704. $u->user_login, $u->user_login, $invoice_preferred, $u->user_login, $u->display_name,
  705. $u->user_login, $u->user_login, $invoice_preferred, $u->user_login, $u->display_name);
  706. }
  707. }else{
  708. $invoice_preferred = "";
  709. if( $payment != 'invoice' ){
  710. $result .= sprintf($row,
  711. $u->user_login, $u->user_login, $invoice_preferred, $u->user_login, $u->display_name,
  712. $u->user_login, $u->user_login, $invoice_preferred, $u->user_login, $u->display_name);
  713. }
  714. }
  715. }
  716. return $result;
  717. }
  718. //generate template based on html file
  719. private function template($id, $file)
  720. {
  721. $text = '<script id="' . $id .'" type="text/x-biukop-template">';
  722. $text .= file_get_contents(plugin_dir_path(__FILE__) . "/html/$file");
  723. $text .= '</script>';
  724. return $text;
  725. }
  726. function list_staff(){
  727. check_ajax_referer('acaresydney');
  728. // Handle the ajax request
  729. $response = array(
  730. 'status' =>'error',
  731. 'users' => [],
  732. );
  733. //search all users that are staff
  734. $staffq = new \WP_User_Query(array('role'=>'staff','meta_key'=>'first_name', 'orderby'=>'meta_value', 'order'=>'ASC'));
  735. $staff = $staffq->get_results();
  736. if (! empty($staff)){
  737. $response['status'] = 'success';
  738. foreach( $staff as $s){
  739. $response['users'][] = array(
  740. 'login' => $s->user_login,
  741. 'firstname'=> $s->first_name,
  742. 'lastname'=> $s->last_name,
  743. 'display_name' => $s->display_name,
  744. 'mobile'=> get_user_meta($s->ID, 'mobile', true),
  745. 'email'=> $s->user_email,
  746. 'wages'=> 0,
  747. 'hour' => 0 ,
  748. 'OT' => 0 ,
  749. 'petrol'=> 0 ,
  750. 'rating'=> 0,
  751. 'unconfirmedjob'=> 0,
  752. );
  753. }
  754. }
  755. wp_send_json($response);
  756. wp_die();
  757. }
  758. function list_client(){
  759. check_ajax_referer('acaresydney');
  760. // Handle the ajax request
  761. $response = array(
  762. 'status' =>'error',
  763. 'users' => [],
  764. );
  765. //search all users that are staff
  766. $clientq = new \WP_User_Query(array('role'=>'client', 'meta_key'=>'first_name', 'orderby'=>'meta_value', 'order'=>'ASC'));
  767. $client = $clientq->get_results();
  768. if (! empty($client)){
  769. $response['status'] = 'success';
  770. foreach( $client as $s){
  771. $data_item = array(
  772. 'login' => $s->user_login,
  773. 'firstname'=> $s->first_name,
  774. 'lastname'=> $s->last_name,
  775. 'display_name'=> $s->display_name,
  776. 'mobile'=> get_user_meta($s->ID, 'mobile', true),
  777. 'email'=> $s->user_email,
  778. 'account'=> get_user_meta($s->ID, 'account', true),
  779. 'address' => get_user_meta($s->ID, 'address', true),
  780. 'payment'=>get_user_meta($s->ID, 'payment', true),
  781. 'rating'=> 0,
  782. 'unconfirmedjob'=> 0,
  783. );
  784. $response['users'][] = $data_item;
  785. }
  786. }
  787. wp_send_json($response);
  788. wp_die();
  789. }
  790. //ajax
  791. function list_tos() {
  792. check_ajax_referer('acaresydney');
  793. // Handle the ajax request
  794. $response = array(
  795. 'status' =>'success',
  796. 'tos' => [],
  797. );
  798. $price = $this->get_ndis_price();
  799. $response['tos']= $price->get_tos_array();
  800. wp_send_json($response);
  801. }
  802. private function get_people_by_role($role){
  803. //search all users that are staff
  804. $staffq = new \WP_User_Query(array('role'=>$role, 'meta_key'=>'first_name', 'orderby'=>'meta_value', 'order'=>'ASC'));
  805. $staff = $staffq->get_results();
  806. return $staff;
  807. }
  808. //ajax get earnings rates
  809. function get_payitem_earnings_rate()
  810. {
  811. $response= array(
  812. 'status' => 'success',
  813. 'options'=> get_option('bts_payitem_earnings_rate'),
  814. );
  815. wp_send_json($response);
  816. }
  817. //ajax job CRUD
  818. function save_job()
  819. {
  820. check_ajax_referer('acaresydney');
  821. $r = $_POST['record'];
  822. $response = array();
  823. $d = array(
  824. 'tos' => $r['tos'],
  825. 'start' => $r['start'],
  826. 'finish' => $r['finish'],
  827. 'rate' => $r['rate'],
  828. 'staff' => $r['staff'],
  829. 'client' => $r['client'],
  830. 'ack' => $r['ack']=='true'?1:0,
  831. 'rating'=>$r['rating'],
  832. );
  833. //this is an update
  834. if ( isset($r['id']) && trim($r['id']) !='' && is_numeric($r['id'])){
  835. $response['isNew'] = false; //add or update?
  836. $result = $this->db->update($this->table_name, $d, array('id' =>$r['id']));
  837. if ($result !== false && $this->db->last_error == ''){
  838. $d['id'] = $r['id'];
  839. $response['status'] = 'success';
  840. //do data type conversion, string to int
  841. $response['newdata'] = $this->get_ts_record($r['id']);
  842. $response['errors'] = array(); //empty array
  843. }else{
  844. $response['status'] = 'error';
  845. $repsonse['errors'] = array(
  846. 'db' => "network database error" . $this->db->last_error,
  847. );
  848. }
  849. }else{
  850. $response['isNew'] = true;
  851. $result = $this->db->insert($this->table_name, $d);
  852. $lastid = $this->db->insert_id;
  853. if ($result != false && $this->db->last_error == ''){
  854. $response['status'] = 'success';
  855. $response['newdata'] = $this->get_ts_record($lastid);
  856. }else{
  857. $response['status'] = 'error';
  858. $response['errors'] = array(
  859. 'db' => 'network database error ' . $this->db->last_error,
  860. );
  861. }
  862. }
  863. wp_send_json($response);
  864. wp_die();
  865. }
  866. private function get_ts_record($id){
  867. $sql = "SELECT * FROM $this->table_name WHERE id=%d";
  868. $row = $this->db->get_row($this->db->prepare ($sql, array($id)));
  869. $response = [];
  870. if ($row != null){
  871. $response = array(
  872. 'id' => (int)$row->id,
  873. 'tos' => $row->tos,
  874. 'start' => $row->start,
  875. 'finish' => $row->finish,
  876. 'rate' => $row->rate,
  877. 'staff' => $row->staff,
  878. 'client' => $row->client,
  879. 'ack' => (int)$row->ack,
  880. 'rating' =>(int) $row->rating,
  881. );
  882. }
  883. return $response;
  884. }
  885. //ajax delete job
  886. function delete_job(){
  887. check_ajax_referer('acaresydney');
  888. $id = $_POST['jobid'];
  889. $result = $this->db->delete($this->table_name, array('id'=> $id));
  890. $response=array(
  891. 'status' => 'success',
  892. 'id' => $id,
  893. 'action'=> 'delete',
  894. 'error' => '',
  895. );
  896. if ($result == 1){
  897. wp_send_json($response);
  898. }else{
  899. $response['status'] = 'error';
  900. $response['error'] = $this->db->last_error;
  901. wp_send_json($response);
  902. }
  903. wp_die();
  904. }
  905. //ajax email staff their job arrangement
  906. function email_job()
  907. {
  908. check_ajax_referer('acaresydney');
  909. $staff = $_POST['staff'];
  910. $start = $_POST['start'];
  911. $finish = $_POST['finish'];
  912. $response=array(
  913. 'status' => 'success',
  914. 'staff' => $staff,
  915. 'start' => $start,
  916. 'finish' => $finish,
  917. 'error' => '',
  918. 'sent' => false,
  919. 'emailstatus'=>"Bypass (no job)",
  920. );
  921. $u = get_user_by('login', $staff);
  922. if ($this->is_staff($u)){
  923. $n = new UserJob($staff);
  924. $resp = $n->list_jobs_by_staff("$start 00:00:00", "$finish 23:59:59");
  925. if ($resp['status']=='success' && $resp['job_count'] >0 ){
  926. $msg = sprintf("Email to <strong>%s</strong> (with job=%d) \n", $u->user_email, $resp['job_count']);
  927. $this->send_email_with_job_link($u, $start, $finish);
  928. $response['sent'] = true;
  929. $response['emailstatus'] = $msg;
  930. }
  931. }
  932. wp_send_json($response);
  933. }
  934. //ajax email feedback url
  935. function email_feedback_url()
  936. {
  937. check_ajax_referer('acaresydney');
  938. $client = $_POST['client'];
  939. $response=array(
  940. 'status' => 'success',
  941. 'error' => '',
  942. 'sent' => false,
  943. 'emailstatus' =>'not sent',
  944. );
  945. $u = get_user_by('login', $client);
  946. if ($this->is_client($u)){
  947. $status = $this->send_email_feedback_url($u);
  948. $response['emailstatus'] = $status;
  949. }
  950. wp_send_json($response);
  951. }
  952. //ajax browse job with different filters
  953. function list_job(){
  954. check_ajax_referer('acaresydney');
  955. $start = $_POST['start'] . " 00:00:00";
  956. $finish = $_POST['finish']. " 23:59:59";
  957. $response = array(
  958. 'status'=>'success',
  959. 'jobs' => [],
  960. );
  961. $sql = "SELECT * FROM $this->table_name WHERE start>='%s' and start <='%s' order by start ASC ,staff ASC";
  962. $query = $this->db->prepare ($sql, array($start, $finish));
  963. $response['sql'] = $query;
  964. $jobs = $this->db->get_results($query);
  965. if (! empty($jobs)){
  966. $response['status'] = 'success';
  967. foreach( $jobs as $s){
  968. $response['jobs'][] = array(
  969. 'id' => $s->id,
  970. 'tos' => $s->tos,
  971. 'start'=> $s->start,
  972. 'finish'=> $s->finish,
  973. 'rate'=> $s->rate,
  974. 'staff'=> $s->staff,
  975. 'client'=> $s->client,
  976. 'ack' => $s->ack,
  977. 'rating' =>$s->rating,
  978. );
  979. }
  980. }
  981. wp_send_json($response);
  982. wp_die();
  983. }
  984. public function list_job_by_staff()
  985. {
  986. check_ajax_referer('acaresydney');
  987. $start = $_POST['start'];
  988. $finish = $_POST['finish'];
  989. //$start="2019-07-01 00:00:00";
  990. //$finish="2019-07-14 23:59:59";
  991. $user = wp_get_current_user();// should be staff;
  992. if ( $this->is_staff($user) || $this->is_admin($user) ){
  993. $n = new UserJob($user->user_login);
  994. $response = $n->list_jobs_by_staff($start, $finish);
  995. wp_send_json($response);
  996. }else{
  997. $response = array(
  998. 'status' => 'error',
  999. 'errmsg' => 'invalid access',
  1000. 'user' => $user,
  1001. );
  1002. wp_send_json($response);
  1003. }
  1004. wp_die();
  1005. }
  1006. public function list_job_by_client()
  1007. {
  1008. check_ajax_referer('acaresydney');
  1009. $start = $_POST['start'];
  1010. $finish = $_POST['finish'];
  1011. //$start="2019-07-01 00:00:00";
  1012. //$finish="2019-07-14 23:59:59";
  1013. $user = wp_get_current_user();// should be staff;
  1014. if ( $this->is_client($user) || $this->is_admin($user) ){
  1015. $n = new UserJob($user->user_login);
  1016. $response = $n->list_jobs_by_client($start, $finish);
  1017. wp_send_json($response);
  1018. }else{
  1019. $response = array(
  1020. 'status' => 'error',
  1021. 'errmsg' => 'invalid access',
  1022. 'user' => $user,
  1023. );
  1024. wp_send_json($response);
  1025. }
  1026. wp_die();
  1027. }
  1028. private function is_staff($user)
  1029. {
  1030. return ($user->ID !=0 && in_array('staff', $user->roles));
  1031. }
  1032. private function is_client($user)
  1033. {
  1034. return ($user->ID !=0 && in_array('client', $user->roles));
  1035. }
  1036. private function is_admin($user)
  1037. {
  1038. $allowed_roles = array('administrator', 'acare_owner');
  1039. if( array_intersect($allowed_roles, $user->roles ) ) {
  1040. return true;
  1041. }
  1042. }
  1043. public function staff_ack_job()
  1044. {
  1045. check_ajax_referer('acaresydney');
  1046. $jobs = $_POST['jobs'];
  1047. $response = array(
  1048. 'status'=>'success',
  1049. 'jobs'=>$jobs,
  1050. );
  1051. $yes=[];
  1052. $no=[];
  1053. foreach($jobs as $job){
  1054. if ( $job['ack'] == "true")
  1055. $yes[] =(int) $job['id'];
  1056. else
  1057. $no[] = (int) $job['id'];
  1058. }
  1059. $err = $this->ack_multiple_job($yes, $no);
  1060. if ($this->db->last_error !='')
  1061. {
  1062. $response['status']= 'error';
  1063. $response['err_msg']= $err;
  1064. }
  1065. $response['yes'] = $yes;
  1066. $response['no'] = $no;
  1067. wp_send_json($response);
  1068. wp_die();
  1069. }
  1070. public function ack_multiple_job($yes, $no)
  1071. {
  1072. $str_yes_ids = implode(",", $yes);
  1073. $str_no_ids = implode(",", $no);
  1074. $err = "";
  1075. if (count($yes) >0 ){
  1076. $sql = "UPDATE $this->table_name SET ack=1 WHERE id IN ( $str_yes_ids) ; ";
  1077. $r = $this->db->get_results($sql);
  1078. $err = $this->db->last_error;
  1079. }
  1080. if (count($no) >0 ){
  1081. $sql = "UPDATE $this->table_name SET ack=0 WHERE id IN ( $str_no_ids) ; ";
  1082. $r = $this->db->get_results($sql);
  1083. $err .= $this->db->last_error;
  1084. }
  1085. return $err;
  1086. }
  1087. public function client_ack_job()
  1088. {
  1089. check_ajax_referer('acaresydney');
  1090. $job_id = $_POST['job_id'];
  1091. $rating = $_POST['rating'];
  1092. $response = array(
  1093. 'status'=>'success',
  1094. );
  1095. $sql= "UPDATE $this->table_name SET rating=%d WHERE id = %d ; ";
  1096. $sql= $this->db->prepare($sql, array($rating, $job_id));
  1097. $result = $this->db->get_results($sql);
  1098. $response['rating'] = (int) $rating;
  1099. if ($this->db->last_error !='')
  1100. {
  1101. $response['status']= 'error';
  1102. $response['err_msg']= $this->db->last_error;
  1103. $response['rating'] = 0;
  1104. }
  1105. wp_send_json($response);
  1106. }
  1107. public function get_timesheet_from_xero()
  1108. {
  1109. check_ajax_referer('acaresydney');
  1110. //check if we need sync
  1111. $sync = $_POST['sync'];
  1112. if ($sync != "true")
  1113. $sync = false;
  1114. else
  1115. $sync = true;
  1116. //set up payroll calendar
  1117. $pc = $this->xero->get_payroll_calendar();
  1118. $start = $pc->getStartDate()->format('Y-m-d');
  1119. $finish = new \DateTime($start);
  1120. $finish = $finish->modify("+13 days")->format('Y-m-d');
  1121. $paydate = $pc->getPaymentDate()->format('Y-m-d');
  1122. //prepare response
  1123. $response = array(
  1124. 'status' => 'success',
  1125. 'payroll_calendar' => array(
  1126. 'start' => $start,
  1127. 'finish' => $finish,
  1128. 'paydate'=> $paydate,
  1129. ),
  1130. );
  1131. $xx = new \Biukop\TimeSheet($this->xero->get_xero_handle(), $finish);
  1132. $local_ts = $this->create_timesheet_from_db($start, $finish);
  1133. if ($sync){
  1134. $xx->set_local_timesheet($local_ts);
  1135. $xx->save_to_xero();
  1136. $xx->refresh_remote();
  1137. }
  1138. $days=[];
  1139. $d = new \DateTime($start);
  1140. for ($i=1; $i<=14; $i++){
  1141. $days["days_$i"] = $d->format("d/M");
  1142. $d->modify("+1 day");
  1143. }
  1144. $lines=[];
  1145. foreach ($local_ts as $staff_login => $details)
  1146. {
  1147. $item = array(
  1148. 'staff_name' => $this->get_user_name_by_login ($staff_login),
  1149. 'staff_id' => $staff_login,
  1150. 'Xero_Status' => 'Empty',
  1151. 'rowspan' =>1,
  1152. 'local_total' =>0,
  1153. 'remote_total'=>0,
  1154. 'ratetype' => [],
  1155. );
  1156. $buddy = $xx->get_buddy_timesheets($staff_login, new \DateTime($start), new \DateTime($finish));
  1157. if ($buddy != NULL){
  1158. $item['Xero_Status'] = $buddy->getStatus();
  1159. }else{
  1160. $item['Xero_Status'] = "Not Exist";
  1161. }
  1162. foreach($details as $rate => $hours){
  1163. $item['rowspan'] ++;
  1164. $ratetype_item=[];
  1165. $ratetype_item['rate_name'] = $this->get_rate_name_by_id($rate);
  1166. //for local
  1167. for ($i=1; $i<=14; $i++)
  1168. {
  1169. $ratetype_item["local_$i"] = $hours[$i-1];
  1170. $ratetype_item["local_$i"] = number_format($ratetype_item["local_$i"], 2);
  1171. $item['local_total'] += $hours[$i-1];
  1172. }
  1173. $item['local_total'] = number_format($item['local_total'], 2);
  1174. //for remote
  1175. if ( $buddy != NULL )
  1176. {
  1177. $remote_lines = $buddy->getTimesheetLines();
  1178. foreach($remote_lines as $rl)
  1179. {
  1180. if ( $rl->getEarningsRateID() == $rate){
  1181. for ($i=1; $i<=14; $i++)
  1182. {
  1183. $ratetype_item["xero_$i"] = $rl->getNumberOfUnits()[$i-1];
  1184. $item['remote_total'] += $rl->getNumberOfUnits()[$i-1];
  1185. if ($ratetype_item["xero_$i"] != $ratetype_item["local_$i"]){
  1186. $ratetype_item["xero_{$i}_mismatch"] = "mismatch";
  1187. }
  1188. }
  1189. break;//we found it
  1190. }
  1191. }
  1192. }
  1193. $item['ratetype'][] = $ratetype_item;
  1194. }
  1195. $item = array_merge($item, $days);
  1196. $lines[]=$item;
  1197. }
  1198. $ts = json_decode(file_get_contents(dirname(__FILE__) . "/sample/timesheets.json"));
  1199. $response['ts'] = $ts;
  1200. $response['lines'] = $lines;
  1201. wp_send_json($response);
  1202. }
  1203. public function approve_all_timesheet()
  1204. {
  1205. check_ajax_referer('acaresydney');
  1206. //set up payroll calendar
  1207. $pc = $this->xero->get_payroll_calendar();
  1208. $start = $pc->getStartDate()->format('Y-m-d');
  1209. $finish = new \DateTime($start);
  1210. $finish = $finish->modify("+13 days")->format('Y-m-d');
  1211. $paydate = $pc->getPaymentDate()->format('Y-m-d');
  1212. //prepare response
  1213. $response = array(
  1214. 'status' => 'success',
  1215. 'payroll_calendar' => array(
  1216. 'start' => $start,
  1217. 'finish' => $finish,
  1218. 'paydate'=> $paydate,
  1219. ),
  1220. );
  1221. $xx = new \Biukop\TimeSheet($this->xero->get_xero_handle(), $finish);
  1222. $xx->approve_all();
  1223. wp_send_json($response);
  1224. }
  1225. static public function get_user_name_by_login($login)
  1226. {
  1227. $user = get_user_by('login', $login);
  1228. if ($user->ID !=0 )
  1229. return $user->display_name;
  1230. else
  1231. return "Invalid Name";
  1232. }
  1233. //ajax
  1234. public function get_invoice_item()
  1235. {
  1236. check_ajax_referer('acaresydney');
  1237. $client = $_POST['client'];
  1238. //$client = "8cb3d205-6cdc-4187-ae39-9216923dd86d";
  1239. $start = $_POST['start']; //2019-07-01';
  1240. $finish= $_POST['finish'];//2019-07-31';
  1241. $sql = "SELECT * from $this->table_name WHERE tos != '00_000_0000_0_0' and start>='$start 00:00:00' and start<='$finish 23:59:59' and client='$client' ORDER BY start";
  1242. $rows = $this->db->get_results($sql);
  1243. $response=[
  1244. 'status' =>'success',
  1245. 'client_login' => $client,
  1246. 'client_name' => $this->get_user_name_by_login($client),
  1247. 'jobs'=>[],
  1248. 'err'=>''
  1249. ];
  1250. $price = $this->get_ndis_price();
  1251. $summary=[];// by ndis code
  1252. foreach($rows as $r){
  1253. $quantity = $this->get_job_hours($r->start, $r->finish);
  1254. $unit = $price->get_tos_unit($r->tos);
  1255. if ($unit != "Hour")
  1256. {
  1257. $quantity = 1;
  1258. }
  1259. $unitprice = $price->get_tos_price($r->tos);
  1260. $description = $this->get_job_description_for_invoice($price, $r);
  1261. $data = [
  1262. 'tos' => $price->get_tos_full_str($r->tos),
  1263. 'start' => $r->start,
  1264. 'finish' => $r->finish,
  1265. 'hours' => $quantity,
  1266. 'unitprice'=> $price->get_tos_price($r->tos),
  1267. 'staff_name' => $this->get_user_name_by_login($r->staff),
  1268. 'price' => sprintf("%.2f", $quantity * $unitprice),
  1269. ];
  1270. $response['jobs'][] = $data;
  1271. $summary[$r->tos] += $quantity;
  1272. }
  1273. if (count($response['jobs']) ==0)
  1274. {
  1275. $response['nojob'] = true;
  1276. }
  1277. foreach ($summary as $key => $val)
  1278. {
  1279. $response['summary'][] = array(
  1280. 'ndis' => $key,
  1281. 'tos' => $price->get_tos_full_str($key),
  1282. 'Hours'=> sprintf("%0.2f", $val),
  1283. );
  1284. }
  1285. if (count($summary) > 0){
  1286. $response['has_summary'] = true;
  1287. }
  1288. wp_send_json($response);
  1289. }
  1290. public function create_invoice_in_xero()
  1291. {
  1292. check_ajax_referer('acaresydney');
  1293. $client = $_POST['client'];
  1294. //$client = "8cb3d205-6cdc-4187-ae39-9216923dd86d";
  1295. $start = $_POST['start']; //2019-07-01';
  1296. $finish= $_POST['finish'];//2019-07-31';
  1297. //
  1298. $response=[
  1299. 'status'=>success,
  1300. 'invoice_number' => '',
  1301. 'err'=> '',
  1302. ];
  1303. try{
  1304. $invoice = $this->create_invoice_by_client($client, $start, $finish);
  1305. $response['invoice_number'] = sprintf("<a href='https://go.xero.com/AccountsReceivable/Edit.aspx?InvoiceID=%s' target='_blank'>%s</a>",
  1306. $invoice->getInvoiceID(), $invoice->getInvoiceNumber());
  1307. }catch(\Exception $e){
  1308. $response['status'] = 'error';
  1309. $response['err'] = "XERO Invoice Error";
  1310. }
  1311. wp_send_json($response);
  1312. }
  1313. public function create_invoice_by_client($client_login, $start, $finish)
  1314. {
  1315. $user = get_user_by('login', $client_login);
  1316. if ( !$this->is_client($user) )
  1317. return NULL;
  1318. // $payment = get_user_meta($user->ID, "payment", true);
  1319. // if ($payment != "invoice")
  1320. // return NULL;
  1321. $sql = "SELECT * from $this->table_name WHERE tos != '00_000_0000_0_0' and start>='$start 00:00:00' and start<='$finish 23:59:59' and client='$client_login' ORDER BY start";
  1322. $rows = $this->db->get_results($sql);
  1323. $xero = $this->xero->get_xero_handle();
  1324. //crate invoice
  1325. $invoice = new \XeroPHP\Models\Accounting\Invoice($xero);
  1326. $contact= $xero->loadByGUID('Accounting\\Contact', $client_login);
  1327. $now = new \DateTime();
  1328. $due = new \DateTime();
  1329. $due->modify("+14 days");
  1330. $invoice->setType("ACCREC")
  1331. ->setStatus("DRAFT")
  1332. ->setContact($contact)
  1333. ->setDate($now)
  1334. ->setDueDate($due);
  1335. $to_save=[];//all invoices to save;
  1336. $price = new NdisPrice($now->format("Y"));//current year;
  1337. foreach($rows as $r){
  1338. $quantity = $this->get_job_hours($r->start, $r->finish);
  1339. $unit = $price->get_tos_unit($r->tos);
  1340. if ($unit != "Hour")
  1341. {
  1342. $quantity = 1;
  1343. }
  1344. $unitprice = $price->get_tos_price($r->tos);
  1345. $description = $this->get_job_description_for_invoice($price, $r);
  1346. $lineItem = new \XeroPHP\Models\Accounting\Invoice\LineItem($xero);
  1347. $lineItem->setDescription($description)
  1348. ->setQuantity($quantity)
  1349. ->setUnitAmount($unitprice)
  1350. ->setAccountCode(220)
  1351. ->setTaxType("EXEMPTOUTPUT");
  1352. $invoice->addLineItem($lineItem);
  1353. }
  1354. //prevent zero lineitems
  1355. if ( count($invoice->getLineItems()) >0 )
  1356. $invoice->save();
  1357. return $invoice;
  1358. }
  1359. public function get_job_description_for_invoice($price, $job)
  1360. {
  1361. $description = sprintf(
  1362. '%s
  1363. [NDIS code: %s]
  1364. Time: %s - %s
  1365. By Carer : %s',
  1366. $price->get_tos_str($job->tos),
  1367. $job->tos,
  1368. $job->start,
  1369. $job->finish,
  1370. $this->get_user_name_by_login($job->staff)
  1371. );
  1372. return $description;
  1373. }
  1374. public function create_timesheet_from_db($start, $finish){
  1375. $results = [];
  1376. $sql = "SELECT * from $this->table_name WHERE start>='$start 00:00:00' and start<='$finish 23:59:59'";
  1377. $rows = $this->db->get_results($sql);
  1378. foreach ($rows as $r){
  1379. if (!array_key_exists($r->staff, $results)){
  1380. $results[$r->staff] = [];
  1381. }
  1382. if (!array_key_exists($r->rate, $results[$r->staff])){
  1383. $results[$r->staff][$r->rate] = [];
  1384. for ($i=0; $i<14; $i++){
  1385. $results[$r->staff][$r->rate][$i] = 0; //14 days init to 0;
  1386. }
  1387. }
  1388. $idx = $this->convert_date_to_idx($r->start, $start, $finish);
  1389. if ($idx >=0 && $idx <=13){
  1390. $hours = $this->get_job_hours($r->start, $r->finish);
  1391. $results[$r->staff][$r->rate][$idx] += $hours;
  1392. //$results[$r->staff][$r->id] = $hours;
  1393. //$results[$r->staff][$r->id . '_index'] = $idx;
  1394. }else{
  1395. $msg = sprintf("ACARE_TS_ERR: found invalid job index for job id=%d, on %s, idx is %d, start=%s, finish=%s\n",
  1396. $r->id, date('Y-m-d'), $idx, $start, $finish);
  1397. $this->log($msg);
  1398. }
  1399. }
  1400. //wp_send_json($results);
  1401. return $results;
  1402. }
  1403. //convert date (no time) to index, 0 day is $start, 13day is finish, -1 is not found
  1404. public function convert_date_to_idx($date, $start, $finish)
  1405. {//start, finish format must be yyyy-mm-dd
  1406. $idx = -1;
  1407. $cur = new \DateTime($date);
  1408. $cur->setTime(0,0,0);//clear time;
  1409. $s = new \DateTime($start);
  1410. $s->setTime(0,0,0);
  1411. $f = new \DateTime($finish);
  1412. $f->setTime(0,0,0);
  1413. if ( $s <= $cur && $cur <=$f ){
  1414. $datediff = date_diff($s,$cur);
  1415. $idx = $datediff->days;
  1416. }
  1417. return $idx;
  1418. }
  1419. private function get_job_hours($start, $finish)
  1420. {
  1421. $hours = 0;
  1422. $s = strtotime($start);
  1423. $f = strtotime($finish);
  1424. $diff = $f- $s;
  1425. $hours = ($diff * 1.0 / 3600); //can be float;
  1426. return sprintf('%0.2f', $hours);
  1427. }
  1428. public function feedback_url()
  1429. {
  1430. $users = get_users(array('role'=>'client'));
  1431. foreach($users as $u){
  1432. echo sprintf("Hi %s:\n\nPlease rate our service, https://acaresydney.com.au/feedback_card/%s/\n\nAcareSydney\n\n", $u->display_name, $u->user_login);
  1433. }
  1434. }
  1435. static public function log($msg){
  1436. openlog("ACARE_TS", LOG_PID | LOG_PERROR, LOG_SYSLOG);
  1437. //something wrong, we dont touch it, but give some error here
  1438. syslog(LOG_WARNING, $msg);
  1439. closelog();
  1440. }
  1441. }
  1442. $bb = new AcareOffice();
  1443. if ( defined( 'WP_CLI' ) && WP_CLI ) {
  1444. \WP_CLI::add_command( 'sync_users', array($bb, 'sync_user_cli'));
  1445. \WP_CLI::add_command( 'email_jobs', array($bb, 'email_jobs'));
  1446. \WP_CLI::add_command( 'feedback_url', array($bb, 'feedback_url'));
  1447. \WP_CLI::add_command( 'produce_invoice', array($bb, 'produce_invoice'));
  1448. }
  1449. //$bb->class_loader();
  1450. //$bb->create_invoice_by_client("8cb3d205-6cdc-4187-ae39-9216923dd86d", "2019-07-01", "2019-07-31");
  1451. //$idx = $bb->convert_date_to_idx("2019-07-02 14:30:00", "2019-07-01", "2019-07-02");
  1452. //wp_send_json($idx);
  1453. //$bb->create_timesheet_from_db("2019-07-01", "2019-07-14");