]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/BadDebt.pm
Merge branch 'master' of git.evergreen-ils.org:Evergreen-DocBook into doc_consolidati...
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / BadDebt.pm
1 package OpenILS::WWW::BadDebt;
2 use strict;
3 use warnings;
4 use bytes;
5
6 use Apache2::Log;
7 use Apache2::Const -compile => qw(OK REDIRECT DECLINED NOT_FOUND :log);
8 use APR::Const    -compile => qw(:error SUCCESS);
9 use APR::Table;
10
11 use Apache2::RequestRec ();
12 use Apache2::RequestIO ();
13 use Apache2::RequestUtil;
14 use CGI;
15
16 use OpenSRF::EX qw(:try);
17 use OpenSRF::System;
18 use OpenSRF::AppSession;
19 use XML::LibXML;
20 use XML::LibXSLT;
21
22 use Encode;
23 use Unicode::Normalize;
24 use OpenILS::Utils::Fieldmapper;
25 use OpenSRF::Utils::Logger qw/$logger/;
26
27 use UNIVERSAL::require;
28
29 # set the bootstrap config when this module is loaded
30 my $bootstrap;
31
32 sub import {
33         my $self = shift;
34         $bootstrap = shift;
35 }
36
37
38 sub child_init {
39         OpenSRF::System->bootstrap_client( config_file => $bootstrap );
40 }
41
42 sub handler {
43         my $r = shift;
44         my $cgi = new CGI;
45     my $auth_ses = $cgi->cookie('ses') || $cgi->param('ses');
46
47         # find some IDs ...
48         my @xacts;
49
50     my $user = verify_login($auth_ses);
51     return 403 unless $user;
52
53         my $mark_bad = $cgi->param('action') eq 'unmark' ? 'f' : 't';
54         my $format = $cgi->param('format') || 'csv';
55
56         my $file = $cgi->param('idfile');
57         if ($file) {
58                 my $col = $cgi->param('idcolumn') || 0;
59                 my $csv = new Text::CSV;
60
61                 while (<$file>) {
62                         $csv->parse($_);
63                         my @data = $csv->fields;
64                         my $id = $data[$col];
65                         $id =~ s/\D+//o;
66                         next unless ($id);
67                         push @xacts, $id;
68                 }
69         }
70
71         if (!@xacts) { # try pathinfo
72                 my $path_rec = $cgi->path_info();
73                 if ($path_rec) {
74                         @xacts = map { $_ ? ($_) : () } split '/', $path_rec;
75                 }
76         }
77
78     return 404 unless @xacts;
79
80     my @lines;
81
82     my ($yr,$mon,$day) = (localtime())[5,4,3]; $yr += 1900;
83     my $date = sprintf('%d-%02d-%02d',$yr,$mon,$day);
84
85     my @header = ( '"Transaction ID"', '"Message"', '"Amount Owed"', '"Transaction Start Date"', '"User Barcode"' );
86
87         my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
88     my $actor = OpenSRF::AppSession->create('open-ils.actor');
89
90     $cstore->connect();
91     $cstore->request('open-ils.cstore.transaction.begin')->gather(1);
92     $cstore->request('open-ils.cstore.set_audit_info', $auth_ses, $user->id, $user->wsid)->gather(1);
93
94     for my $xact ( @xacts ) {
95         try {
96     
97             my $x = $cstore->request('open-ils.cstore.direct.money.billable_xact.retrieve' => $xact)->gather(1);
98             my $s = $cstore->request('open-ils.cstore.direct.money.billable_xact_summary.retrieve' => $xact)->gather(1);
99             my $u = $cstore->request('open-ils.cstore.direct.actor.usr.retrieve' => $s->usr)->gather(1);
100             my $c = $cstore->request('open-ils.cstore.direct.actor.card.retrieve' => $u->card)->gather(1);
101             my $w;
102
103             if ($s->xact_type eq 'circulation') {
104                 $w = $cstore->request('open-ils.cstore.direct.action.circulation.retrieve' => $xact)->gather(1)->circ_lib;
105             } elsif ($s->xact_type eq 'grocery') {
106                 $w = $cstore->request('open-ils.cstore.direct.money.grocery.retrieve' => $xact)->gather(1)->billing_location;
107             } elsif ($s->xact_type eq 'reservation') {
108                 $w = $cstore->request('open-ils.cstore.direct.booking.reservation.retrieve' => $xact)->gather(1)->pickup_lib;
109             } else {
110                 die;
111             }
112     
113             my $failures = $actor->request('open-ils.actor.user.perm.check', $auth_ses, $user->id, $w, ['MARK_BAD_DEBT'])->gather(1);
114     
115             if (@$failures) {
116                 push @lines, [ $xact, '"Permission Failure"', '""', '""', '""' ];
117             } else {
118                 $x->unrecovered($mark_bad);
119                 my $result = $cstore->request('open-ils.cstore.direct.money.billable_xact.update' => $x)->gather(1);
120                 if ($result != $x->id) {
121                     push @lines, [ $xact, '"Update Failure"', '""', '""', '""' ];
122                 } else {
123                     my $amount = $s->balance_owed;
124                     my $start = $s->xact_start;
125                     my $barcode = $c->barcode;
126
127                     if ( $mark_bad eq 't' ) {
128                         push @lines, [ $xact, '"Marked Bad Debt"', $amount, "\"$start\"", "\"$barcode\"" ];
129                     } else {
130                         push @lines, [ $xact, '"Unmarked Bad Debt"', $amount, "\"$start\"", "\"$barcode\"" ];
131                     }
132                 }
133             }
134         } otherwise {
135             push @lines, [ $xact, '"Update Failure"', '""', '""', '""' ];
136         };
137     }
138
139     $cstore->request('open-ils.cstore.transaction.commit')->gather(1);
140     $cstore->disconnect();
141
142     if ($format eq 'csv') {
143         $r->headers_out->set("Content-Disposition" => "inline; filename=bad_debt_$date.csv");
144             $r->content_type('application/octet-stream');
145
146         $r->print( join(',', @header) . "\n" );
147         $r->print( join(',', @$_    ) . "\n" ) for (@lines);
148
149     } elsif ($format eq 'json') {
150
151             $r->content_type('application/json');
152
153         $r->print( '[' );
154
155         my $first = 1;
156         for my $line ( @lines ) {
157             $r->print( ',' ) if $first;
158             $first = 0;
159
160             $r->print( '{' );
161             for my $field ( 0 .. 4 ) {
162                 $r->print( "$header[$field] : $$line[$field]" );
163                 $r->print( ',' ) if ($field < 4);
164             }
165             $r->print( '}' );
166         }
167
168         $r->print( ']' );
169     }
170
171         return Apache2::Const::OK;
172
173 }
174
175 sub verify_login {
176         my $auth_token = shift;
177         return undef unless $auth_token;
178
179         my $user = OpenSRF::AppSession
180                 ->create("open-ils.auth")
181                 ->request( "open-ils.auth.session.retrieve", $auth_token )
182                 ->gather(1);
183
184         if (ref($user) eq 'HASH' && $user->{ilsevent} == 1001) {
185                 return undef;
186         }
187
188         return $user if ref($user);
189         return undef;
190 }
191
192 sub show_template {
193         my $r = shift;
194
195         $r->content_type('text/html');
196         $r->print(<<HTML);
197
198 <html>
199         <head>
200                 <title>Record Export</title>
201         </head>
202         <body>
203                 <form method="POST" enctype="multipart/form-data">
204                         Use field number <input type="text" size="2" maxlength="2" name="idcolumn" value="0"/> (starting from 0)
205                         from CSV file <input type="file" name="idfile"/>
206                         <input type="submit" value="Mark Transactions Unrecoverable"/>
207                 </form>
208         </body>
209 </html>
210
211 HTML
212
213         return Apache2::Const::OK;
214 }
215
216 1;