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.

1460 lines
53KB

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