Bug 33161: (follow-up) Consistent use of db fields throughout
[koha-ffzg.git] / Koha / Object.pm
index 6a74140..102d715 100644 (file)
@@ -20,14 +20,16 @@ package Koha::Object;
 
 use Modern::Perl;
 
-use Carp;
+use Carp qw( croak );
 use Mojo::JSON;
 use Scalar::Util qw( blessed looks_like_number );
-use Try::Tiny;
+use Try::Tiny qw( catch try );
+use List::MoreUtils qw( any );
 
 use Koha::Database;
 use Koha::Exceptions::Object;
-use Koha::DateUtils;
+use Koha::DateUtils qw( dt_from_string output_pref );
+use Koha::Object::Message;
 
 =head1 NAME
 
@@ -77,6 +79,8 @@ sub new {
           $schema->resultset( $class->_type() )->new($attributes);
     }
 
+    $self->{_messages} = [];
+
     croak("No _type found! Koha::Object must be subclassed!")
       unless $class->_type();
 
@@ -127,7 +131,9 @@ sub store {
     # Handle not null and default values for integers and dates
     foreach my $col ( keys %{$columns_info} ) {
         # Integers
-        if ( _numeric_column_type( $columns_info->{$col}->{data_type} ) ) {
+        if (   _numeric_column_type( $columns_info->{$col}->{data_type} )
+            or _decimal_column_type( $columns_info->{$col}->{data_type} )
+        ) {
             # Has been passed but not a number, usually an empty string
             my $value = $self->_result()->get_column($col);
             if ( defined $value and not looks_like_number( $value ) ) {
@@ -217,9 +223,8 @@ sub update {
 Removes the object from storage.
 
 Returns:
-    1  if the deletion was a success
-    0  if the deletion failed
-    -1 if the object was never in storage
+    The item object if deletion was a success
+    The DBIX::Class error if deletion failed
 
 =cut
 
@@ -330,6 +335,50 @@ sub get_from_storage {
     return $object_class->_new_from_dbic($stored_object);
 }
 
+=head3 $object->object_messages
+
+    my @messages = @{ $object->object_messages };
+
+Returns the (probably non-fatal) messages that were recorded on the object.
+
+=cut
+
+sub object_messages {
+    my ( $self ) = @_;
+
+    $self->{_messages} = []
+        unless defined $self->{_messages};
+
+    return $self->{_messages};
+}
+
+=head3 $object->add_message
+
+    try {
+        <some action that might fail>
+    }
+    catch {
+        if ( <fatal condition> ) {
+            Koha::Exception->throw...
+        }
+
+        # This is a non fatal error, notify the caller
+        $self->add_message({ message => $error, type => 'error' });
+    }
+    return $self;
+
+Adds a message.
+
+=cut
+
+sub add_message {
+    my ( $self, $params ) = @_;
+
+    push @{ $self->{_messages} }, Koha::Object::Message->new($params);
+
+    return $self;
+}
+
 =head3 $object->TO_JSON
 
 Returns an unblessed representation of the object, suitable for JSON output.
@@ -358,8 +407,9 @@ sub TO_JSON {
         ) {
 
             # TODO: Remove once the solution for
-            # https://rt.cpan.org/Ticket/Display.html?id=119904
+            # https://github.com/perl5-dbi/DBD-mysql/issues/212
             # is ported to whatever distro we support by that time
+            # or we move to DBD::MariaDB
             $unblessed->{$col} += 0;
         }
         elsif ( _decimal_column_type( $columns_info->{$col}->{data_type} )
@@ -367,8 +417,9 @@ sub TO_JSON {
         ) {
 
             # TODO: Remove once the solution for
-            # https://rt.cpan.org/Ticket/Display.html?id=119904
+            # https://github.com/perl5-dbi/DBD-mysql/issues/212
             # is ported to whatever distro we support by that time
+            # or we move to DBD::MariaDB
             $unblessed->{$col} += 0.00;
         }
         elsif ( _datetime_column_type( $columns_info->{$col}->{data_type} ) ) {
@@ -408,8 +459,9 @@ sub _datetime_column_type {
 
 sub _numeric_column_type {
     # TODO: Remove once the solution for
-    # https://rt.cpan.org/Ticket/Display.html?id=119904
+    # https://github.com/perl5-dbi/DBD-mysql/issues/212
     # is ported to whatever distro we support by that time
+    # or we move to DBD::MariaDB
     my ($column_type) = @_;
 
     my @numeric_types = (
@@ -426,8 +478,9 @@ sub _numeric_column_type {
 
 sub _decimal_column_type {
     # TODO: Remove once the solution for
-    # https://rt.cpan.org/Ticket/Display.html?id=119904
+    # https://github.com/perl5-dbi/DBD-mysql/issues/212
     # is ported to whatever distro we support by that time
+    # or we move to DBD::MariaDB
     my ($column_type) = @_;
 
     my @decimal_types = (
@@ -486,6 +539,7 @@ sub prefetch_whitelist {
                     ...
                 }
             },
+            public => 0|1,
             ...
          ]
         }
@@ -499,33 +553,70 @@ sub to_api {
     my ( $self, $params ) = @_;
     my $json_object = $self->TO_JSON;
 
+    # Make sure we duplicate the $params variable to avoid
+    # breaking calls in a loop (Koha::Objects->to_api)
+    $params = defined $params ? {%$params} : {};
+
+    # children should be able to handle without
+    my $embeds  = delete $params->{embed};
+    my $strings = delete $params->{strings};
+
+    # coded values handling
+    my $avs = {};
+    if ( $strings and $self->can('api_strings_mapping') ) {
+        $avs = $self->api_strings_mapping($params);
+    }
+
+    # Remove forbidden attributes if required (including their coded values)
+    if ( $params->{public} ) {
+        for my $field ( keys %{$json_object} ) {
+            delete $json_object->{$field}
+              unless any { $_ eq $field } @{ $self->public_read_list };
+        }
+
+        if ($strings) {
+            foreach my $field ( keys %{$avs} ) {
+                delete $avs->{$field}
+                  unless any { $_ eq $field } @{ $self->public_read_list };
+            }
+        }
+    }
+
     my $to_api_mapping = $self->to_api_mapping;
 
-    # Rename attributes if there's a mapping
+    # Rename attributes and coded values if there's a mapping
     if ( $self->can('to_api_mapping') ) {
         foreach my $column ( keys %{ $self->to_api_mapping } ) {
             my $mapped_column = $self->to_api_mapping->{$column};
             if ( exists $json_object->{$column}
                 && defined $mapped_column )
             {
+
                 # key != undef
                 $json_object->{$mapped_column} = delete $json_object->{$column};
+                $avs->{$mapped_column}         = delete $avs->{$column}
+                  if exists $avs->{$column};
+
             }
             elsif ( exists $json_object->{$column}
                 && !defined $mapped_column )
             {
+
                 # key == undef
                 delete $json_object->{$column};
+                delete $avs->{$column};
             }
         }
     }
 
-    my $embeds = $params->{embed};
+    $json_object->{_strings} = $avs
+      if $strings;
 
     if ($embeds) {
         foreach my $embed ( keys %{$embeds} ) {
-            if ( $embed =~ m/^(?<relation>.*)_count$/
-                and $embeds->{$embed}->{is_count} ) {
+            if (    $embed =~ m/^(?<relation>.*)_count$/
+                and $embeds->{$embed}->{is_count} )
+            {
 
                 my $relation = $+{relation};
                 $json_object->{$embed} = $self->$relation->count;
@@ -534,25 +625,38 @@ sub to_api {
                 my $curr = $embed;
                 my $next = $embeds->{$curr}->{children};
 
+                $params->{strings} = 1
+                  if $embeds->{$embed}->{strings};
+
                 my $children = $self->$curr;
 
                 if ( defined $children and ref($children) eq 'ARRAY' ) {
                     my @list = map {
                         $self->_handle_to_api_child(
-                            { child => $_, next => $next, curr => $curr } )
+                            {
+                                child  => $_,
+                                next   => $next,
+                                curr   => $curr,
+                                params => $params
+                            }
+                        )
                     } @{$children};
                     $json_object->{$curr} = \@list;
                 }
                 else {
                     $json_object->{$curr} = $self->_handle_to_api_child(
-                        { child => $children, next => $next, curr => $curr } );
+                        {
+                            child  => $children,
+                            next   => $next,
+                            curr   => $curr,
+                            params => $params
+                        }
+                    );
                 }
             }
         }
     }
 
-
-
     return $json_object;
 }
 
@@ -572,6 +676,45 @@ sub to_api_mapping {
     return {};
 }
 
+=head3 api_strings_mapping
+
+    my $params = { is_public => 1 };
+    my $string_map = $object->api_strings_mapping($params);
+
+Generic method that returns the string map for coded attributes.
+
+Return should be a hashref keyed on database field name with the values
+being hashrefs containing 'str', 'type' and optionally 'category'.
+
+This is then use in to_api to render the _strings embed when requested.
+
+Note: this only returns an empty I<hashref>. Each class should have its
+own mapping returned.
+
+=cut
+
+sub api_strings_mapping {
+    return {};
+}
+
+=head3 public_read_list
+
+
+    my @public_read_list = @{$object->public_read_list};
+
+Generic method that returns the list of database columns that are allowed to
+be passed to render objects on the public API.
+
+Note: this only returns an empty I<arrayref>. Each class should have its
+own implementation.
+
+=cut
+
+sub public_read_list
+ {
+    return [];
+}
+
 =head3 from_api_mapping
 
     my $mapping = $object->from_api_mapping;
@@ -586,7 +729,8 @@ sub from_api_mapping {
 
     my $to_api_mapping = $self->to_api_mapping;
 
-    unless ( $self->{_from_api_mapping} ) {
+    unless ( defined $self->{_from_api_mapping} ) {
+        $self->{_from_api_mapping} = {};
         while (my ($key, $value) = each %{ $to_api_mapping } ) {
             $self->{_from_api_mapping}->{$value} = $key
                 if defined $value;
@@ -642,6 +786,7 @@ sub attributes_from_api {
 
     my $params;
     my $columns_info = $self->_result->result_source->columns_info;
+    my $dtf          = $self->_result->result_source->storage->datetime_parser;
 
     while (my ($key, $value) = each %{ $from_api_params } ) {
         my $koha_field_name =
@@ -656,7 +801,14 @@ sub attributes_from_api {
         }
         elsif ( _date_or_datetime_column_type( $columns_info->{$koha_field_name}->{data_type} ) ) {
             try {
-                $value = dt_from_string($value, 'rfc3339');
+                if ( $columns_info->{$koha_field_name}->{data_type} eq 'date' ) {
+                    $value = $dtf->format_date(dt_from_string($value, 'iso'))
+                        if defined $value;
+                }
+                else {
+                    $value = $dtf->format_datetime(dt_from_string($value, 'rfc3339'))
+                        if defined $value;
+                }
             }
             catch {
                 Koha::Exceptions::BadParameter->throw( parameter => $key );
@@ -797,19 +949,21 @@ sub _type { }
 sub _handle_to_api_child {
     my ($self, $args ) = @_;
 
-    my $child = $args->{child};
-    my $next  = $args->{next};
-    my $curr  = $args->{curr};
+    my $child  = $args->{child};
+    my $next   = $args->{next};
+    my $curr   = $args->{curr};
+    my $params = $args->{params};
 
     my $res;
 
     if ( defined $child ) {
 
-        Koha::Exceptions::Exception->throw( "Asked to embed $curr but its return value doesn't implement to_api" )
+        Koha::Exception->throw( "Asked to embed $curr but its return value doesn't implement to_api" )
             if defined $next and blessed $child and !$child->can('to_api');
 
         if ( blessed $child ) {
-            $res = $child->to_api({ embed => $next });
+            $params->{embed} = $next;
+            $res = $child->to_api($params);
         }
         else {
             $res = $child;