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