timesheet source code
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

487 行
17KB

  1. <?php
  2. namespace Biukop;
  3. use \XeroPHP\Application\PrivateApplication;
  4. use \XeroPHP\Remote\Exception\RateLimitExceededException;
  5. use \XeroPHP\Remote\Exception\NotFoundException;
  6. class Xero {
  7. private $xero;
  8. private $clientgroup="48646f3d-cf5e-4fea-8c8b-5812bd540e1b";
  9. private $minimum_sync_interval_in_seconds = 600;
  10. private function default_config(){
  11. $config = array(
  12. 'oauth' => [
  13. 'callback' => 'http://acaresydney.com.au/',
  14. 'consumer_key' => 'G6AJIRWTH0X3C5SVS3ETZXNFCMDNGG',
  15. 'consumer_secret' => 'LP0PTSBCJLBB4CGYYKOHDXYF2NWXWD',
  16. 'rsa_private_key' => 'file://' . dirname(__FILE__) . '/keys/privatekey.pem',
  17. ],
  18. );
  19. return $config;
  20. }
  21. private function office_config(){
  22. $office_config = [
  23. 'xero' => [
  24. // 'payroll_version' =>'1.9',
  25. ],
  26. 'curl' => [
  27. CURLOPT_USERAGENT =>'AcareSydneyWebOffice',
  28. ],
  29. 'oauth' => [
  30. 'callback' => 'http://acaresydney.com.au/',
  31. 'consumer_key' => 'JE4LWKCJ6NHED30RFZWCT7WQYTS8JD',
  32. 'consumer_secret' => 'JXVZAZWKGM7MLUZSVIMK7ZSJE9GNYQ',
  33. 'rsa_private_key' => 'file://' . dirname(__FILE__) . '/keys/privatekey.pem',
  34. ],
  35. ];
  36. return $office_config;
  37. }
  38. public function __construct(){
  39. $this->xero = new PrivateApplication($this->office_config());
  40. }
  41. public function get_xero_handle()
  42. {
  43. return $this->xero;
  44. }
  45. public function getClients($contact_group_id){
  46. $xero = $this->xero;
  47. $cg = $xero->loadByGUID("Accounting\\ContactGroup", $contact_group_id);
  48. $contacts = $cg->getContacts();
  49. return $contacts;
  50. }
  51. public function getContact($id){
  52. $user = $this->xero->loadByGUID("Accounting\\Contact",$id);
  53. return $user;
  54. }
  55. public function getEmployees(){
  56. $employees = $this->xero->load("PayrollAU\\Employee")
  57. ->where('EmployeeGroupName="Web-Employee"')
  58. ->execute();
  59. return $employees;
  60. }
  61. public function getEmployee($id){
  62. $employee = $this->xero->loadByGUID("PayrollAU\\Employee",$id);
  63. return $employee;
  64. }
  65. //
  66. //sync users to wordpress system
  67. //does not work for too many users or employees
  68. public function sync_users($mininterval, $employeeonly, $clientsonly){
  69. $this->usage();
  70. $this->minimum_sync_interval_in_seconds = $mininterval;
  71. $msg="Sync users with minimum interval set to $mininterval \n";
  72. $this->logConsole($msg);
  73. try{
  74. if ($clientsonly){
  75. $this->sync_clients();
  76. }else if ($employeeonly){
  77. $this->sync_employees();
  78. }else{
  79. $this->sync_clients();
  80. $this->sync_employees();
  81. }
  82. }catch(RateLimitExceededException $e){
  83. $msg= "Xero API rate limit exceeded, please try again later, existing sync within 600 seconds will by passed automatically\n";
  84. $this->logConsole($msg);
  85. }catch(NotFoundException $e){
  86. $msg= "Xero API resource not found rate limit exceeded, please try again later, existing sync within 600 seconds will by passed automatically\n";
  87. $this->logConsole($msg);
  88. }
  89. }
  90. private function sync_clients($add_new_only = false){
  91. $contacts = $this->getClients($this->clientgroup);
  92. //add new first;
  93. $to_update = [];
  94. foreach ($contacts as $c){
  95. $login = $c->getContactID();
  96. $user = get_user_by('login', $login);
  97. if ($user === false){
  98. $this->add_new_contact($c);
  99. }else{
  100. $to_update[] = $c; // to update users later;
  101. }
  102. }
  103. if ($add_new_only)
  104. return;
  105. //sync existing
  106. foreach ($to_update as $c){
  107. $msg = sprintf("SYNC Client name=[%s] {%s} \n", $c->getName(), $c->getContactID());
  108. $this->logConsole($msg);
  109. $this->update_existing_contact($c);
  110. }
  111. }
  112. private function sync_employees($add_new_only = false){
  113. $employees = $this->getEmployees();
  114. //add new staff
  115. foreach ( $employees as $e){
  116. $login = $e->getContactID();
  117. $user = get_user_by('login', $login);
  118. if ($user === false){
  119. $this->add_new_staff($e);
  120. }else{
  121. $to_update[] = $e; // to update exiting users later;
  122. }
  123. }
  124. if ($add_new_only)
  125. return;
  126. foreach ( $to_update as $e){
  127. $msg = sprintf("SYNC employee name=[%s %s] {%s} \n", $e->getFirstName(), $e->getLastName(), $e->getEmployeeID());
  128. $this->logConsole($msg);
  129. $this->update_existing_staff($e);
  130. }
  131. }
  132. private function add_new_contact($contact){
  133. $login = $contact->getContactID();
  134. $user = get_user_by('login', $login);
  135. if ($user === false){
  136. $msg = sprintf("ADD Client name=[%s] {%s} \n", $contact->getName(), $contact->getContactID());
  137. $this->logConsole($msg);
  138. $xero_contact = $this->getContact($login);
  139. $args = $this->xero_contact_profile($xero_contact);
  140. $id = wp_insert_user($args);
  141. if (! id instanceof \WP_Error){
  142. $user = get_user_by('ID', $id);
  143. update_user_meta($user->ID, 'address', $args['address']);
  144. update_user_meta($user->ID, 'account', $args['account']);
  145. }else{
  146. $msg = "==(Add Client failed)==";
  147. $this->logConsole($msg);
  148. }
  149. }
  150. }
  151. private function update_existing_contact($contact){
  152. $login = $contact->getContactID();
  153. $user = get_user_by('login', $login);
  154. if ($user !== false)
  155. {//update user - must be existing user;
  156. if ($this->is_too_close_to_sync($user)){
  157. return;
  158. }
  159. $xero_contact = $this->getContact($login);
  160. $args = $this->xero_contact_profile($xero_contact);
  161. $args['ID'] = $user->ID;
  162. unset($args['user_pass']); //we don't change password
  163. wp_update_user($args);
  164. update_user_meta($user->ID, 'address', $args['address']);
  165. update_user_meta($user->ID, 'account', $args['account']);
  166. }
  167. $this->mark_updated($user->ID);
  168. }
  169. private function xero_contact_profile($c){
  170. $args = [
  171. 'user_login' => $username = $c->getContactID(),
  172. 'user_pass' => md5(uniqid(rand() + time(), true)),
  173. 'display_name' =>$c->getName(),
  174. 'user_email' => $c->getEmailAddress(),
  175. 'first_name' => $c->getFirstName(),
  176. 'last_name' => $c->getLastName(),
  177. 'nickname' => $c->getName(),
  178. 'account' => $c->getAccountNumber(),
  179. 'address'=> $this->get_post_address($c),
  180. 'role' => 'client',
  181. ];
  182. return $args;
  183. }
  184. private function get_post_address($client){
  185. $result = "";
  186. $addr = $this->get_client_address_by_type($client, 'POBOX');
  187. if ( $addr != false){
  188. if ($addr->getAddressLine1() != ""){
  189. $result .= $addr->getAddressLine1() . ";";
  190. }
  191. if ($addr->getAddressLine2() != ""){
  192. $result .= $addr->getAddressLine2() . ";";
  193. }
  194. if ($addr->getAddressLine3() != ""){
  195. $result .= $addr->getAddressLine3() . ";";
  196. }
  197. if ($addr->getAddressLine4() != ""){
  198. $result .= $addr->getAddressLine4() . ";";
  199. }
  200. if ($addr->getCity() != ""){
  201. $result .= $addr->getCity() . ";";
  202. }
  203. if ($addr->getPostalCode() != ""){
  204. $result .= $addr->getPostalCode() . ";";
  205. }
  206. }
  207. echo "result for client is " . $result . "\n";
  208. return $result;
  209. }
  210. private function get_client_address_by_type($client, $t){
  211. $addr = false;
  212. foreach( $client->getAddresses() as $a){
  213. if( $a->getAddressType() == $t){
  214. $addr = $a;
  215. break;
  216. }
  217. }
  218. return $addr;
  219. }
  220. private function add_new_staff($employee)
  221. {
  222. $login = $employee->getEmployeeID();
  223. $user = get_user_by('login', $login);
  224. if ($user === false){
  225. $msg = sprintf("ADD employee name=[%s %s] {%s} \n",
  226. $employee->getFirstName(),
  227. $employee->getLastName(),
  228. $employee->getEmployeeID());
  229. $this->logConsole($msg);
  230. $xero_employee = $this->getEmployee($login);
  231. $args = $this->xero_employee_profile($xero_employee);
  232. $id = wp_insert_user($args);
  233. if (! id instanceof \WP_Error){
  234. $user = get_user_by('ID', $id);
  235. update_user_meta($user->ID, 'mobile', $args['mobile']);
  236. update_user_meta($user->ID, 'address', $args['address']);
  237. }else{
  238. $msg = "==(Add staff failed)==";
  239. $this->logConsole($msg);
  240. }
  241. }
  242. }
  243. private function update_existing_staff($employee)
  244. {
  245. $login = $employee->getEmployeeID();
  246. $user = get_user_by('login', $login);
  247. if ($this->is_too_close_to_sync($user)){
  248. return;
  249. }
  250. if ($user != false) {
  251. $xero_employee = $this->getEmployee($login);
  252. $args = $this->xero_employee_profile($xero_employee);
  253. $args['ID'] = $user->ID;
  254. unset($args['user_pass']);
  255. wp_update_user($args);
  256. update_user_meta($user->ID, 'mobile', $args['mobile']);
  257. update_user_meta($user->ID, 'address', $args['address']);
  258. }
  259. $this->mark_updated($user->ID);
  260. }
  261. private function xero_employee_profile($e){
  262. $args = [
  263. 'user_login' => $username = $e->getEmployeeID(),
  264. 'user_pass' => md5(uniqid(rand() + time(), true)),
  265. 'display_name' =>$e->getFirstName() . " " . $e->getLastName(),
  266. 'user_email' => $e->getEmail(),
  267. 'first_name' => $e->getFirstName(),
  268. 'last_name' => $e->getLastName(),
  269. 'nickname' => $e->getFirstName(),
  270. 'mobile' => $e->getMobile(),
  271. 'address'=> $this->get_employee_address($e),
  272. 'role' => 'staff',
  273. ];
  274. return $args;
  275. }
  276. private function get_employee_address($e){
  277. // "HomeAddress": {
  278. // "AddressLine1": "16 Quist Avenue",
  279. // "City": "Lurnea",
  280. // "Region": "NSW",
  281. // "PostalCode": "2170",
  282. // "Country": "AUSTRALIA"
  283. // },
  284. $addr = "";
  285. $home = $e->getHomeAddress();
  286. $addr .= $home->getAddressLine1() .",";
  287. $addr .= $home->getAddressLine2() .",";
  288. $addr .= $home->getCity() . ",";
  289. $addr .= $home->getRegion() . " ";
  290. $addr .= $home->getCountry() ." ";
  291. $addr .= $home->getPostalCode();
  292. return $addr;
  293. }
  294. private function mark_updated($userid){
  295. update_user_meta($userid, 'lastsync', time());
  296. }
  297. private function get_last_sync($userid){
  298. $lastsync = get_user_meta($userid, 'lastsync', true);
  299. return (int)($lastsync);
  300. }
  301. private function is_too_close_to_sync($user){
  302. $userid = $user->ID;
  303. $lastsync = $this->get_last_sync($user->ID);
  304. $now = time();
  305. $diff = $now - (int) $lastsync;
  306. if ($diff < $this->minimum_sync_interval_in_seconds){
  307. $msg = sprintf("\tSKIP userid(%d),login=%s,display_name=%s,(lastsync=%d secs ago, mininterval=%d) \n",
  308. $user->ID, $user->user_login, $user->display_name, $diff, $this->minimum_sync_interval_in_seconds);
  309. $this->logConsole($msg);
  310. return true;
  311. }
  312. return false;
  313. }
  314. private function logConsole($str){
  315. //if is commandline
  316. if ( defined( 'WP_CLI' ) && WP_CLI ) {
  317. echo $str;
  318. }
  319. }
  320. private function usage(){
  321. $msg = "_____________________________________________\n";
  322. $msg .= "run this command at public_html/, where wp-config.php exist \n";
  323. $msg .= "wp sync_users --mininterval=6000 \n";
  324. $msg .= "6000 means those users synced within 6000 seconds will be bypassed \n";
  325. $msg .= "to sync everything \n";
  326. $msg .= "wp sync_users --mininterval=0 [--clientsonly] [--employeeonly]\n";
  327. $msg .= "but it may hit XERO rate limit, 60call/sec, 5000/day \n";
  328. $msg .= "---------------------------------------------\n";
  329. $this->logConsole($msg);
  330. }
  331. /* sync payitems to wp options */
  332. public function init_wp(){
  333. try{
  334. $this->sync_payitem();
  335. $this->add_new_client();
  336. $this->add_new_employee();
  337. $this->sync_payroll_calendar();
  338. }catch(\XeroPHP\Remote\Exception $e){
  339. }
  340. }
  341. private function add_new_client(){
  342. if ($this->too_close_to_add_employee()){
  343. return;
  344. }
  345. update_option('bts_add_client_last_sync', time());
  346. $this->sync_clients(true);//add new only;
  347. }
  348. private function add_new_employee(){
  349. if ($this->too_close_to_add_client()){
  350. return;
  351. }
  352. update_option('bts_add_employee_last_sync', time());
  353. $this->sync_employee(true);//add new only;
  354. }
  355. private function sync_payroll_calendar()
  356. {
  357. if ($this->too_close_to_sync_payroll_calendar()){
  358. return;
  359. }
  360. update_option('bts_pay_roll_calendar_last_sync', time());
  361. $pc = $this->get_payroll_calendar();
  362. $start = $pc->getStartDate()->format('Y-m-d');
  363. $finish = new \DateTime($start);
  364. $finish = $finish->modify("+13 days")->format('Y-m-d');
  365. $paydate = $pc->getPaymentDate()->format('Y-m-d');
  366. $calendar["start"] = $start;
  367. $calendar["finish"] = $finish;
  368. $calendar["paydate"] = $paydate;
  369. update_option('bts_pay_roll_calendar', $calendar);
  370. }
  371. private function sync_payitem(){
  372. if ($this->too_close_to_sync_payitem()){
  373. return;
  374. }
  375. $payitems = $this->xero->load('PayrollAU\\PayItem')->execute();
  376. $payitem_options = array();
  377. foreach ($payitems[0]->getEarningsRates() as $e){
  378. // "EarningsRateID": "34e17d08-237a-4ae2-8115-375d1ff8a9ed",
  379. // "Name": "Overtime Hours (exempt from super)",
  380. // "EarningsType": "OVERTIMEEARNINGS",
  381. // "RateType": "MULTIPLE",
  382. // "AccountCode": "477",
  383. // "Multiplier": 1.5,
  384. // "IsExemptFromTax": true,
  385. // "IsExemptFromSuper": true,
  386. // "AccrueLeave": false,
  387. // "IsReportableAsW1": true,
  388. // "UpdatedDateUTC": "2019-03-16T13:18:19+00:00",
  389. // "CurrentRecord": false
  390. if ($e->getCurrentRecord() == "true"){
  391. $payitem_options[]= array(
  392. 'EarningsRateID' => $e->getEarningsRateID(),
  393. 'Name'=> $e->getName(),
  394. 'EarningsType'=> $e->getEarningstype(),
  395. 'RatePerUnit' => $e->getRatePerUnit(),
  396. 'RateType' => $e->getRateType(),
  397. 'AccountCode' => $e->getAccountCode(),
  398. "Multiplier"=> $e->getMultiplier(),
  399. "IsExemptFromTax" => $e->getIsExemptFromTax(),
  400. "IsExemptFromSuper"=> $e->getIsExemptFromSuper(),
  401. "AccrueLeave" => $e->getAccrueLeave(),
  402. "TypeOfUnits" => $e->getTypeOfUnits(),
  403. "CurrentRecord"=> $e->getCurrentRecord(),
  404. );
  405. }
  406. }
  407. update_option('bts_payitem_earnings_rate', $payitem_options);
  408. update_option('bts_payitem_last_sync', time());
  409. }
  410. private function too_close_to_sync_payitem(){
  411. $lastsync = get_option('bts_payitem_last_sync', 0);
  412. $now = time();
  413. $diff = $now - (int) $lastsync;
  414. return $diff < $this->minimum_sync_interval_in_seconds; //default 10 minutes
  415. }
  416. private function too_close_to_add_employee(){
  417. $lastsync = get_option('bts_add_employee_last_sync', 0);
  418. $now = time();
  419. $diff = $now - (int) $lastsync;
  420. return $diff < 1.1 * $this->minimum_sync_interval_in_seconds; //default 1.1 * 10 minutes
  421. }
  422. private function too_close_to_add_client(){
  423. $lastsync = get_option('bts_add_client_last_sync', 0);
  424. $now = time();
  425. $diff = $now - (int) $lastsync;
  426. return $diff < 1.2 * $this->minimum_sync_interval_in_seconds; //default 1.2 * 10 minutes
  427. }
  428. private function too_close_to_sync_payroll_calendar(){
  429. $lastsync = get_option('bts_pay_roll_calendar_last_sync', 0);
  430. $now = time();
  431. $diff = $now - (int) $lastsync;
  432. return $diff < 1.3 * $this->minimum_sync_interval_in_seconds; //default 1.3 * 10 minutes
  433. }
  434. public function get_payroll_calendar()
  435. {
  436. $id = "33dc7df5-3060-4d76-b4da-57c20685d77d"; //fortnightly
  437. $pc = $this->xero->loadByGUID('PayrollAU\\PayrollCalendar', $id);
  438. return $pc;
  439. }
  440. }