From 0544674d532c1d65ac0f323db06d1b7ff39eddd1 Mon Sep 17 00:00:00 2001
From: Arthur Suzuki <arthur.suzuki@biblibre.com>
Date: Fri, 2 Jul 2021 17:24:01 +0200
Subject: [PATCH] dev#87908 : enables users to change personnal informations
 with Koha

---
 FEATURES/87908                                |  10 ++
 VERSIONS_WIP/87908                            |   1 +
 library/Class/WebService/SIGB/Emprunteur.php  |  23 ++++
 .../WebService/SIGB/Koha/RestfulService.php   |  51 ++++++++-
 .../Class/WebService/SIGB/KohaRestfulTest.php | 105 +++++++++++++++++-
 5 files changed, 184 insertions(+), 6 deletions(-)
 create mode 100644 FEATURES/87908
 create mode 100644 VERSIONS_WIP/87908

diff --git a/FEATURES/87908 b/FEATURES/87908
new file mode 100644
index 00000000000..eda3ebe0967
--- /dev/null
+++ b/FEATURES/87908
@@ -0,0 +1,10 @@
+        '87908' =>
+            ['Label' => $this->_('SIGB Koha - Permettre la modifications des informations personnelles depuis Bokeh'),
+             'Desc' => $this->_('Il sera désormais possible de modifier les informations personnelles de son compte lecteur aussi bien dans le portail que dans le SIGB directement depuis Bokeh sans passer par la bibliothèque'),
+             'Image' => '',
+             'Video' => 'https://www.youtube.com/watch?v=EMDn_ic0yDE',
+             'Category' => $this->_('Compte Lecteur'),
+             'Right' => function($feature_description, $user) {return true;},
+             'Wiki' => 'https://wiki.bokeh-library-portal.org/index.php?title=SIGB_Koha#Changer_ses_informations_personnelles_dans_Koha_et_Bokeh_via_le_web_service',
+             'Test' => '',
+             'Date' => '2021-07-02'],
\ No newline at end of file
diff --git a/VERSIONS_WIP/87908 b/VERSIONS_WIP/87908
new file mode 100644
index 00000000000..6d3e06b850b
--- /dev/null
+++ b/VERSIONS_WIP/87908
@@ -0,0 +1 @@
+ - ticket #87908 : SIGB Koha : Les modifications des informations du compte lecteur sont transmises au SIGB.
\ No newline at end of file
diff --git a/library/Class/WebService/SIGB/Emprunteur.php b/library/Class/WebService/SIGB/Emprunteur.php
index 2515cd9f844..acb9f1772b2 100644
--- a/library/Class/WebService/SIGB/Emprunteur.php
+++ b/library/Class/WebService/SIGB/Emprunteur.php
@@ -46,6 +46,7 @@ class Class_WebService_SIGB_Emprunteur {
     $_ville,
     $_code_postal,
     $_telephone,
+    $_mobile,
     $_date_naissance,
     $_is_contact_email= 0,
     $_is_contact_sms= 0,
@@ -241,6 +242,24 @@ class Class_WebService_SIGB_Emprunteur {
   }
 
 
+  /**
+   * @param string $mobile
+   * @return Class_WebService_SIGB_Emprunteur
+   */
+  public function setMobile($mobile) {
+    $this->_mobile = $mobile;
+    return $this;
+  }
+
+
+  /**
+   * @return string
+   */
+  public function getMobile(){
+    return $this->_mobile;
+  }
+
+
   /**
    * @param string $is_contact_email
    * @return Class_WebService_SIGB_Emprunteur
@@ -835,8 +854,12 @@ class Class_WebService_SIGB_Emprunteur {
       ->setNom($user->getNom())
       ->setPrenom($user->getPrenom())
       ->setEMail($user->getMail())
+      ->setAdresse($user->getAdresse())
+      ->setVille($user->getVille())
+      ->setCodePostal($user->getCodePostal())
       ->setPassword($user->getPassword())
       ->setTelephone($user->getTelephone())
+      ->setMobile($user->getMobile())
       ->setIsContactSms($user->getIsContactSms())
       ->setIsContactEmail($user->getIsContactMail())
       ->setLogin($user->getLogin());
diff --git a/library/Class/WebService/SIGB/Koha/RestfulService.php b/library/Class/WebService/SIGB/Koha/RestfulService.php
index 3eb1ff3bb3e..2a95092cf93 100644
--- a/library/Class/WebService/SIGB/Koha/RestfulService.php
+++ b/library/Class/WebService/SIGB/Koha/RestfulService.php
@@ -172,12 +172,19 @@ class Class_WebService_SIGB_Koha_RestfulService
 
 
   public function saveEmprunteur($emprunteur) {
+    $this->_changePassword($emprunteur);
+    $this->_updateSigbUser($emprunteur);
+    return $emprunteur;
+  }
+
+
+  protected function _changePassword($emprunteur) {
     $response = $this->restfulPut('auth/change_password',
-                      ['user_name' => $emprunteur->getLogin(),
-                       'new_password' => $emprunteur->getPassword()]);
+                                  ['user_name' => $emprunteur->getLogin(),
+                                   'new_password' => $emprunteur->getPassword()]);
 
     if (null === ($json = json_decode($response,true))) {
-      throw new Class_WebService_Exception($this->_("saveEmprunteur() s'attends à une réponse au format JSON"));
+      throw new Class_WebService_Exception($this->_("Le format de la réponse envoyé par Koha à la demande de changement de mot de passe n'est pas correct."));
     }
 
     if (!array_key_exists('reasons', $json)
@@ -187,7 +194,43 @@ class Class_WebService_SIGB_Koha_RestfulService
 
     $error = implode(', ', array_map([$this, '_getErrorFromCode'],
                                      $reasons, $reasons));
-    throw new Class_WebService_Exception($this->_('Erreur de mise à jour du mot de passe : %s', $error));
+    throw new Class_WebService_Exception($this->_('Erreur de mise à jour du mot de passe : %s',
+                                                  $error));
+  }
+
+
+  protected function _updateSigbUser($emprunteur) {
+    $data = $this->_prepareData($emprunteur);
+    $response = $this->restfulPut('user/' . $emprunteur->getLogin(),
+                                  ['data' => json_encode($data)]);
+
+    if (null === ($json = json_decode($response, true)))
+      throw new Class_WebService_Exception($this->_('Le format de la réponse envoyé par Koha à la demande de mise à jour des informations personnelles est incorrect.'));
+
+    if (array_key_exists('success', $json)
+        && $json['success'])
+      return $emprunteur;
+
+    $error = (array_key_exists('error', $json)
+              && $json['error'])
+      ? ' : ' . $json['error']
+      : '';
+
+    throw new Class_WebService_Exception($this->_('Erreur de mise à jour des informations%s',
+                                                  $error));
+  }
+
+
+  protected function _prepareData($emprunteur) {
+    return array_filter(['surname' => $emprunteur->getNom(),
+                         'firstname' => $emprunteur->getPrenom(),
+                         'address' => $emprunteur->getAdresse(),
+                         'city' => $emprunteur->getVille(),
+                         'zipcode' => $emprunteur->getCodePostal(),
+                         'email' => $emprunteur->getEmail(),
+                         'phone' => $emprunteur->getTelephone(),
+                         'mobile' => $emprunteur->getMobile(),
+                         'dateofbirth' => $emprunteur->getDateNaissance()]);
   }
 
 
diff --git a/tests/library/Class/WebService/SIGB/KohaRestfulTest.php b/tests/library/Class/WebService/SIGB/KohaRestfulTest.php
index 0705de0a210..4983e4d712b 100644
--- a/tests/library/Class/WebService/SIGB/KohaRestfulTest.php
+++ b/tests/library/Class/WebService/SIGB/KohaRestfulTest.php
@@ -562,8 +562,13 @@ class KohaRestfulChangePasswordTest extends KohaRestfulTestCase {
       ->with('http://cat-aficg55.biblibre.com/cgi-bin/koha/rest.pl/auth/change_password',
              ['user_name' => 'harlock',
               'new_password' => $password])
-      ->answers($response)
-      ->beStrict();
+      ->willDo(function() use ($response)
+               {
+                 $this->mock_web_client
+                   ->whenCalled('putData')
+                   ->answers('{"success":1}');
+                 return $response;
+               });
 
     $this->_user->setPassword($password);
     $this->_borrower->updateFromUser($this->_user);
@@ -610,4 +615,100 @@ class KohaRestfulChangePasswordTest extends KohaRestfulTestCase {
     $this->setPasswordWaitReply($password,json_encode($response));
     $this->assertEquals($password, Class_Users::find(34)->getPassword());
   }
+}
+
+
+
+
+class KohaRestfulEditUserTest extends KohaRestfulTestCase {
+
+  protected $_user, $_borrower;
+
+  public function setUp() {
+    parent::setUp();
+
+    $this->_borrower = new Class_WebService_SIGB_Emprunteur('harlock', 'harlock');
+    $this->_borrower->setService($this->service);
+
+    $this->_user = $this->fixture('Class_Users',
+                                  ['id' => 34,
+                                   'login' => 'harlock',
+                                   'role_level' => ZendAfi_Acl_AdminControllerRoles::ABONNE_SIGB,
+                                   'id_site' => 1,
+                                   'password' => 'arcadia',
+                                   'idabon' => 'AO989IE']);
+
+    $this->_user->setFicheSIGB(['fiche' => $this->_borrower]);
+    $this->_borrower->updateFromUser($this->_user);
+  }
+
+
+  public function setUserInfoWaitReply($user_info,$response){
+    $this->mock_web_client
+      ->whenCalled('putData')
+      ->willDo(function() use ($user_info,$response)
+               {
+                 $this->mock_web_client
+                   ->whenCalled('putData')
+                   ->with('http://cat-aficg55.biblibre.com/cgi-bin/koha/rest.pl/user/harlock',
+                          ['data' => json_encode($user_info)])
+                   ->answers($response)
+                   ->beStrict();
+                   return '{"success":1}';
+               }
+      );
+    $this->_borrower->updateFromUser($this->_user);
+    Class_Users::clearCache();
+    $this->_borrower->save();
+    $this->_user->save();
+  }
+
+
+  /** @test */
+  public function withoutResponseShouldNotUpdatePasswordAndTriggerException() {
+    $this->expectExceptionMessage('Le format de la réponse envoyé par Koha à la demande de mise à jour des informations personnelles est incorrect.');
+    $this->_user->setPrenom('captain');
+    $this->_user->setNom('haddock');
+    $this->setUserInfoWaitReply(['surname' => 'haddock',
+                                 'firstname' => 'captain'],
+                                '');
+  }
+
+
+  /** @test */
+  public function withErrorBorrowerNotFoundShouldFailAndNoticeUser() {
+    $this->expectExceptionMessage('Erreur de mise à jour des informations : Borrower not found');
+    $this->_user->setPrenom('captain');
+    $this->_user->setNom('haddock');
+    $this->setUserInfoWaitReply(['surname' => 'haddock',
+                                 'firstname' => 'captain'],
+                                '{"error": "Borrower not found."}');
+  }
+
+
+  /** @test */
+  public function withSuccessNullShouldFailAndThrowException() {
+    $this->expectExceptionMessage('Erreur de mise à jour des informations');
+    $this->_user->setPrenom('captain');
+    $this->_user->setNom('haddock');
+    $this->setUserInfoWaitReply(['surname' => 'haddock',
+                                 'firstname' => 'captain'],
+                                '{"success":0}');
+  }
+
+
+  /** @test */
+  public function withValidResponseShouldUpdateUser() {
+    $this->_user->setPrenom('captain');
+    $this->_user->setNom('haddock');
+    $this->_user->setMail('captain.haddock@tonnerre.bzh');
+    $this->setUserInfoWaitReply(['surname' => 'haddock',
+                                 'firstname' => 'captain',
+                                 'email' => 'captain.haddock@tonnerre.bzh'],
+                                json_encode(['success' => 1,
+                                             'modified_fields' => ['firstname',
+                                                                   'surname',
+                                                                   'email']]));
+    $this->assertEquals('captain', Class_Users::find(34)->getPrenom());
+  }
 }
\ No newline at end of file
-- 
GitLab