From 26ccdffb590b8d8b783caa9fe155f5cc5248fa0b Mon Sep 17 00:00:00 2001
From: Arthur Suzuki <arthur.suzuki@biblibre.com>
Date: Wed, 29 May 2019 01:50:49 +0200
Subject: [PATCH] Bug 17314 : Migration from Swagger2 to OpenApi

---
 Koha/REST/V1/Suggestions.pm                | 103 +++++++++++++----------------
 api/v1/swagger/definitions/suggestion.json |   8 +--
 api/v1/swagger/paths/suggestions.json      |  20 +++---
 3 files changed, 59 insertions(+), 72 deletions(-)

diff --git a/Koha/REST/V1/Suggestions.pm b/Koha/REST/V1/Suggestions.pm
index 4b771ff25c..fae6aff1a6 100644
--- a/Koha/REST/V1/Suggestions.pm
+++ b/Koha/REST/V1/Suggestions.pm
@@ -32,11 +32,11 @@ use Koha::Libraries;
 use Try::Tiny;
 
 sub list {
-    my ($c, $args, $cb) = @_;
+    my $c = shift->openapi->valid_input or return;
 
     my $suggestions;
     my $filter;
-    $args //= {};
+    my $args = $c->validation->output;
 
     for my $filter_param ( keys %$args ) {
         $filter->{$filter_param} = { LIKE => $args->{$filter_param} . '%' };
@@ -44,55 +44,54 @@ sub list {
 
     return try {
         $suggestions = Koha::Suggestions->search($filter)->unblessed;
-        return $c->$cb( $suggestions, 200 );
+        return $c->render( status => 200, openapi => $suggestions );
     }
     catch {
         if ( $_->isa('DBIx::Class::Exception') ) {
-            return $c->$cb( { error => $_->{msg} }, 500 );
+            return $c->render( status => 500, openapi => { error => $_->{msg} } );
         }
         else {
-            return $c->$cb(
-                { error => 'Something went wrong, check the logs.' }, 500 );
+            return $c->render( status => 500, openapi => { error => 'Something went wrong, check the logs.' } );
         }
     };
 }
 
 sub get {
-    my ($c, $args, $cb) = @_;
+    my $c = shift->openapi->valid_input or return;
+    my $args = $c->validation->output;
 
     my $suggestion = Koha::Suggestions->find($args->{suggestionid});
     unless ($suggestion) {
-        return $c->$cb({error => 'Suggestion not found'}, 404);
+        return $c->render( status => 404, openapi => {error => 'Suggestion not found'});
     }
 
-    return $c->$cb($suggestion->unblessed, 200);
+    return $c->render( status => 200, openapi => $suggestion->unblessed );
 }
 
 sub add {
-    my ( $c, $args, $cb ) = @_;
-
-    my $error = _validate_body($c, $args, $cb, 0);
-    return $error if $error;
+    my $c = shift->openapi->valid_input or return;
+    my $args = $c->validation->output;
 
     my $suggestion = Koha::Suggestion->new( $args->{body} );
 
     return try {
         $suggestion->store;
-        return $c->$cb( $suggestion->unblessed, 200 );
+        return $c->render( status => 200, openapi => $suggestion->unblessed );
     }
     catch {
         if ( $_->isa('DBIx::Class::Exception') ) {
-            return $c->$cb( { error => $_->msg }, 500 );
+            return $c->render( status => 500, openapi => { error => $_->msg } );
         }
         else {
-            return $c->$cb(
-                { error => 'Something went wrong, check the logs.' }, 500 );
+            return $c->render( status => 500, openapi => { error => 'Something went wrong, check the logs.' } );
         }
-    };
+    }
 }
 
 sub update {
-    my ( $c, $args, $cb ) = @_;
+    my $c = shift->openapi->valid_input or return;
+
+    my $args = $c->validation->output;
 
     my $suggestion;
 
@@ -109,55 +108,54 @@ sub update {
             }
         }
 
-        my $error = _validate_body($c, $args, $cb, 1);
-        return $error if $error;
-
         $suggestion->set( $body );
         $suggestion->store();
-        return $c->$cb( $suggestion->unblessed, 200 );
+        return $c->render( status => 200, openapi => $suggestion->unblessed );
     }
     catch {
         if ( not defined $suggestion ) {
-            return $c->$cb( { error => 'Object not found' }, 404 );
+            return $c->render( status => 404, openapi => { error => 'Object not found' } );
         }
         elsif ( $_->isa('Koha::Exceptions::Object') ) {
-            return $c->$cb( { error => $_->message }, 500 );
+            return $c->render( status => 500, openapi => { error => $_->message } );
         }
         else {
-            return $c->$cb(
-                { error => 'Something went wrong, check the logs.' }, 500 );
+            return $c->render( status => 500, openapi => { error => 'Something went wrong, check the logs.' } );
         }
     };
 
 }
 
 sub delete {
-    my ( $c, $args, $cb ) = @_;
+    my $c = shift->openapi->valid_input or return;
+
+    my $args = $c->validation->output;
 
     my $suggestion;
 
     return try {
         $suggestion = Koha::Suggestions->find( $args->{suggestionid} );
         $suggestion->delete;
-        return $c->$cb( '', 200 );
+        return $c->render( status => 200, openapi => '' );
     }
     catch {
         if ( not defined $suggestion ) {
-            return $c->$cb( { error => 'Object not found' }, 404 );
+            return $c->render( status => 404, openapi => { error => 'Object not found' } );
         }
         elsif ( $_->isa('DBIx::Class::Exception') ) {
-            return $c->$cb( { error => $_->msg }, 500 );
+            return $c->render( status => 500, openapi => { error => $_->msg } );
         }
         else {
-            return $c->$cb(
-                { error => 'Something went wrong, check the logs.' }, 500 );
+            return $c->render( status => 500, openapi => { error => 'Something went wrong, check the logs.' } );
         }
     };
 
 }
 
 sub _validate_body {
-    my ( $c, $args, $cb, $updating ) = @_;
+    my $c = shift->openapi->valid_input or return;
+
+    my $args = $c->validation->output;
 
     my $body = $args->{body};
     my $user = $c->stash('koha.user');
@@ -177,25 +175,14 @@ sub _validate_body {
         foreach my $param ( keys %{ $body } ) {
             unless (/^$param$/ ~~ @allowed_fields) {
                 # Ouch ! Some mandatory field is missing!
-                my $verb = $updating ? 'updated ' : 'specified ';
-                return $c->$cb({error => 'You ' . $verb . $param . ', but allowed fields are only ' .
-                        join(', ', @allowed_fields)}, 403);
+                my $verb = 'specified ';
+                return $c->render( status => 403 , openapi => {
+				error => 'You ' . $verb . $param . ', but allowed fields are only ' . join(', ', @allowed_fields)}
+				 );
             }
         }
     }
 
-    if (not $updating) {
-        # Check for missing fields
-        my @mandatory_fields = split /,/, C4::Context->preference('OPACSuggestionMandatoryFields');
-        my @missing_fields = ();
-        for my $mandatory_field (@mandatory_fields) {
-            push(@missing_fields, $mandatory_field) if (not exists $body->{$mandatory_field});
-        }
-
-        if ( @missing_fields ) {
-            return $c->$cb({error => 'Missing mandatory fields: ' . join(', ', @missing_fields)}, 400);
-        }
-    }
 
     # Is suggester anonymous?
     my $is_anonymous = not (defined $body->{suggestedby} and
@@ -204,7 +191,7 @@ sub _validate_body {
 
     # Refuse if are anonymous suggestions disabled
     if ( $is_anonymous ) {
-        return $c->$cb({error => 'Anonymous suggestions are disabled'}, 403)
+        return $c->render( status => 403, openapi => {error => 'Anonymous suggestions are disabled'} )
         unless C4::Context->preference('AnonSuggestions');
     }
 
@@ -213,47 +200,47 @@ sub _validate_body {
     if ( $max_open_suggestions gt 0 and not $is_anonymous ) {
         my $count = Koha::Suggestions->search({suggestedby => $body->{suggestedby}})->count();
 
-        return $c->$cb({error =>
-                'You have ' . $count . ' opened suggestions out of ' . $max_open_suggestions}, 403)
+        return $c->render( status => 403 , openapi => {error =>
+                'You have ' . $count . ' opened suggestions out of ' . $max_open_suggestions} )
         if ( $count >= $max_open_suggestions );
     }
 
     # Check STATUS is valid
     if ( exists $body->{STATUS} ) {
-        return $c->$cb({error => 'STATUS must be one of ASKED, CHECKED, ACCEPTED, or REJECTED'}, 400)
+        return $c->render( status => 400, openapi => {error => 'STATUS must be one of ASKED, CHECKED, ACCEPTED, or REJECTED'} )
         unless ($body->{STATUS} =~ m/^(ASKED|CHECKED|ACCEPTED|REJECTED)$/);
     }
 
     # Check itemtype is valid
     if ( exists $body->{itemtype} ) {
         my @item_types = map {$_->unblessed->{itemtype}} Koha::ItemTypes->search;
-        return $c->$cb({error => 'itemtype must be one of ' . join(', ', @item_types)}, 400)
+        return $c->render( status => 400 , openapi => {error => 'itemtype must be one of ' . join(', ', @item_types)} )
         unless /^$body->{itemtype}$/ ~~ @item_types;
     }
 
     # Check branchcode is valid
     if ( exists $body->{branchcode} ) {
         my @branch_codes = map {$_->unblessed->{branchcode}} Koha::Libraries->search;
-        return $c->$cb({error => 'branchcode must be one of ' . join(', ', @branch_codes)}, 400)
+        return $c->render( status => 400 , openapi => {error => 'branchcode must be one of ' . join(', ', @branch_codes)} )
         unless /^$body->{branchcode}$/ ~~ @branch_codes;
     }
 
     # Check patron reason is valid
     if ( exists $body->{patronreason} ) {
         my @authorized_values = map { $_->{authorised_value} } @{ C4::Koha::GetAuthorisedValues('OPAC_SUG') };
-        return $c->$cb({error => 'patronreason must be one of ' . join(', ', @authorized_values)}, 400)
+        return $c->render( status => 400, openapi => {error => 'patronreason must be one of ' . join(', ', @authorized_values)} )
         unless /^$body->{patronreason}$/ ~~ @authorized_values;
     }
 
     # Check suggestedby patron exists
     if ( exists $body->{suggestedby} ) {
-        return $c->$cb({error => 'suggestedby patron not found'}, 400)
+        return $c->render( status => 400 , openapi => {error => 'suggestedby patron not found'} )
         unless Koha::Patrons->find($body->{suggestedby});
     }
 
     # Check managedby patron exists
     if ( exists $body->{managedby} ) {
-        return $c->$cb({error => 'managedby patron not found'}, 400)
+        return $c->render( status => 400 , openapi => {error => 'managedby patron not found'} )
         unless Koha::Patrons->find($body->{managedby});
     }
 
diff --git a/api/v1/swagger/definitions/suggestion.json b/api/v1/swagger/definitions/suggestion.json
index 12ff222722..b789d09961 100644
--- a/api/v1/swagger/definitions/suggestion.json
+++ b/api/v1/swagger/definitions/suggestion.json
@@ -7,7 +7,7 @@
     },
     "suggestedby": {
       "type": "string",
-      "description": "borrowernumber for the person making the suggestion, foreign key linking to the borrowers table"
+      "description": "patron_id for the person making the suggestion, foreign key linking to the borrowers table"
     },
     "suggesteddate": {
       "type": "string",
@@ -15,7 +15,7 @@
     },
     "managedby": {
       "type": ["string", "null"],
-      "description": "borrowernumber for the librarian managing the suggestion, foreign key linking to the borrowers table"
+      "description": "patron_id for the librarian managing the suggestion, foreign key linking to the borrowers table"
     },
     "manageddate": {
       "type": ["string", "null"],
@@ -23,7 +23,7 @@
     },
     "acceptedby": {
       "type": ["string", "null"],
-      "description": "borrowernumber for the librarian who accepted the suggestion, foreign key linking to the borrowers table"
+      "description": "patron_id for the librarian who accepted the suggestion, foreign key linking to the borrowers table"
     },
     "accepteddate": {
       "type": ["string", "null"],
@@ -31,7 +31,7 @@
     },
     "rejectedby": {
       "type": ["string", "null"],
-      "description": "borrowernumber for the librarian who rejected the suggestion, foreign key linking to the borrowers table"
+      "description": "patron_id for the librarian who rejected the suggestion, foreign key linking to the borrowers table"
     },
     "rejecteddate": {
       "type": ["string", "null"],
diff --git a/api/v1/swagger/paths/suggestions.json b/api/v1/swagger/paths/suggestions.json
index dfef6cba05..091f5be01b 100644
--- a/api/v1/swagger/paths/suggestions.json
+++ b/api/v1/swagger/paths/suggestions.json
@@ -1,8 +1,8 @@
 {
   "/suggestions": {
     "get": {
-      "x-mojo-controller": "Koha::REST::V1::Suggestions",
-      "operationId": "list",
+      "x-mojo-to": "Suggestions#list",
+      "operationId" : "list",
       "tags": ["patrons", "suggestions"],
       "parameters": [
         {
@@ -15,25 +15,25 @@
           "name": "suggestedby",
           "in": "query",
           "type": "integer",
-          "description": "borrowernumber for the person making the suggestion, foreign key linking to the borrowers table"
+          "description": "patron_id for the person making the suggestion, foreign key linking to the borrowers table"
         },
         {
           "name": "managedby",
           "in": "query",
           "type": "integer",
-          "description": "borrowernumber for the librarian managing the suggestion, foreign key linking to the borrowers table"
+          "description": "patron_id for the librarian managing the suggestion, foreign key linking to the borrowers table"
         },
         {
           "name": "acceptedby",
           "in": "query",
           "type": "integer",
-          "description": "borrowernumber for the librarian who accepted the suggestion, foreign key linking to the borrowers table"
+          "description": "patron_id for the librarian who accepted the suggestion, foreign key linking to the borrowers table"
         },
         {
           "name": "rejectedby",
           "in": "query",
           "type": "integer",
-          "description": "borrowernumber for the librarian who rejected the suggestion, foreign key linking to the borrowers table"
+          "description": "patron_id for the librarian who rejected the suggestion, foreign key linking to the borrowers table"
         },
         {
           "name": "STATUS",
@@ -118,7 +118,7 @@
       }
     },
     "post": {
-      "x-mojo-controller": "Koha::REST::V1::Suggestions",
+      "x-mojo-to": "Suggestions#add",
       "operationId": "add",
       "tags": ["patrons", "suggestions"],
       "parameters": [{
@@ -169,7 +169,7 @@
   },
   "/suggestions/{suggestionid}": {
     "get": {
-      "x-mojo-controller": "Koha::REST::V1::Suggestions",
+      "x-mojo-to": "Suggestions#get",
       "operationId": "get",
       "tags": ["patrons", "suggestions"],
       "parameters": [{
@@ -208,7 +208,7 @@
       }
     },
     "put": {
-      "x-mojo-controller": "Koha::REST::V1::Suggestions",
+      "x-mojo-to": "Suggestions#update",
       "operationId": "update",
       "tags": ["patrons", "suggestions"],
       "parameters": [{
@@ -265,7 +265,7 @@
       }
     },
     "delete": {
-      "x-mojo-controller": "Koha::REST::V1::Suggestions",
+      "x-mojo-to": "Suggestions#delete",
       "operationId": "delete",
       "tags": ["patrons", "suggestions"],
       "parameters": [{
-- 
2.11.0