timesheet source code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

348 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 getClients($contact_group_id){
  42. $xero = $this->xero;
  43. $cg = $xero->loadByGUID("Accounting\\ContactGroup", $contact_group_id);
  44. $contacts = $cg->getContacts();
  45. return $contacts;
  46. }
  47. public function getContact($id){
  48. $user = $this->xero->loadByGUID("Accounting\\Contact",$id);
  49. return $user;
  50. }
  51. public function getEmployees(){
  52. $employees = $this->xero->load("PayrollAU\\Employee")
  53. ->where('EmployeeGroupName="Web-Employee"')
  54. ->execute();
  55. return $employees;
  56. }
  57. public function getEmployee($id){
  58. $employee = $this->xero->loadByGUID("PayrollAU\\Employee",$id);
  59. return $employee;
  60. }
  61. //
  62. //sync users to wordpress system
  63. //does not work for too many users or employees
  64. public function sync_users($mininterval, $employeeonly, $clientsonly){
  65. $this->usage();
  66. $this->minimum_sync_interval_in_seconds = $mininterval;
  67. $msg="Sync users with minimum interval set to $mininterval \n";
  68. $this->logConsole($msg);
  69. try{
  70. if ($clientsonly){
  71. $this->sync_clients();
  72. }else if ($employeeonly){
  73. $this->sync_employees();
  74. }else{
  75. $this->sync_clients();
  76. $this->sync_employees();
  77. }
  78. }catch(RateLimitExceededException $e){
  79. $msg= "Xero API rate limit exceeded, please try again later, existing sync within 600 seconds will by passed automatically\n";
  80. $this->logConsole($msg);
  81. }catch(NotFoundException $e){
  82. $msg= "Xero API resource not found rate limit exceeded, please try again later, existing sync within 600 seconds will by passed automatically\n";
  83. $this->logConsole($msg);
  84. }
  85. }
  86. private function sync_clients(){
  87. $contacts = $this->getClients($this->clientgroup);
  88. foreach ($contacts as $c){
  89. $msg = sprintf("SYNC Client name=[%s] {%s} \n", $c->getName(), $c->getContactID());
  90. $this->logConsole($msg);
  91. $this->ensure_contact_exists($c);
  92. }
  93. }
  94. private function sync_employees(){
  95. $employees = $this->getEmployees();
  96. foreach ( $employees as $e){
  97. $msg = sprintf("SYNC employee name=[%s %s] {%s} \n", $e->getFirstName(), $e->getLastName(), $e->getEmployeeID());
  98. $this->logConsole($msg);
  99. $this->ensure_staff_exists($e);
  100. }
  101. }
  102. private function ensure_contact_exists($contact){
  103. $login = $contact->getContactID();
  104. $user = get_user_by('login', $login);
  105. if ($user === false){
  106. $xero_contact = $this->getContact($login);
  107. $args = $this->xero_contact_profile($xero_contact);
  108. $id = wp_insert_user($args);
  109. $user = get_user_by('ID', $id);
  110. update_user_meta($user->ID, 'address', $args['address']);
  111. update_user_meta($user->ID, 'account', $args['account']);
  112. }else{//update user
  113. if ($this->is_too_close_to_sync($user)){
  114. return;
  115. }
  116. $xero_contact = $this->getContact($login);
  117. $args = $this->xero_contact_profile($xero_contact);
  118. $args['ID'] = $user->ID;
  119. unset($args['user_pass']); //we don't change password
  120. wp_update_user($args);
  121. update_user_meta($user->ID, 'address', $args['address']);
  122. update_user_meta($user->ID, 'account', $args['account']);
  123. }
  124. $this->mark_updated($user->ID);
  125. }
  126. private function xero_contact_profile($c){
  127. $args = [
  128. 'user_login' => $username = $c->getContactID(),
  129. 'user_pass' => md5(uniqid(rand() + time(), true)),
  130. 'display_name' =>$c->getName(),
  131. 'user_email' => $c->getEmailAddress(),
  132. 'first_name' => $c->getFirstName(),
  133. 'last_name' => $c->getLastName(),
  134. 'nickname' => $c->getName(),
  135. 'account' => $c->getAccountNumber(),
  136. 'address'=> $this->get_post_address($c),
  137. 'role' => 'client',
  138. ];
  139. return $args;
  140. }
  141. private function get_post_address($client){
  142. $result = "";
  143. $addr = $this->get_client_address_by_type($client, 'POBOX');
  144. if ( $addr != false){
  145. if ($addr->getAddressLine1() != ""){
  146. $result .= $addr->getAddressLine1() . ";";
  147. }
  148. if ($addr->getAddressLine2() != ""){
  149. $result .= $addr->getAddressLine2() . ";";
  150. }
  151. if ($addr->getAddressLine3() != ""){
  152. $result .= $addr->getAddressLine3() . ";";
  153. }
  154. if ($addr->getAddressLine4() != ""){
  155. $result .= $addr->getAddressLine4() . ";";
  156. }
  157. if ($addr->getCity() != ""){
  158. $result .= $addr->getCity() . ";";
  159. }
  160. if ($addr->getPostalCode() != ""){
  161. $result .= $addr->getPostalCode() . ";";
  162. }
  163. }
  164. echo "result for client is " . $result . "\n";
  165. return $result;
  166. }
  167. private function get_client_address_by_type($client, $t){
  168. $addr = false;
  169. foreach( $client->getAddresses() as $a){
  170. if( $a->getAddressType() == $t){
  171. $addr = $a;
  172. break;
  173. }
  174. }
  175. return $addr;
  176. }
  177. private function ensure_staff_exists($employee)
  178. {
  179. $login = $employee->getEmployeeID();
  180. $user = get_user_by('login', $login);
  181. if ($user === false){
  182. $xero_employee = $this->getEmployee($login);
  183. $args = $this->xero_employee_profile($xero_employee);
  184. $id = wp_insert_user($args);
  185. $user = get_user_by('ID', $id);
  186. update_user_meta($user->ID, 'mobile', $args['mobile']);
  187. update_user_meta($user->ID, 'address', $args['address']);
  188. }else{
  189. if ($this->is_too_close_to_sync($user)){
  190. return;
  191. }
  192. $xero_employee = $this->getEmployee($login);
  193. $args = $this->xero_employee_profile($xero_employee);
  194. $args['ID'] = $user->ID;
  195. unset($args['user_pass']);
  196. wp_update_user($args);
  197. update_user_meta($user->ID, 'mobile', $args['mobile']);
  198. update_user_meta($user->ID, 'address', $args['address']);
  199. }
  200. $this->mark_updated($user->ID);
  201. }
  202. private function xero_employee_profile($e){
  203. $args = [
  204. 'user_login' => $username = $e->getEmployeeID(),
  205. 'user_pass' => md5(uniqid(rand() + time(), true)),
  206. 'display_name' =>$e->getFirstName() . " " . $e->getLastName(),
  207. 'user_email' => $e->getEmail(),
  208. 'first_name' => $e->getFirstName(),
  209. 'last_name' => $e->getLastName(),
  210. 'nickname' => $e->getFirstName(),
  211. 'mobile' => $e->getMobile(),
  212. 'address'=> $this->get_employee_address($e),
  213. 'role' => 'staff',
  214. ];
  215. return $args;
  216. }
  217. private function get_employee_address($e){
  218. // "HomeAddress": {
  219. // "AddressLine1": "16 Quist Avenue",
  220. // "City": "Lurnea",
  221. // "Region": "NSW",
  222. // "PostalCode": "2170",
  223. // "Country": "AUSTRALIA"
  224. // },
  225. $addr = "";
  226. $home = $e->getHomeAddress();
  227. $addr .= $home->getAddressLine1() .",";
  228. $addr .= $home->getAddressLine2() .",";
  229. $addr .= $home->getCity() . ",";
  230. $addr .= $home->getRegion() . " ";
  231. $addr .= $home->getCountry() ." ";
  232. $addr .= $home->getPostalCode();
  233. return $addr;
  234. }
  235. private function mark_updated($userid){
  236. update_user_meta($userid, 'lastsync', time());
  237. }
  238. private function get_last_sync($userid){
  239. $lastsync = get_user_meta($userid, 'lastsync', true);
  240. return (int)($lastsync);
  241. }
  242. private function is_too_close_to_sync($user){
  243. $userid = $user->ID;
  244. $lastsync = $this->get_last_sync($user->ID);
  245. $now = time();
  246. $diff = $now - (int) $lastsync;
  247. if ($diff < $this->minimum_sync_interval_in_seconds){
  248. $msg = sprintf("\tSKIP userid(%d),login=%s,display_name=%s,(lastsync=%d secs ago, mininterval=%d) \n",
  249. $user->ID, $user->user_login, $user->display_name, $diff, $this->minimum_sync_interval_in_seconds);
  250. $this->logConsole($msg);
  251. return true;
  252. }
  253. return false;
  254. }
  255. private function logConsole($str){
  256. //if is commandline
  257. if ( defined( 'WP_CLI' ) && WP_CLI ) {
  258. echo $str;
  259. }
  260. }
  261. private function usage(){
  262. $msg = "_____________________________________________\n";
  263. $msg .= "run this command at public_html/, where wp-config.php exist \n";
  264. $msg .= "wp sync_users --mininterval=6000 \n";
  265. $msg .= "6000 means those users synced within 6000 seconds will be bypassed \n";
  266. $msg .= "to sync everything \n";
  267. $msg .= "wp sync_users --mininterval=0 [--clientsonly] [--employeeonly]\n";
  268. $msg .= "but it may hit XERO rate limit, 60call/sec, 5000/day \n";
  269. $msg .= "---------------------------------------------\n";
  270. $this->logConsole($msg);
  271. }
  272. /* sync payitems to wp options */
  273. public function init_wp(){
  274. $this->sync_payitem();
  275. }
  276. private function sync_payitem(){
  277. if ($this->too_close_to_sync_payitem()){
  278. return;
  279. }
  280. $payitems = $this->xero->load('PayrollAU\\PayItem')->execute();
  281. $payitem_options = array();
  282. foreach ($payitems[0]->getEarningsRates() as $e){
  283. // "EarningsRateID": "34e17d08-237a-4ae2-8115-375d1ff8a9ed",
  284. // "Name": "Overtime Hours (exempt from super)",
  285. // "EarningsType": "OVERTIMEEARNINGS",
  286. // "RateType": "MULTIPLE",
  287. // "AccountCode": "477",
  288. // "Multiplier": 1.5,
  289. // "IsExemptFromTax": true,
  290. // "IsExemptFromSuper": true,
  291. // "AccrueLeave": false,
  292. // "IsReportableAsW1": true,
  293. // "UpdatedDateUTC": "2019-03-16T13:18:19+00:00",
  294. // "CurrentRecord": false
  295. $payitem_options[]= array(
  296. 'EarningsRateID' => $e->getEarningsRateID(),
  297. 'Name'=> $e->getName(),
  298. 'EarningsType'=> $e->getEarningstype(),
  299. 'RatePerUnit' => $e->getRatePerUnit(),
  300. 'RateType' => $e->getRateType(),
  301. 'AccountCode' => $e->getAccountCode(),
  302. "Multiplier"=> $e->getMultiplier(),
  303. "IsExemptFromTax" => $e->getIsExemptFromTax(),
  304. "IsExemptFromSuper"=> $e->getIsExemptFromSuper(),
  305. "AccrueLeave" => $e->getAccrueLeave(),
  306. );
  307. }
  308. update_option('bts_payitem_earnings_rate', $payitem_options);
  309. update_option('bts_payitem_last_sync', time());
  310. }
  311. private function too_close_to_sync_payitem(){
  312. $lastsync = get_option('bts_payitem_last_sync', 0);
  313. $now = time();
  314. $diff = $now - (int) $lastsync;
  315. return $diff < $this->minimum_sync_interval_in_seconds; //default 10 minutes
  316. }
  317. }