timesheet source code
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1553 líneas
57KB

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