diff --git a/Xero.php b/Xero.php index 796be74..86da2e8 100644 --- a/Xero.php +++ b/Xero.php @@ -49,4 +49,16 @@ class Xero { $user = $this->xero->loadByGUID("Accounting\\Contact",$id); return $user; } + + public function getEmployees(){ + $employees = $this->xero->load("PayrollAU\\Employee") + ->where('EmployeeGroupName="Web-Employee"') + ->execute(); + return $employees; + } + + public function getEmployee($id){ + $employee = $this->xero->loadByGUID("PayrollAU\\Employee",$id); + return $employee; + } } \ No newline at end of file diff --git a/ts.php b/ts.php index 2ca7ea6..8c7c768 100644 --- a/ts.php +++ b/ts.php @@ -20,6 +20,7 @@ class AcareOffice{ private $acaresydney_userid = 0; private $clientgroup="48646f3d-cf5e-4fea-8c8b-5812bd540e1b"; private $xero ; + private $cli = false; public function __construct() { add_action('init', array($this, 'class_loader')); @@ -91,9 +92,17 @@ class AcareOffice{ wp_enqueue_script( 'bts_ts', plugins_url('js/bts_timesheet.js', __FILE__), array( 'jquery' , 'bts' )); } + public function sync_user_cli($args = array(), $assoc_args = array()){ + $this->cli = true; + echo "running sync user from command line;"; + $this->sync_users(); + return; + } + //sync users to wordpress system public function sync_users(){ - $this->sync_clients(); + set_time_limit(600); // executing time longer than expected 10 minutes + //$this->sync_clients(); $this->sync_employees(); } private function sync_clients(){ @@ -104,7 +113,13 @@ class AcareOffice{ } private function sync_employees(){ - + $employees = $this->xero->getEmployees(); + foreach ( $employees as $e){ + if ($this->cli){ + echo "sync " . $e->getFirstName() ."\n"; + } + $this->ensure_staff_exists($e); + } } private function ensure_contact_exists($contact){ @@ -134,6 +149,42 @@ class AcareOffice{ ]; return $args; } + + + private function ensure_staff_exists($employee) + { + $login = $employee->getEmployeeID(); + $user = get_user_by('login', $login); + if ($user === false){ + $xero_employee = $this->xero->getEmployee($login); + $args = $this->xero_employee_profile($xero_employee); + wp_insert_user($args); + }else{ + return; + $args['ID'] = $user->ID; + unset($args['user_pass']); + wp_update_user($args); + } + } + + private function xero_employee_profile($e){ + $args = [ + 'user_login' => $username = $e->getEmployeeID(), + 'user_pass' => md5(uniqid(rand() + time(), true)), + 'display_name' =>$e->getFirstName() . " " . $e->getLastName(), + 'user_email' => $e->getEmail(), + 'first_name' => $e->getFirstName(), + 'last_name' => $e->getLastName(), + 'nickname' => $e->getFirstName(), + 'role' => 'staff', + ]; + return $args; + } + } -new AcareOffice(); \ No newline at end of file +$bb = new AcareOffice(); + +if ( defined( 'WP_CLI' ) && WP_CLI ) { + \WP_CLI::add_command( 'sync_users', array($bb, 'sync_user_cli')); +}