Bug 31552: SIP2 option format_due_date not honored for AH field in item information...
[koha-ffzg.git] / C4 / SIP / Sip / MsgType.pm
index 425ff76..cad82e0 100644 (file)
@@ -9,7 +9,6 @@ package C4::SIP::Sip::MsgType;
 use strict;
 use warnings;
 use Exporter;
-use Sys::Syslog qw(syslog);
 
 use C4::SIP::Sip qw(:all);
 use C4::SIP::Sip::Constants qw(:all);
@@ -19,7 +18,11 @@ use Data::Dumper;
 use CGI qw ( -utf8 );
 use C4::Auth qw(&check_api_auth);
 
+use Koha::Patrons;
 use Koha::Patron::Attributes;
+use Koha::Plugins;
+use Koha::Items;
+use Koha::DateUtils qw( output_pref );
 
 use UNIVERSAL::can;
 
@@ -69,12 +72,12 @@ my %handlers = (
         handler  => \&handle_checkout,
         protocol => {
             1 => {
-                template     => "CCA18A18",
+                template     => "A1A1A18A18",
                 template_len => 38,
                 fields       => [ (FID_INST_ID), (FID_PATRON_ID), (FID_ITEM_ID), (FID_TERMINAL_PWD) ],
             },
             2 => {
-                template     => "CCA18A18",
+                template     => "A1A1A18A18",
                 template_len => 38,
                 fields       => [ (FID_INST_ID), (FID_PATRON_ID), (FID_ITEM_ID), (FID_TERMINAL_PWD), (FID_ITEM_PROPS), (FID_PATRON_PWD), (FID_FEE_ACK), (FID_CANCEL) ],
             },
@@ -85,12 +88,12 @@ my %handlers = (
         handler  => \&handle_checkin,
         protocol => {
             1 => {
-                template     => "CA18A18",
+                template     => "A1A18A18",
                 template_len => 37,
                 fields       => [ (FID_CURRENT_LOCN), (FID_INST_ID), (FID_ITEM_ID), (FID_TERMINAL_PWD) ],
             },
             2 => {
-                template     => "CA18A18",
+                template     => "A1A18A18",
                 template_len => 37,
                 fields       => [ (FID_CURRENT_LOCN), (FID_INST_ID), (FID_ITEM_ID), (FID_TERMINAL_PWD), (FID_ITEM_PROPS), (FID_CANCEL) ],
             }
@@ -101,7 +104,7 @@ my %handlers = (
         handler  => \&handle_block_patron,
         protocol => {
             1 => {
-                template     => "CA18",
+                template     => "A1A18",
                 template_len => 19,
                 fields       => [ (FID_INST_ID), (FID_BLOCKED_CARD_MSG), (FID_PATRON_ID), (FID_TERMINAL_PWD) ],
             },
@@ -112,7 +115,7 @@ my %handlers = (
         handler  => \&handle_sc_status,
         protocol => {
             1 => {
-                template     => "CA3A4",
+                template     => "A1A3A4",
                 template_len => 8,
                 fields       => [],
             }
@@ -123,7 +126,7 @@ my %handlers = (
         handler  => \&handle_request_acs_resend,
         protocol => {
             1 => {
-                template     => "",
+                template     => q{},
                 template_len => 0,
                 fields       => [],
             }
@@ -225,7 +228,7 @@ my %handlers = (
         handler  => \&handle_renew,
         protocol => {
             2 => {
-                template     => "CCA18A18",
+                template     => "A1A1A18A18",
                 template_len => 38,
                 fields       => [ (FID_INST_ID), (FID_PATRON_ID), (FID_PATRON_PWD), (FID_ITEM_ID), (FID_TITLE_ID), (FID_TERMINAL_PWD), (FID_ITEM_PROPS), (FID_FEE_ACK) ],
             }
@@ -266,14 +269,14 @@ sub new {
         # it's using the 2.00 login process, so it must support 2.00.
         $protocol_version = 2;
     }
-    syslog( "LOG_DEBUG", "Sip::MsgType::new('%s', '%s...', '%s'): seq.no '%s', protocol %s", $class, substr( $msg, 0, 10 ), $msgtag, $seqno, $protocol_version );
+    siplog( "LOG_DEBUG", "Sip::MsgType::new('%s', '%s...', '%s'): seq.no '%s', protocol %s", $class, substr( $msg, 0, 10 ), $msgtag, $seqno, $protocol_version );
 
     # warn "SIP PROTOCOL: $protocol_version";
     if ( !exists( $handlers{$msgtag} ) ) {
-        syslog( "LOG_WARNING", "new Sip::MsgType: Skipping message of unknown type '%s' in '%s'", $msgtag, $msg );
+        siplog( "LOG_WARNING", "new Sip::MsgType: Skipping message of unknown type '%s' in '%s'", $msgtag, $msg );
         return;
     } elsif ( !exists( $handlers{$msgtag}->{protocol}->{$protocol_version} ) ) {
-        syslog( "LOG_WARNING", "new Sip::MsgType: Skipping message '%s' unsupported by protocol rev. '%d'", $msgtag, $protocol_version );
+        siplog( "LOG_WARNING", "new Sip::MsgType: Skipping message '%s' unsupported by protocol rev. '%d'", $msgtag, $protocol_version );
         return;
     }
 
@@ -305,7 +308,7 @@ sub _initialize {
         $self->{fields}->{$field} = undef;
     }
 
-    syslog( "LOG_DEBUG", "Sip::MsgType::_initialize('%s', '%s', '%s', '%s', ...)", $self->{name}, $msg, $proto->{template}, $proto->{template_len} );
+    siplog( "LOG_DEBUG", "Sip::MsgType::_initialize('%s', '%s', '%s', '%s', ...)", $self->{name}, $msg, $proto->{template}, $proto->{template_len} );
 
     $self->{fixed_fields} = [ unpack( $proto->{template}, $msg ) ];    # see http://perldoc.perl.org/5.8.8/functions/unpack.html
 
@@ -315,9 +318,9 @@ sub _initialize {
         $fn = substr( $field, 0, 2 );
 
         if ( !exists( $self->{fields}->{$fn} ) ) {
-            syslog( "LOG_WARNING", "Unsupported field '%s' in %s message '%s'", $fn, $self->{name}, $msg );
+            siplog( "LOG_WARNING", "Unsupported field '%s' in %s message '%s'", $fn, $self->{name}, $msg );
         } elsif ( defined( $self->{fields}->{$fn} ) ) {
-            syslog( "LOG_WARNING", "Duplicate field '%s' (previous value '%s') in %s message '%s'", $fn, $self->{fields}->{$fn}, $self->{name}, $msg );
+            siplog( "LOG_WARNING", "Duplicate field '%s' (previous value '%s') in %s message '%s'", $fn, $self->{fields}->{$fn}, $self->{name}, $msg );
         } else {
             $self->{fields}->{$fn} = substr( $field, 2 );
         }
@@ -333,7 +336,7 @@ sub handle {
 
     # Set system preference overrides, first global, then account level
     # Clear overrides from previous message handling first
-    foreach my $key ( %ENV ) {
+    foreach my $key ( keys %ENV ) {
         delete $ENV{$key} if index($key, 'OVERRIDE_SYSPREF_') > 0;
     }
     foreach my $key ( keys %{ $config->{'syspref_overrides'} } ) {
@@ -366,7 +369,7 @@ sub handle {
         $error_detection = 1;
 
         if ( !verify_cksum($msg) ) {
-            syslog( "LOG_WARNING", "Checksum failed on message '%s'", $msg );
+            siplog( "LOG_WARNING", "Checksum failed on message '%s'", $msg );
 
             # REQUEST_SC_RESEND with error detection
             $last_response = REQUEST_SC_RESEND_CKSUM;
@@ -382,7 +385,7 @@ sub handle {
 
         # We received a non-ED message when ED is supposed to be active.
         # Warn about this problem, then process the message anyway.
-        syslog( "LOG_WARNING", "Received message without error detection: '%s'", $msg );
+        siplog( "LOG_WARNING", "Received message without error detection: '%s'", $msg );
         $error_detection = 0;
         $self = C4::SIP::Sip::MsgType->new( $msg, 0 );
     } else {
@@ -395,7 +398,7 @@ sub handle {
         return substr( $msg, 0, 2 );
     }
     unless ( $self->{handler} ) {
-        syslog( "LOG_WARNING", "No handler defined for '%s'", $msg );
+        siplog( "LOG_WARNING", "No handler defined for '%s'", $msg );
         $last_response = REQUEST_SC_RESEND;
         print("$last_response\r");
         return REQUEST_ACS_RESEND;
@@ -433,9 +436,14 @@ sub build_patron_status {
             $password_rc = $patron->check_password($patron_pwd);
         }
 
-        $resp .= patron_status_string($patron);
+        $resp .= patron_status_string( $patron, $server );
         $resp .= $lang . timestamp();
-        $resp .= add_field( FID_PERSONAL_NAME, $patron->name( $server->{account}->{ae_field_template} ), $server );
+        if ( defined $server->{account}->{ae_field_template} ) {
+            $resp .= add_field( FID_PERSONAL_NAME, $patron->format( $server->{account}->{ae_field_template}, $server ) );
+        } else {
+            $resp .= add_field( FID_PERSONAL_NAME, $patron->name, $server );
+        }
+
 
         # while the patron ID we got from the SC is valid, let's
         # use the one returned from the ILS, just in case...
@@ -452,12 +460,13 @@ sub build_patron_status {
 
         my $msg = $patron->screen_msg;
         $msg .= ' -- '. INVALID_PW if $patron_pwd && !$password_rc;
-        $resp .= maybe_add( FID_SCREEN_MSG, $msg, $server, $server );
+        $resp .= maybe_add( FID_SCREEN_MSG, $msg, $server );
 
         $resp .= maybe_add( FID_SCREEN_MSG, $patron->{branchcode}, $server )
           if ( $server->{account}->{send_patron_home_library_in_af} );
         $resp .= maybe_add( FID_PRINT_LINE, $patron->print_line, $server );
 
+        $resp .= $patron->build_custom_field_string( $server );
         $resp .= $patron->build_patron_attributes_string( $server );
 
     } else {
@@ -475,7 +484,7 @@ sub build_patron_status {
         ( $protocol_version >= 2 )
           and $resp .= add_field( FID_VALID_PATRON, 'N', $server );
 
-        $resp .= maybe_add( FID_SCREEN_MSG, INVALID_CARD, $server, $server );
+        $resp .= maybe_add( FID_SCREEN_MSG, INVALID_CARD, $server );
     }
 
     $resp .= add_field( FID_INST_ID, $fields->{ (FID_INST_ID) }, $server );
@@ -513,6 +522,7 @@ sub handle_checkout {
     $fields = $self->{fields};
 
     $patron_id = $fields->{ (FID_PATRON_ID) };
+    Koha::Plugins->call('patron_barcode_transform', \$patron_id );
     $item_id   = $fields->{ (FID_ITEM_ID) };
     my $fee_ack = $fields->{ (FID_FEE_ACK) };
 
@@ -520,14 +530,14 @@ sub handle_checkout {
 
         # Off-line transactions need to be recorded, but there's
         # not a lot we can do about it
-        syslog( "LOG_WARNING", "received no-block checkout from terminal '%s'", $account->{id} );
+        siplog( "LOG_WARNING", "received no-block checkout from terminal '%s'", $account->{id} );
 
-        $status = $ils->checkout_no_block( $patron_id, $item_id, $sc_renewal_policy, $trans_date, $nb_due_date );
+        $status = $ils->checkout( $patron_id, $item_id, $sc_renewal_policy, $fee_ack, $account, $nb_due_date );
     } else {
 
         # Does the transaction date really matter for items that are
         # checkout out while the terminal is online?  I'm guessing 'no'
-        $status = $ils->checkout( $patron_id, $item_id, $sc_renewal_policy, $fee_ack );
+        $status = $ils->checkout( $patron_id, $item_id, $sc_renewal_policy, $fee_ack, $account );
     }
 
     $item   = $status->item;
@@ -546,7 +556,16 @@ sub handle_checkout {
         }
 
         # We never return the obsolete 'U' value for 'desensitize'
-        $resp .= sipbool( $status->desensitize );
+        $resp .= sipbool(
+            desensitize(
+                {
+                    item   => $item,
+                    patron => $patron,
+                    server => $server,
+                    status => $status,
+                }
+            )
+        );
         $resp .= timestamp;
 
         # Now for the variable fields
@@ -555,12 +574,16 @@ sub handle_checkout {
         $resp .= add_field( FID_ITEM_ID,   $item_id, $server );
         $resp .= add_field( FID_TITLE_ID,  $item->title_id, $server );
         if ( $item->due_date ) {
-            $resp .= add_field( FID_DUE_DATE, timestamp( $item->due_date ), $server );
+            my $due_date =
+              $account->{format_due_date}
+              ? output_pref( { str => $item->due_date, as_due_date => 1 } )
+              : timestamp( $item->due_date );
+            $resp .= add_field( FID_DUE_DATE, $due_date, $server );
         } else {
             $resp .= add_field( FID_DUE_DATE, q{}, $server );
         }
 
-        $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server, $server );
+        $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server );
         $resp .= maybe_add( FID_PRINT_LINE, $status->print_line, $server );
 
         if ( $protocol_version >= 2 ) {
@@ -591,7 +614,7 @@ sub handle_checkout {
         # it's not due, so leave the date blank
         $resp .= add_field( FID_DUE_DATE, '', $server );
 
-        $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server, $server );
+        $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server );
         $resp .= maybe_add( FID_PRINT_LINE, $status->print_line, $server );
 
         if ( $protocol_version >= 2 ) {
@@ -607,6 +630,8 @@ sub handle_checkout {
         }
     }
 
+    $resp .= $item->build_additional_item_fields_string( $server ) if $item;
+
     if ( $protocol_version >= 2 ) {
 
         # Financials : return irrespective of ok status
@@ -647,10 +672,10 @@ sub handle_checkin {
     if ( $no_block eq 'Y' ) {
 
         # Off-line transactions, ick.
-        syslog( "LOG_WARNING", "received no-block checkin from terminal '%s'", $account->{id} );
+        siplog( "LOG_WARNING", "received no-block checkin from terminal '%s'", $account->{id} );
         $status = $ils->checkin_no_block( $item_id, $trans_date, $return_date, $item_props, $cancel );
     } else {
-        $status = $ils->checkin( $item_id, $trans_date, $return_date, $my_branch, $item_props, $cancel, $account->{checked_in_ok}, $account->{cv_triggers_alert} );
+        $status = $ils->checkin( $item_id, $trans_date, $return_date, $my_branch, $item_props, $cancel, $account );
     }
 
     $patron = $status->patron;
@@ -674,6 +699,7 @@ sub handle_checkin {
     if ($item) {
         $resp .= add_field( FID_PERM_LOCN, $item->permanent_location, $server );
         $resp .= maybe_add( FID_TITLE_ID, $item->title_id, $server );
+        $resp .= $item->build_additional_item_fields_string( $server );
     }
 
     if ( $protocol_version >= 2 ) {
@@ -682,13 +708,18 @@ sub handle_checkin {
             $resp .= add_field( FID_PATRON_ID, $patron->id, $server );
         }
         if ($item) {
-$resp .= maybe_add( FID_MEDIA_TYPE,           $item->sip_media_type,      $server );
-$resp .= maybe_add( FID_ITEM_PROPS,           $item->sip_item_properties, $server );
-$resp .= maybe_add( FID_COLLECTION_CODE,      $item->collection_code,     $server );
-$resp .= maybe_add( FID_CALL_NUMBER,          $item->call_number,         $server );
-$resp .= maybe_add( FID_HOLD_PATRON_ID,       $item->hold_patron_bcode,   $server );
-$resp .= add_field( FID_DESTINATION_LOCATION, $item->destination_loc,     $server ) if ( $item->destination_loc || $server->{account}->{ct_always_send} );
-$resp .= maybe_add( FID_HOLD_PATRON_NAME,     $item->hold_patron_name( $server->{account}->{da_field_template} ), $server );
+            $resp .= maybe_add( FID_MEDIA_TYPE,           $item->sip_media_type,      $server );
+            $resp .= maybe_add( FID_ITEM_PROPS,           $item->sip_item_properties, $server );
+            $resp .= maybe_add( FID_CALL_NUMBER,          $item->call_number,         $server );
+            $resp .= maybe_add( FID_HOLD_PATRON_ID,       $item->hold_patron_bcode,   $server );
+            $resp .= add_field( FID_DESTINATION_LOCATION, $item->destination_loc,     $server ) if ( $item->destination_loc || $server->{account}->{ct_always_send} );
+            $resp .= maybe_add( FID_HOLD_PATRON_NAME,     $item->hold_patron_name( $server->{account}->{da_field_template} ), $server );
+
+            if ( my $CR = $server->{account}->{cr_item_field} ) {
+                $resp .= maybe_add( FID_COLLECTION_CODE, $item->{$CR}, $server );
+            } else {
+                $resp .= maybe_add( FID_COLLECTION_CODE, $item->collection_code, $server );
+            }
 
             if ( $status->hold and $status->hold->{branchcode} ne $item->destination_loc ) {
                 warn 'SIP hold mismatch: $status->hold->{branchcode}=' . $status->hold->{branchcode} . '; $item->destination_loc=' . $item->destination_loc;
@@ -726,6 +757,8 @@ sub handle_block_patron {
     $patron_id        = $fields->{ (FID_PATRON_ID) };
     $terminal_pwd     = $fields->{ (FID_TERMINAL_PWD) };
 
+    Koha::Plugins->call('patron_barcode_transform', \$patron_id );
+
     # Terminal passwords are different from account login
     # passwords, but I have no idea what to do with them.  So,
     # I'll just ignore them for now.
@@ -766,19 +799,19 @@ sub handle_sc_status {
     } elsif ( $sc_protocol_version =~ /^2\./ ) {
         $new_proto = 2;
     } else {
-        syslog( "LOG_WARNING", "Unrecognized protocol revision '%s', falling back to '1'", $sc_protocol_version );
+        siplog( "LOG_WARNING", "Unrecognized protocol revision '%s', falling back to '1'", $sc_protocol_version );
         $new_proto = 1;
     }
 
     if ( $new_proto != $protocol_version ) {
-        syslog( "LOG_INFO", "Setting protocol level to $new_proto" );
+        siplog( "LOG_INFO", "Setting protocol level to $new_proto" );
         $protocol_version = $new_proto;
     }
 
     if ( $status == SC_STATUS_PAPER ) {
-        syslog( "LOG_WARNING", "Self-Check unit '%s@%s' out of paper", $self->{account}->{id}, $self->{account}->{institution} );
+        siplog( "LOG_WARNING", "Self-Check unit '%s@%s' out of paper", $self->{account}->{id}, $self->{account}->{institution} );
     } elsif ( $status == SC_STATUS_SHUTDOWN ) {
-        syslog( "LOG_WARNING", "Self-Check unit '%s@%s' shutting down", $self->{account}->{id}, $self->{account}->{institution} );
+        siplog( "LOG_WARNING", "Self-Check unit '%s@%s' shutting down", $self->{account}->{id}, $self->{account}->{institution} );
     }
 
     $self->{account}->{print_width} = $print_width;
@@ -818,10 +851,10 @@ sub login_core {
     my $pwd    = shift;
     my $status = 1;                 # Assume it all works
     if ( !exists( $server->{config}->{accounts}->{$uid} ) ) {
-        syslog( "LOG_WARNING", "MsgType::login_core: Unknown login '$uid'" );
+        siplog( "LOG_WARNING", "MsgType::login_core: Unknown login '$uid'" );
         $status = 0;
     } elsif ( $server->{config}->{accounts}->{$uid}->{password} ne $pwd ) {
-        syslog( "LOG_WARNING", "MsgType::login_core: Invalid password for login '$uid'" );
+        siplog( "LOG_WARNING", "MsgType::login_core: Invalid password for login '$uid'" );
         $status = 0;
     } else {
 
@@ -835,16 +868,16 @@ sub login_core {
 
         my $auth_status = api_auth( $uid, $pwd, $inst );
         if ( !$auth_status or $auth_status !~ /^ok$/i ) {
-            syslog( "LOG_WARNING", "api_auth failed for SIP terminal '%s' of '%s': %s", $uid, $inst, ( $auth_status || 'unknown' ) );
+            siplog( "LOG_WARNING", "api_auth failed for SIP terminal '%s' of '%s': %s", $uid, $inst, ( $auth_status || 'unknown' ) );
             $status = 0;
         } else {
-            syslog( "LOG_INFO", "Successful login/auth for '%s' of '%s'", $server->{account}->{id}, $inst );
+            siplog( "LOG_INFO", "Successful login/auth for '%s' of '%s'", $server->{account}->{id}, $inst );
 
             #
             # initialize connection to ILS
             #
             my $module = $server->{config}->{institutions}->{$inst}->{implementation};
-            syslog( "LOG_DEBUG", 'login_core: ' . Dumper($module) );
+            siplog( "LOG_DEBUG", 'login_core: ' . Dumper($module) );
 
             # Suspect this is always ILS but so we don't break any eccentic install (for now)
             if ( $module eq 'ILS' ) {
@@ -852,14 +885,14 @@ sub login_core {
             }
             $module->use;
             if ($@) {
-                syslog( "LOG_ERR", "%s: Loading ILS implementation '%s' for institution '%s' failed", $server->{service}, $module, $inst );
+                siplog( "LOG_ERR", "%s: Loading ILS implementation '%s' for institution '%s' failed", $server->{service}, $module, $inst );
                 die("Failed to load ILS implementation '$module' for $inst");
             }
 
             # like   ILS->new(), I think.
             $server->{ils} = $module->new( $server->{institution}, $server->{account} );
             if ( !$server->{ils} ) {
-                syslog( "LOG_ERR", "%s: ILS connection to '%s' failed", $server->{service}, $inst );
+                siplog( "LOG_ERR", "%s: ILS connection to '%s' failed", $server->{service}, $inst );
                 die("Unable to connect to ILS '$inst'");
             }
         }
@@ -882,7 +915,7 @@ sub handle_login {
     $pwd = $fields->{ (FID_LOGIN_PWD) };    # Terminal PWD, not patron PWD.
 
     if ( $uid_algorithm || $pwd_algorithm ) {
-        syslog( "LOG_ERR", "LOGIN: Unsupported non-zero encryption method(s): uid = $uid_algorithm, pwd = $pwd_algorithm" );
+        siplog( "LOG_ERR", "LOGIN: Unsupported non-zero encryption method(s): uid = $uid_algorithm, pwd = $pwd_algorithm" );
         $status = 0;
     } else {
         $status = login_core( $server, $uid, $pwd );
@@ -902,7 +935,6 @@ sub handle_login {
 sub summary_info {
     my ( $ils, $patron, $summary, $start, $end, $server ) = @_;
     my $resp = '';
-    my $summary_type;
 
     #
     # Map from offsets in the "summary" field of the Patron Information
@@ -917,17 +949,18 @@ sub summary_info {
         { func => $patron->can("unavail_holds"), fid => FID_UNAVAILABLE_HOLD_ITEMS },
     );
 
-    if ( ( $summary_type = index( $summary, 'Y' ) ) == -1 ) {
-        return '';    # No detailed information required
-    }
+    my $summary_type = index( $summary, 'Y' );
+    return q{} if $summary_type == -1;    # No detailed information required.
+    return q{} if $summary_type > 5;      # Positions 6-9 are not defined in the sip spec,
+                                          # and we have no extensions to handle them.
 
-    syslog( "LOG_DEBUG", "Summary_info: index == '%d', field '%s'", $summary_type, $summary_map[$summary_type]->{fid} );
+    siplog( "LOG_DEBUG", "Summary_info: index == '%d', field '%s'", $summary_type, $summary_map[$summary_type]->{fid} );
 
     my $func     = $summary_map[$summary_type]->{func};
     my $fid      = $summary_map[$summary_type]->{fid};
     my $itemlist = &$func( $patron, $start, $end, $server );
 
-    syslog( "LOG_DEBUG", "summary_info: list = (%s)", join( ", ", @{$itemlist} ) );
+    siplog( "LOG_DEBUG", "summary_info: list = (%s)", join( ", ", map{ $_->{barcode} } @{$itemlist} ) );
     foreach my $i ( @{$itemlist} ) {
         $resp .= add_field( $fid, $i->{barcode}, $server );
     }
@@ -950,12 +983,14 @@ sub handle_patron_info {
     $start        = $fields->{ (FID_START_ITEM) };
     $end          = $fields->{ (FID_END_ITEM) };
 
+    Koha::Plugins->call('patron_barcode_transform', \$patron_id );
+
     $patron = $ils->find_patron($patron_id);
 
     $resp = (PATRON_INFO_RESP);
     if ($patron) {
         $patron->update_lastseen();
-        $resp .= patron_status_string($patron);
+        $resp .= patron_status_string( $patron, $server );
         $resp .= ( defined($lang) and length($lang) == 3 ) ? $lang : $patron->language;
         $resp .= timestamp();
 
@@ -971,7 +1006,11 @@ sub handle_patron_info {
         # while the patron ID we got from the SC is valid, let's
         # use the one returned from the ILS, just in case...
         $resp .= add_field( FID_PATRON_ID,     $patron->id, $server );
-        $resp .= add_field( FID_PERSONAL_NAME, $patron->name( $server->{account}->{ae_field_template} ), $server );
+        if ( defined $server->{account}->{ae_field_template} ) {
+            $resp .= add_field( FID_PERSONAL_NAME, $patron->format( $server->{account}->{ae_field_template} ), $server );
+        } else {
+            $resp .= add_field( FID_PERSONAL_NAME, $patron->name, $server );
+        }
 
         # TODO: add code for the fields
         #   hold items limit
@@ -1020,12 +1059,13 @@ sub handle_patron_info {
         if( defined( $patron_pwd ) && !$password_rc ) {
             $msg .= ' -- ' . INVALID_PW;
         }
-        $resp .= maybe_add( FID_SCREEN_MSG, $msg, $server, $server );
+        $resp .= maybe_add( FID_SCREEN_MSG, $msg, $server );
         if ( $server->{account}->{send_patron_home_library_in_af} ) {
             $resp .= maybe_add( FID_SCREEN_MSG, $patron->{branchcode}, $server);
         }
         $resp .= maybe_add( FID_PRINT_LINE, $patron->print_line, $server );
 
+        $resp .= $patron->build_custom_field_string( $server );
         $resp .= $patron->build_patron_attributes_string( $server );
     } else {
 
@@ -1044,7 +1084,7 @@ sub handle_patron_info {
         if ( $protocol_version >= 2 ) {
             $resp .= add_field( FID_VALID_PATRON, 'N', $server );
         }
-        $resp .= maybe_add( FID_SCREEN_MSG, INVALID_CARD, $server, $server );
+        $resp .= maybe_add( FID_SCREEN_MSG, INVALID_CARD, $server );
     }
 
     $self->write_msg( $resp, undef, $server->{account}->{terminator}, $server->{account}->{encoding} );
@@ -1071,7 +1111,7 @@ sub handle_end_patron_session {
     $resp .= add_field( FID_INST_ID, $server->{ils}->institution, $server );
     $resp .= add_field( FID_PATRON_ID, $fields->{ (FID_PATRON_ID) }, $server );
 
-    $resp .= maybe_add( FID_SCREEN_MSG, $screen_msg, $server, $server );
+    $resp .= maybe_add( FID_SCREEN_MSG, $screen_msg, $server );
     $resp .= maybe_add( FID_PRINT_LINE, $print_line, $server );
 
     $self->write_msg( $resp, undef, $server->{account}->{terminator}, $server->{account}->{encoding} );
@@ -1091,6 +1131,7 @@ sub handle_fee_paid {
 
     my $disallow_overpayment  = $server->{account}->{disallow_overpayment};
     my $payment_type_writeoff = $server->{account}->{payment_type_writeoff} || q{};
+    my $register_id           = $server->{account}->{register_id};
 
     my $is_writeoff = $pay_type eq $payment_type_writeoff;
 
@@ -1101,15 +1142,56 @@ sub handle_fee_paid {
     $fee_id     = $fields->{ (FID_FEE_ID) };
     $trans_id   = $fields->{ (FID_TRANSACTION_ID) };
 
+    Koha::Plugins->call('patron_barcode_transform', \$patron_id );
+
     $ils->check_inst_id( $inst_id, "handle_fee_paid" );
 
-    $status = $ils->pay_fee( $patron_id, $patron_pwd, $fee_amt, $fee_type, $pay_type, $fee_id, $trans_id, $currency, $is_writeoff, $disallow_overpayment );
+    my $pay_result = $ils->pay_fee( $patron_id, $patron_pwd, $fee_amt, $fee_type, $pay_type, $fee_id, $trans_id, $currency, $is_writeoff, $disallow_overpayment, $register_id );
+    $status = $pay_result->{status};
+    my $pay_response = $pay_result->{pay_response};
+
+    my $failmap = {
+        "no_item" => "No matching item could be found",
+        "no_checkout" => "Item is not checked out",
+        "too_soon" => "Cannot yet be renewed",
+        "too_many" => "Renewed the maximum number of times",
+        "auto_too_soon" => "Scheduled for automatic renewal and cannot yet be renewed",
+        "auto_too_late" => "Scheduled for automatic renewal and cannot yet be any more",
+        "auto_account_expired" => "Scheduled for automatic renewal and cannot be renewed because the patron's account has expired",
+        "auto_renew" => "Scheduled for automatic renewal",
+        "auto_too_much_oweing" => "Scheduled for automatic renewal",
+        "on_reserve" => "On hold for another patron",
+        "patron_restricted" => "Patron is currently restricted",
+        "item_denied_renewal" => "Item is not allowed renewal",
+        "onsite_checkout" => "Item is an onsite checkout"
+    };
+    my @success = ();
+    my @fail = ();
+    foreach my $result( @{$pay_response->{renew_result}} ) {
+        my $item = Koha::Items->find({ itemnumber => $result->{itemnumber} });
+        if ($result->{success}) {
+            push @success, '"' . $item->biblio->title . '"';
+        } else {
+            push @fail, '"' . $item->biblio->title . '" : ' . $failmap->{$result->{error}};
+        }
+    }
+
+    my $msg = "";
+    if (scalar @success > 0) {
+        $msg.="The following items were renewed: " . join(", ", @success) . ". ";
+    }
+    if (scalar @fail > 0) {
+        $msg.="The following items were not renewed: " . join(", ", @fail) . ".";
+    }
+    if (length $msg > 0) {
+        $status->screen_msg($status->screen_msg . " $msg");
+    }
 
     $resp .= ( $status->ok ? 'Y' : 'N' ) . timestamp;
     $resp .= add_field( FID_INST_ID,   $inst_id, $server );
     $resp .= add_field( FID_PATRON_ID, $patron_id, $server );
     $resp .= maybe_add( FID_TRANSACTION_ID, $status->transaction_id, $server );
-    $resp .= maybe_add( FID_SCREEN_MSG,     $status->screen_msg, $server, $server );
+    $resp .= maybe_add( FID_SCREEN_MSG,     $status->screen_msg, $server );
     $resp .= maybe_add( FID_PRINT_LINE,     $status->print_line, $server );
 
     $self->write_msg( $resp, undef, $server->{account}->{terminator}, $server->{account}->{encoding} );
@@ -1119,10 +1201,11 @@ sub handle_fee_paid {
 
 sub handle_item_information {
     my ( $self, $server ) = @_;
-    my $ils = $server->{ils};
+    my $account = $server->{account};
+    my $ils     = $server->{ils};
+    my $fields  = $self->{fields};
+    my $resp    = ITEM_INFO_RESP;
     my $trans_date;
-    my $fields = $self->{fields};
-    my $resp   = ITEM_INFO_RESP;
     my $item;
     my $i;
 
@@ -1147,11 +1230,16 @@ sub handle_item_information {
     } else {
 
         # Valid Item ID, send the good stuff
-        $resp .= $item->sip_circulation_status;
+        my $circulation_status = $item->sip_circulation_status;
+        $resp .= $circulation_status;
         $resp .= $item->sip_security_marker;
         $resp .= $item->sip_fee_type;
         $resp .= timestamp;
 
+        if ( $circulation_status eq '01' ) {
+            $resp .= maybe_add( FID_SCREEN_MSG, "Item is damaged", $server );
+        }
+
         $resp .= add_field( FID_ITEM_ID,  $item->id, $server );
         $resp .= add_field( FID_TITLE_ID, $item->title_id, $server );
 
@@ -1160,6 +1248,13 @@ sub handle_item_information {
         $resp .= maybe_add( FID_CURRENT_LOCN, $item->current_location, $server );
         $resp .= maybe_add( FID_ITEM_PROPS,   $item->sip_item_properties, $server );
 
+
+        if ( my $CR = $server->{account}->{cr_item_field} ) {
+                $resp .= maybe_add( FID_COLLECTION_CODE, $item->{$CR}, $server );
+        } else {
+          $resp .= maybe_add( FID_COLLECTION_CODE, $item->collection_code, $server );
+        }
+
         if ( ( $i = $item->fee ) != 0 ) {
             $resp .= add_field( FID_CURRENCY, $item->fee_currency, $server );
             $resp .= add_field( FID_FEE_AMT,  $i, $server );
@@ -1170,7 +1265,11 @@ sub handle_item_information {
             $resp .= add_field( FID_HOLD_QUEUE_LEN, $i, $server );
         }
         if ( $item->due_date ) {
-            $resp .= add_field( FID_DUE_DATE, timestamp( $item->due_date ), $server );
+            my $due_date =
+              $account->{format_due_date}
+              ? output_pref( { str => $item->due_date, as_due_date => 1 } )
+              : timestamp( $item->due_date );
+            $resp .= add_field( FID_DUE_DATE, $due_date, $server );
         }
         if ( ( $i = $item->recall_date ) != 0 ) {
             $resp .= add_field( FID_RECALL_DATE, timestamp($i), $server );
@@ -1179,8 +1278,11 @@ sub handle_item_information {
             $resp .= add_field( FID_HOLD_PICKUP_DATE, timestamp($i), $server );
         }
 
-        $resp .= maybe_add( FID_SCREEN_MSG, $item->screen_msg, $server, $server );
+        $resp .= maybe_add( FID_SCREEN_MSG, $item->screen_msg, $server );
         $resp .= maybe_add( FID_PRINT_LINE, $item->print_line, $server );
+
+        $resp .= $item->build_additional_item_fields_string( $server );
+        $resp .= $item->build_custom_field_string( $server );
     }
 
     $self->write_msg( $resp, undef, $server->{account}->{terminator}, $server->{account}->{encoding} );
@@ -1205,7 +1307,7 @@ sub handle_item_status_update {
     $item_props = $fields->{ (FID_ITEM_PROPS) };
 
     if ( !defined($item_id) ) {
-        syslog( "LOG_WARNING", "handle_item_status: received message without Item ID field" );
+        siplog( "LOG_WARNING", "handle_item_status: received message without Item ID field" );
     } else {
         $item = $ils->find_item($item_id);
     }
@@ -1230,7 +1332,7 @@ sub handle_item_status_update {
         $resp .= maybe_add( FID_ITEM_PROPS, $item->sip_item_properties, $server );
     }
 
-    $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server, $server );
+    $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server );
     $resp .= maybe_add( FID_PRINT_LINE, $status->print_line, $server );
 
     $self->write_msg( $resp, undef, $server->{account}->{terminator}, $server->{account}->{encoding} );
@@ -1250,7 +1352,9 @@ sub handle_patron_enable {
     $patron_id  = $fields->{ (FID_PATRON_ID) };
     $patron_pwd = $fields->{ (FID_PATRON_PWD) };
 
-    syslog( "LOG_DEBUG", "handle_patron_enable: patron_id: '%s', patron_pwd: '%s'", $patron_id, $patron_pwd );
+    Koha::Plugins->call('patron_barcode_transform', \$patron_id );
+
+    siplog( "LOG_DEBUG", "handle_patron_enable: patron_id: '%s', patron_pwd: '%s'", $patron_id, $patron_pwd );
 
     $patron = $ils->find_patron($patron_id);
 
@@ -1270,16 +1374,16 @@ sub handle_patron_enable {
             # Don't enable the patron if there was an invalid password
             $status = $patron->enable;
         }
-        $resp .= patron_status_string($patron);
+        $resp .= patron_status_string( $patron, $server );
         $resp .= $patron->language . timestamp();
 
         $resp .= add_field( FID_PATRON_ID,     $patron->id, $server );
-        $resp .= add_field( FID_PERSONAL_NAME, $patron->name( $server->{account}->{ae_field_template} ), $server );
+        $resp .= add_field( FID_PERSONAL_NAME, $patron->format( $server->{account}->{ae_field_template} ), $server );
         if ( defined($patron_pwd) ) {
             $resp .= add_field( FID_VALID_PATRON_PWD, sipbool( $patron->check_password($patron_pwd) ), $server );
         }
         $resp .= add_field( FID_VALID_PATRON, 'Y', $server );
-        $resp .= maybe_add( FID_SCREEN_MSG, $patron->screen_msg, $server, $server );
+        $resp .= maybe_add( FID_SCREEN_MSG, $patron->screen_msg, $server );
         $resp .= maybe_add( FID_PRINT_LINE, $patron->print_line, $server );
     }
 
@@ -1313,6 +1417,8 @@ sub handle_hold {
     $title_id    = $fields->{ (FID_TITLE_ID) } || '';
     $fee_ack     = $fields->{ (FID_FEE_ACK) } || 'N';
 
+    Koha::Plugins->call('patron_barcode_transform', \$patron_id );
+
     if ( $hold_mode eq '+' ) {
         $status = $ils->add_hold( $patron_id, $patron_pwd, $item_id, $title_id, $expiry_date, $pickup_locn, $hold_type, $fee_ack );
     } elsif ( $hold_mode eq '-' ) {
@@ -1320,7 +1426,7 @@ sub handle_hold {
     } elsif ( $hold_mode eq '*' ) {
         $status = $ils->alter_hold( $patron_id, $patron_pwd, $item_id, $title_id, $expiry_date, $pickup_locn, $hold_type, $fee_ack );
     } else {
-        syslog( "LOG_WARNING", "handle_hold: Unrecognized hold mode '%s' from terminal '%s'", $hold_mode, $server->{account}->{id} );
+        siplog( "LOG_WARNING", "handle_hold: Unrecognized hold mode '%s' from terminal '%s'", $hold_mode, $server->{account}->{id} );
         $status = $ils->Transaction::Hold;    # new?
         $status->screen_msg("System error. Please contact library staff.");
     }
@@ -1345,7 +1451,7 @@ sub handle_hold {
     }
 
     $resp .= add_field( FID_INST_ID, $ils->institution, $server );
-    $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server, $server );
+    $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server );
     $resp .= maybe_add( FID_PRINT_LINE, $status->print_line, $server );
 
     $self->write_msg( $resp, undef, $server->{account}->{terminator}, $server->{account}->{encoding} );
@@ -1368,7 +1474,7 @@ sub handle_renew {
     $ils->check_inst_id( $fields->{ (FID_INST_ID) }, "handle_renew" );
 
     if ( $no_block eq 'Y' ) {
-        syslog( "LOG_WARNING", "handle_renew: received 'no block' renewal from terminal '%s'", $server->{account}->{id} );
+        siplog( "LOG_WARNING", "handle_renew: received 'no block' renewal from terminal '%s'", $server->{account}->{id} );
     }
 
     $patron_id  = $fields->{ (FID_PATRON_ID) };
@@ -1378,6 +1484,8 @@ sub handle_renew {
     $item_props = $fields->{ (FID_ITEM_PROPS) };
     $fee_ack    = $fields->{ (FID_FEE_ACK) };
 
+    Koha::Plugins->call('patron_barcode_transform', \$patron_id );
+
     $status = $ils->renew( $patron_id, $patron_pwd, $item_id, $title_id, $no_block, $nb_due_date, $third_party, $item_props, $fee_ack );
 
     $patron = $status->patron;
@@ -1391,7 +1499,7 @@ sub handle_renew {
         } else {
             $resp .= 'U';
         }
-        $resp .= sipbool( $status->desensitize );
+        $resp .= sipbool( desensitize( { status => $status, patron => $patron, server => $server } ) );
         $resp .= timestamp;
         $resp .= add_field( FID_PATRON_ID, $patron->id, $server );
         $resp .= add_field( FID_ITEM_ID, $item->id, $server );
@@ -1430,7 +1538,7 @@ sub handle_renew {
     }
 
     $resp .= add_field( FID_INST_ID, $ils->institution, $server );
-    $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server, $server );
+    $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server );
     $resp .= maybe_add( FID_PRINT_LINE, $status->print_line, $server );
 
     $self->write_msg( $resp, undef, $server->{account}->{terminator}, $server->{account}->{encoding} );
@@ -1459,6 +1567,8 @@ sub handle_renew_all {
     $terminal_pwd = $fields->{ (FID_TERMINAL_PWD) };
     $fee_ack      = $fields->{ (FID_FEE_ACK) };
 
+    Koha::Plugins->call('patron_barcode_transform', \$patron_id );
+
     $status = $ils->renew_all( $patron_id, $patron_pwd, $fee_ack );
 
     $resp .= $status->ok ? '1' : '0';
@@ -1481,7 +1591,7 @@ sub handle_renew_all {
     $resp .= join( '', map( add_field( FID_RENEWED_ITEMS,   $_ ), @renewed ), $server );
     $resp .= join( '', map( add_field( FID_UNRENEWED_ITEMS, $_ ), @unrenewed ), $server );
 
-    $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server, $server );
+    $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server );
     $resp .= maybe_add( FID_PRINT_LINE, $status->print_line, $server );
 
     $self->write_msg( $resp, undef, $server->{account}->{terminator}, $server->{account}->{encoding} );
@@ -1517,13 +1627,17 @@ my @message_type_names = (
 
 sub send_acs_status {
     my ( $self, $server, $screen_msg, $print_line ) = @_;
+
     my $msg = ACS_STATUS;
     ($server) or die "send_acs_status error: no \$server argument received";
     my $account = $server->{account} or die "send_acs_status error: no 'account' in \$server object:\n" . Dumper($server);
     my $policy  = $server->{policy}  or die "send_acs_status error: no 'policy' in \$server object:\n" . Dumper($server);
     my $ils     = $server->{ils}     or die "send_acs_status error: no 'ils' in \$server object:\n" . Dumper($server);
+    my $sip_username = $server->{sip_username} or die "send_acs_status error: no 'sip_username' in \$server object:\n" . Dumper($server);
     my ( $online_status,    $checkin_ok, $checkout_ok, $ACS_renewal_policy );
     my ( $status_update_ok, $offline_ok, $timeout,     $retries );
+    my $sip_user = Koha::Patrons->find({ userid => $sip_username });
+    die "send_acs_status error: sip_username cannot be found in DB or DB cannot be reached" unless $sip_user;
 
     $online_status      = 'Y';
     $checkout_ok        = sipbool( $ils->checkout_ok );
@@ -1535,7 +1649,7 @@ sub send_acs_status {
     $retries            = sprintf( "%03d", $policy->{retries} );
 
     if ( length($retries) != 3 ) {
-        syslog( "LOG_ERR", "handle_acs_status: retries field wrong size: '%s'", $retries );
+        siplog( "LOG_ERR", "handle_acs_status: retries field wrong size: '%s'", $retries );
         $retries = '000';
     }
 
@@ -1548,7 +1662,7 @@ sub send_acs_status {
     } elsif ( $protocol_version == 2 ) {
         $msg .= '2.00';
     } else {
-        syslog( "LOG_ERR", 'Bad setting for $protocol_version, "%s" in send_acs_status', $protocol_version );
+        siplog( "LOG_ERR", 'Bad setting for $protocol_version, "%s" in send_acs_status', $protocol_version );
         $msg .= '1.00';
     }
 
@@ -1568,17 +1682,17 @@ sub send_acs_status {
             }
         }
         if ( length($supported_msgs) < 16 ) {
-            syslog( "LOG_ERR", 'send_acs_status: supported messages "%s" too short', $supported_msgs );
+            siplog( "LOG_ERR", 'send_acs_status: supported messages "%s" too short', $supported_msgs );
         }
         $msg .= add_field( FID_SUPPORTED_MSGS, $supported_msgs, $server );
     }
 
-    $msg .= maybe_add( FID_SCREEN_MSG, $screen_msg, $server, $server );
+    $msg .= maybe_add( FID_SCREEN_MSG, $screen_msg, $server );
 
     if (   defined( $account->{print_width} )
         && defined($print_line)
         && $account->{print_width} < length($print_line) ) {
-        syslog( "LOG_WARNING", "send_acs_status: print line '%s' too long.  Truncating", $print_line );
+        siplog( "LOG_WARNING", "send_acs_status: print line '%s' too long.  Truncating", $print_line );
         $print_line = substr( $print_line, 0, $account->{print_width} );
     }
 
@@ -1596,9 +1710,11 @@ sub send_acs_status {
 #
 sub patron_status_string {
     my $patron = shift;
+    my $server = shift;
+
     my $patron_status;
 
-    syslog( "LOG_DEBUG", "patron_status_string: %s charge_ok: %s", $patron->id, $patron->charge_ok );
+    siplog( "LOG_DEBUG", "patron_status_string: %s charge_ok: %s", $patron->id, $patron->charge_ok );
     $patron_status = sprintf(
         '%s%s%s%s%s%s%s%s%s%s%s%s%s%s',
         denied( $patron->charge_ok ),
@@ -1607,7 +1723,7 @@ sub patron_status_string {
         denied( $patron->hold_ok ),
         boolspace( $patron->card_lost ),
         boolspace( $patron->too_many_charged ),
-        boolspace( $patron->too_many_overdue ),
+        $server->{account}->{overdues_block_checkout} ? boolspace( $patron->too_many_overdue ) : q{ },
         boolspace( $patron->too_many_renewal ),
         boolspace( $patron->too_many_claim_return ),
         boolspace( $patron->too_many_lost ),
@@ -1632,6 +1748,38 @@ sub api_auth {
     return $status;
 }
 
+sub desensitize {
+    my ($params) = @_;
+
+    my $status      = $params->{status};
+    my $desensitize = $status->desensitize();
+
+    # If desenstize is already false, no need to do anything
+    return unless $desensitize;
+
+    my $patron = $params->{patron};
+    my $item   = $params->{item};
+    my $server = $params->{server};
+
+    my $patron_categories = $server->{account}->{inhouse_patron_categories} // q{};
+    my $item_types = $server->{account}->{inhouse_item_types} // q{};
+
+    # If no patron categories or item types are set for never desensitize, no need to do anything
+    return $desensitize unless $patron_categories || $item_types;
+
+    my $patron_category = $patron->ptype();
+    my @patron_categories = split( /,/, $patron_categories );
+    my $found_patron_category = grep( /^$patron_category$/, @patron_categories );
+    return 0 if $found_patron_category;
+
+    my $item_type = $item->itemtype;
+    my @item_types = split( /,/, $item_types );
+    my $found_item_type = grep( /^$item_type$/, @item_types );
+    return 0 if $found_item_type;
+
+    return 1;
+}
+
 1;
 __END__