timesheet source code
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1679 linhas
61KB

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