timesheet source code
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

371 lines
13KB

  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(){
  91. $contacts = $this->getClients($this->clientgroup);
  92. foreach ($contacts as $c){
  93. $msg = sprintf("SYNC Client name=[%s] {%s} \n", $c->getName(), $c->getContactID());
  94. $this->logConsole($msg);
  95. $this->ensure_contact_exists($c);
  96. }
  97. }
  98. private function sync_employees(){
  99. $employees = $this->getEmployees();
  100. foreach ( $employees as $e){
  101. $msg = sprintf("SYNC employee name=[%s %s] {%s} \n", $e->getFirstName(), $e->getLastName(), $e->getEmployeeID());
  102. $this->logConsole($msg);
  103. // if ($e->getEmployeeID() != '3e8c2e62-8e28-4b68-ae98-9ef1d76188c4')
  104. // continue;
  105. $this->ensure_staff_exists($e);
  106. }
  107. }
  108. private function ensure_contact_exists($contact){
  109. $login = $contact->getContactID();
  110. $user = get_user_by('login', $login);
  111. if ($user === false){
  112. $xero_contact = $this->getContact($login);
  113. $args = $this->xero_contact_profile($xero_contact);
  114. $id = wp_insert_user($args);
  115. $user = get_user_by('ID', $id);
  116. update_user_meta($user->ID, 'address', $args['address']);
  117. update_user_meta($user->ID, 'account', $args['account']);
  118. }else{//update user
  119. if ($this->is_too_close_to_sync($user)){
  120. return;
  121. }
  122. $xero_contact = $this->getContact($login);
  123. $args = $this->xero_contact_profile($xero_contact);
  124. $args['ID'] = $user->ID;
  125. unset($args['user_pass']); //we don't change password
  126. wp_update_user($args);
  127. update_user_meta($user->ID, 'address', $args['address']);
  128. update_user_meta($user->ID, 'account', $args['account']);
  129. }
  130. $this->mark_updated($user->ID);
  131. }
  132. private function xero_contact_profile($c){
  133. $args = [
  134. 'user_login' => $username = $c->getContactID(),
  135. 'user_pass' => md5(uniqid(rand() + time(), true)),
  136. 'display_name' =>$c->getName(),
  137. 'user_email' => $c->getEmailAddress(),
  138. 'first_name' => $c->getFirstName(),
  139. 'last_name' => $c->getLastName(),
  140. 'nickname' => $c->getName(),
  141. 'account' => $c->getAccountNumber(),
  142. 'address'=> $this->get_post_address($c),
  143. 'role' => 'client',
  144. ];
  145. return $args;
  146. }
  147. private function get_post_address($client){
  148. $result = "";
  149. $addr = $this->get_client_address_by_type($client, 'POBOX');
  150. if ( $addr != false){
  151. if ($addr->getAddressLine1() != ""){
  152. $result .= $addr->getAddressLine1() . ";";
  153. }
  154. if ($addr->getAddressLine2() != ""){
  155. $result .= $addr->getAddressLine2() . ";";
  156. }
  157. if ($addr->getAddressLine3() != ""){
  158. $result .= $addr->getAddressLine3() . ";";
  159. }
  160. if ($addr->getAddressLine4() != ""){
  161. $result .= $addr->getAddressLine4() . ";";
  162. }
  163. if ($addr->getCity() != ""){
  164. $result .= $addr->getCity() . ";";
  165. }
  166. if ($addr->getPostalCode() != ""){
  167. $result .= $addr->getPostalCode() . ";";
  168. }
  169. }
  170. echo "result for client is " . $result . "\n";
  171. return $result;
  172. }
  173. private function get_client_address_by_type($client, $t){
  174. $addr = false;
  175. foreach( $client->getAddresses() as $a){
  176. if( $a->getAddressType() == $t){
  177. $addr = $a;
  178. break;
  179. }
  180. }
  181. return $addr;
  182. }
  183. private function ensure_staff_exists($employee)
  184. {
  185. $login = $employee->getEmployeeID();
  186. $user = get_user_by('login', $login);
  187. if ($user === false){
  188. echo "add new \n";
  189. $xero_employee = $this->getEmployee($login);
  190. $args = $this->xero_employee_profile($xero_employee);
  191. $id = wp_insert_user($args);
  192. $user = get_user_by('ID', $id);
  193. update_user_meta($user->ID, 'mobile', $args['mobile']);
  194. update_user_meta($user->ID, 'address', $args['address']);
  195. }else{
  196. if ($this->is_too_close_to_sync($user)){
  197. return;
  198. }
  199. $xero_employee = $this->getEmployee($login);
  200. $args = $this->xero_employee_profile($xero_employee);
  201. $args['ID'] = $user->ID;
  202. unset($args['user_pass']);
  203. wp_update_user($args);
  204. update_user_meta($user->ID, 'mobile', $args['mobile']);
  205. update_user_meta($user->ID, 'address', $args['address']);
  206. }
  207. $this->mark_updated($user->ID);
  208. }
  209. private function xero_employee_profile($e){
  210. $args = [
  211. 'user_login' => $username = $e->getEmployeeID(),
  212. 'user_pass' => md5(uniqid(rand() + time(), true)),
  213. 'display_name' =>$e->getFirstName() . " " . $e->getLastName(),
  214. 'user_email' => $e->getEmail(),
  215. 'first_name' => $e->getFirstName(),
  216. 'last_name' => $e->getLastName(),
  217. 'nickname' => $e->getFirstName(),
  218. 'mobile' => $e->getMobile(),
  219. 'address'=> $this->get_employee_address($e),
  220. 'role' => 'staff',
  221. ];
  222. return $args;
  223. }
  224. private function get_employee_address($e){
  225. // "HomeAddress": {
  226. // "AddressLine1": "16 Quist Avenue",
  227. // "City": "Lurnea",
  228. // "Region": "NSW",
  229. // "PostalCode": "2170",
  230. // "Country": "AUSTRALIA"
  231. // },
  232. $addr = "";
  233. $home = $e->getHomeAddress();
  234. $addr .= $home->getAddressLine1() .",";
  235. $addr .= $home->getAddressLine2() .",";
  236. $addr .= $home->getCity() . ",";
  237. $addr .= $home->getRegion() . " ";
  238. $addr .= $home->getCountry() ." ";
  239. $addr .= $home->getPostalCode();
  240. return $addr;
  241. }
  242. private function mark_updated($userid){
  243. update_user_meta($userid, 'lastsync', time());
  244. }
  245. private function get_last_sync($userid){
  246. $lastsync = get_user_meta($userid, 'lastsync', true);
  247. return (int)($lastsync);
  248. }
  249. private function is_too_close_to_sync($user){
  250. $userid = $user->ID;
  251. $lastsync = $this->get_last_sync($user->ID);
  252. $now = time();
  253. $diff = $now - (int) $lastsync;
  254. if ($diff < $this->minimum_sync_interval_in_seconds){
  255. $msg = sprintf("\tSKIP userid(%d),login=%s,display_name=%s,(lastsync=%d secs ago, mininterval=%d) \n",
  256. $user->ID, $user->user_login, $user->display_name, $diff, $this->minimum_sync_interval_in_seconds);
  257. $this->logConsole($msg);
  258. return true;
  259. }
  260. return false;
  261. }
  262. private function logConsole($str){
  263. //if is commandline
  264. if ( defined( 'WP_CLI' ) && WP_CLI ) {
  265. echo $str;
  266. }
  267. }
  268. private function usage(){
  269. $msg = "_____________________________________________\n";
  270. $msg .= "run this command at public_html/, where wp-config.php exist \n";
  271. $msg .= "wp sync_users --mininterval=6000 \n";
  272. $msg .= "6000 means those users synced within 6000 seconds will be bypassed \n";
  273. $msg .= "to sync everything \n";
  274. $msg .= "wp sync_users --mininterval=0 [--clientsonly] [--employeeonly]\n";
  275. $msg .= "but it may hit XERO rate limit, 60call/sec, 5000/day \n";
  276. $msg .= "---------------------------------------------\n";
  277. $this->logConsole($msg);
  278. }
  279. /* sync payitems to wp options */
  280. public function init_wp(){
  281. try{
  282. $this->sync_payitem();
  283. }catch(\XeroPHP\Remote\Exception $e){
  284. }
  285. }
  286. private function sync_payitem(){
  287. if ($this->too_close_to_sync_payitem()){
  288. return;
  289. }
  290. $payitems = $this->xero->load('PayrollAU\\PayItem')->execute();
  291. $payitem_options = array();
  292. foreach ($payitems[0]->getEarningsRates() as $e){
  293. // "EarningsRateID": "34e17d08-237a-4ae2-8115-375d1ff8a9ed",
  294. // "Name": "Overtime Hours (exempt from super)",
  295. // "EarningsType": "OVERTIMEEARNINGS",
  296. // "RateType": "MULTIPLE",
  297. // "AccountCode": "477",
  298. // "Multiplier": 1.5,
  299. // "IsExemptFromTax": true,
  300. // "IsExemptFromSuper": true,
  301. // "AccrueLeave": false,
  302. // "IsReportableAsW1": true,
  303. // "UpdatedDateUTC": "2019-03-16T13:18:19+00:00",
  304. // "CurrentRecord": false
  305. if ($e->getCurrentRecord() == "true"){
  306. $payitem_options[]= array(
  307. 'EarningsRateID' => $e->getEarningsRateID(),
  308. 'Name'=> $e->getName(),
  309. 'EarningsType'=> $e->getEarningstype(),
  310. 'RatePerUnit' => $e->getRatePerUnit(),
  311. 'RateType' => $e->getRateType(),
  312. 'AccountCode' => $e->getAccountCode(),
  313. "Multiplier"=> $e->getMultiplier(),
  314. "IsExemptFromTax" => $e->getIsExemptFromTax(),
  315. "IsExemptFromSuper"=> $e->getIsExemptFromSuper(),
  316. "AccrueLeave" => $e->getAccrueLeave(),
  317. "TypeOfUnits" => $e->getTypeOfUnits(),
  318. "CurrentRecord"=> $e->getCurrentRecord(),
  319. );
  320. }
  321. }
  322. update_option('bts_payitem_earnings_rate', $payitem_options);
  323. update_option('bts_payitem_last_sync', time());
  324. }
  325. private function too_close_to_sync_payitem(){
  326. $lastsync = get_option('bts_payitem_last_sync', 0);
  327. $now = time();
  328. $diff = $now - (int) $lastsync;
  329. return $diff < $this->minimum_sync_interval_in_seconds; //default 10 minutes
  330. }
  331. public function get_payroll_calendar()
  332. {
  333. $id = "33dc7df5-3060-4d76-b4da-57c20685d77d"; //fortnightly
  334. $pc = $this->xero->loadByGUID('PayrollAU\\PayrollCalendar', $id);
  335. return $pc;
  336. }
  337. }