timesheet source code
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

1565 rindas
57KB

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