Bug 4450 Use more consistent error returns in C4/Creators/*
[koha_gimpoz] / C4 / Creators / Batch.pm
1 package C4::Creators::Batch;
2
3 use strict;
4 use warnings;
5
6 use autouse 'Data::Dumper' => qw(Dumper);
7
8 use C4::Context;
9 use C4::Debug;
10
11 BEGIN {
12     use version; our $VERSION = qv('1.0.0_1');
13 }
14
15 sub _check_params {
16     my $given_params = {};
17     my $exit_code = 0;
18     my @valid_template_params = (
19         'label_id',
20         'batch_id',
21         'item_number',
22         'card_number',
23         'branch_code',
24         'creator',
25     );
26     if (scalar(@_) >1) {
27         $given_params = {@_};
28         foreach my $key (keys %{$given_params}) {
29             if (!(grep m/$key/, @valid_template_params)) {
30                 warn sprintf('Unrecognized parameter type of "%s".', $key);
31                 $exit_code = 1;
32             }
33         }
34     }
35     else {
36         if (!(grep m/$_/, @valid_template_params)) {
37             warn sprintf('Unrecognized parameter type of %s', $_);
38             $exit_code = 1;
39         }
40     }
41     return $exit_code;
42 }
43
44 sub new {
45     my ($invocant) = shift;
46     my $type = ref($invocant) || $invocant;
47     my $self = {
48         batch_id        => 0,
49         items           => [],
50         branch_code     => 'NB',
51         batch_stat      => 0,   # False if any data has changed and the db has not been updated
52         @_,
53     };
54     my $sth = C4::Context->dbh->prepare("SELECT MAX(batch_id) FROM creator_batches;");
55     $sth->execute();
56     my $batch_id = $sth->fetchrow_array;
57     $self->{'batch_id'} = ++$batch_id unless $self->{'batch_id'} != 0;      # this allows batch_id to be passed in for individual label printing
58     bless ($self, $type);
59     return $self;
60 }
61
62 sub add_item {
63     my $self = shift;
64     my $number = shift;
65     ref($self) =~ m/C4::(.+)::.+$/;
66     my $number_type = ($1 eq 'Patroncards' ? 'borrower_number' : 'item_number');
67     my $query = "INSERT INTO creator_batches (batch_id, $number_type, branch_code, creator) VALUES (?,?,?,?);";
68     my $sth = C4::Context->dbh->prepare($query);
69 #    $sth->{'TraceLevel'} = 3;
70     $sth->execute($self->{'batch_id'}, $number, $self->{'branch_code'}, $1);
71     if ($sth->err) {
72         warn sprintf('Database returned the following error on attempted INSERT: %s', $sth->errstr);
73         return -1;
74     }
75     $query = "SELECT max(label_id) FROM creator_batches WHERE batch_id=? AND $number_type=? AND branch_code=?;";
76     my $sth1 = C4::Context->dbh->prepare($query);
77     $sth1->execute($self->{'batch_id'}, $number, $self->{'branch_code'});
78     my $label_id = $sth1->fetchrow_array;
79     push (@{$self->{'items'}}, {$number_type => $number, label_id => $label_id});
80     $self->{'batch_stat'} = 1;
81     return 0;
82 }
83
84 sub get_attr {
85     my $self = shift;
86     return $self->{$_[0]};
87 }
88
89 sub remove_item {
90     my $self = shift;
91     my $label_id = shift;
92     my $query = "DELETE FROM creator_batches WHERE label_id=? AND batch_id=?;";
93     my $sth = C4::Context->dbh->prepare($query);
94 #    $sth->{'TraceLevel'} = 3;
95     $sth->execute($label_id, $self->{'batch_id'});
96     if ($sth->err) {
97         warn sprintf('Database returned the following error on attempted DELETE: %s', $sth->errstr);
98         return -1;
99     }
100     @{$self->{'items'}} = grep{$_->{'label_id'} != $label_id} @{$self->{'items'}};
101     $self->{'batch_stat'} = 1;
102     return 0;
103 }
104
105 # FIXME: This method is effectively useless the way the current add_item method is written. Ideally, the items should be added to the object
106 #       and then the save method called. This does not work well in practice due to the inability to pass objects accross cgi script calls.
107 #       I'm leaving it here because it should be here and for consistency's sake and once memcached support is fully implimented this should be as well. -cnighswonger
108 #
109 #=head2 $batch->save()
110 #
111 #    Invoking the I<save> method attempts to insert the batch into the database. The method returns
112 #    the new record batch_id upon success and -1 upon failure (This avoids conflicting with a record
113 #    batch_id of 1). Errors are logged to the Apache log.
114 #
115 #    example:
116 #        my $exitstat = $batch->save(); # to save the record behind the $batch object
117 #
118 #=cut
119 #
120 #sub save {
121 #    my $self = shift;
122 #    foreach my $item_number (@{$self->{'items'}}) {
123 #        my $query = "INSERT INTO creator_batches (batch_id, item_number, branch_code) VALUES (?,?,?);";
124 #        my $sth1 = C4::Context->dbh->prepare($query);
125 #        $sth1->execute($self->{'batch_id'}, $item_number->{'item_number'}, $self->{'branch_code'});
126 #        if ($sth1->err) {
127 #            warn sprintf('Database returned the following error on attempted INSERT: %s', $sth1->errstr);
128 #            return -1;
129 #        }
130 #        $self->{'batch_stat'} = 1;
131 #        return $self->{'batch_id'};
132 #    }
133 #}
134
135 sub retrieve {
136     my $invocant = shift;
137     my %opts = @_;
138     my $type = ref($invocant) || $invocant;
139     $type =~ m/C4::(.+)::.+$/;
140     my $number_type = ($1 eq 'Patroncards' ? 'borrower_number' : 'item_number');
141     my $record_flag = 0;
142     my $query = "SELECT * FROM creator_batches WHERE batch_id = ? ORDER BY label_id";
143     my $sth = C4::Context->dbh->prepare($query);
144 #    $sth->{'TraceLevel'} = 3;
145     $sth->execute($opts{'batch_id'});
146     my $self = {
147         batch_id        => $opts{'batch_id'},
148         items           => [],
149     };
150     while (my $record = $sth->fetchrow_hashref) {
151         $self->{'branch_code'} = $record->{'branch_code'};
152         push (@{$self->{'items'}}, {$number_type => $record->{$number_type}, label_id => $record->{'label_id'}});
153         $record_flag = 1;       # true if one or more rows were retrieved
154     }
155     if ($record_flag == 0) {
156         return; # no such record exists return undef
157     }
158     if ($sth->err) {
159         warn sprintf('Database returned the following error on attempted SELECT: %s', $sth->errstr);
160         return;
161     }
162     $self->{'batch_stat'} = 1;
163     bless ($self, $type);
164     return $self;
165 }
166
167 sub delete {
168     my $self = {};
169     my %opts = ();
170     my $call_type = '';
171     my @query_params = ();
172     if (ref($_[0])) {
173         $self = shift;  # check to see if this is a method call
174         $call_type = 'C4::Labels::Batch->delete'; # seems hackish
175         @query_params = ($self->{'batch_id'}, $self->{'branch_code'});
176     }
177     else {
178         shift @_;
179         %opts = @_;
180         $call_type = 'C4::Labels::Batch::delete';
181         @query_params = ($opts{'batch_id'}, $opts{'branch_code'});
182     }
183     if ($query_params[0] eq '') {   # If there is no template id then we cannot delete it
184         warn sprintf('%s : Cannot delete batch as the batch id is invalid or non-existent.', $call_type);
185         return -1;
186     }
187     my $query = "DELETE FROM creator_batches WHERE batch_id = ? AND branch_code =?";
188     my $sth = C4::Context->dbh->prepare($query);
189 #    $sth->{'TraceLevel'} = 3;
190     $sth->execute(@query_params);
191     if ($sth->err) {
192         warn sprintf('%s : Database returned the following error on attempted INSERT: %s', $call_type, $sth->errstr);
193         return -1;
194     }
195     return 0;
196 }
197
198 sub remove_duplicates {
199     my $self = shift;
200     my %seen=();
201     my $query = "DELETE FROM creator_batches WHERE label_id = ?;"; # ORDER BY timestamp ASC LIMIT ?;";
202     my $sth = C4::Context->dbh->prepare($query);
203     my @duplicate_items = grep{$seen{$_->{'item_number'}}++} @{$self->{'items'}};
204     foreach my $item (@duplicate_items) {
205         $sth->execute($item->{'label_id'});
206         if ($sth->err) {
207             warn sprintf('Database returned the following error on attempted DELETE for label_id %s: %s', $item->{'label_id'}, $sth->errstr);
208             return -1;
209         }
210         $sth->finish(); # Per DBI.pm docs: "If execute() is called on a statement handle that's still active ($sth->{Active} is true) then it should effectively call finish() to tidy up the previous execution results before starting this new execution."
211         @{$self->{'items'}} = grep{$_->{'label_id'} != $item->{'label_id'}} @{$self->{'items'}};  # the correct label/item must be removed from the current batch object as well; this should be done *after* each sql DELETE in case the DELETE fails
212     }
213     return scalar(@duplicate_items);
214 }
215
216 1;
217 __END__
218
219 =head1 NAME
220
221 C4::Labels::Batch - A class for creating and manipulating batch objects in Koha
222
223 =head1 ABSTRACT
224
225 This module provides methods for creating, and otherwise manipulating batch objects used by Koha to create and export labels.
226
227 =head1 METHODS
228
229 =head2 new()
230
231     Invoking the I<new> method constructs a new batch object with no items. It is possible to pre-populate the batch with items and a branch code by passing them
232     as in the second example below.
233
234     B<NOTE:> The items list must be an arrayref pointing to an array of hashes containing a key/data pair after this fashion: {item_number => item_number}. The order of
235     the array elements determines the order of the items in the batch.
236
237     example:
238         C<my $batch = C4::Labels::Batch->new(); # Creates and returns a new batch object>
239
240         C<my $batch = C4::Labels::Batch->new(items => $arrayref, branch_code => branch_code) #    Creates and returns a new batch object containing the items passed in
241             with the branch code passed in.>
242
243     B<NOTE:> This batch is I<not> written to the database until C<$batch->save()> is invoked. You have been warned!
244
245 =head2 $batch->add_item(item_number => $item_number, branch_code => $branch_code)
246
247     Invoking the I<add_item> method will add the supplied item to the batch object.
248
249     example:
250         $batch->add_item(item_number => $item_number, branch_code => $branch_code);
251
252 =head2 $batch->get_attr($attribute)
253
254     Invoking the I<get_attr> method will return the requested attribute.
255
256     example:
257         my @items = $batch->get_attr('items');
258
259 =head2 $batch->remove_item($item_number)
260
261     Invoking the I<remove_item> method will remove the supplied item number from the batch object.
262
263     example:
264         $batch->remove_item($item_number);
265
266 =head2 C4::Labels::Batch->retrieve(batch_id => $batch_id)
267
268     Invoking the I<retrieve> method constructs a new batch object containing the current values for batch_id. The method returns a new object upon success and undefined upon failure.
269     Errors are logged to the Apache log.
270
271     examples:
272
273         my $batch = C4::Labels::Batch->(batch_id => 1); # Retrieves batch 1 and returns an object containing the record
274
275 =head2 delete()
276
277     Invoking the delete method attempts to delete the template from the database. The method returns -1 upon failure. Errors are logged to the Apache log.
278     NOTE: This method may also be called as a function and passed a key/value pair simply deleteing that batch from the database. See the example below.
279
280     examples:
281         my $exitstat = $batch->delete(); # to delete the record behind the $batch object
282         my $exitstat = C4::Labels::Batch->delete(batch_id => 1); # to delete batch 1
283
284 =head2 remove_duplicates()
285
286     Invoking the remove_duplicates method attempts to remove duplicate items in the batch from the database. The method returns the count of duplicate records removed upon
287     success and -1 upon failure. Errors are logged to the Apache log.
288     NOTE: This method may also be called as a function and passed a key/value pair removing duplicates in the batch passed in. See the example below.
289
290     examples:
291         my $remove_count = $batch->remove_duplicates(); # to remove duplicates the record behind the $batch object
292         my $remove_count = C4::Labels::Batch->remove_duplicates(batch_id => 1); # to remove duplicates in batch 1
293
294 =head1 AUTHOR
295
296 Chris Nighswonger <cnighswonger AT foundations DOT edu>
297
298 =head1 COPYRIGHT
299
300 Copyright 2009 Foundations Bible College.
301
302 =head1 LICENSE
303
304 This file is part of Koha.
305
306 Koha is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software
307 Foundation; either version 2 of the License, or (at your option) any later version.
308
309 You should have received a copy of the GNU General Public License along with Koha; if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
310 Fifth Floor, Boston, MA 02110-1301 USA.
311
312 =head1 DISCLAIMER OF WARRANTY
313
314 Koha is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
315 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
316
317 =cut
318