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