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

1182 líneas
43KB

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