timesheet source code
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

342 lines
12KB

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