timesheet source code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1719 lines
63KB

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