timesheet source code
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

1537 lines
56KB

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