c94a2199a07b4e8f9f5b9902eab6220d7e395d3e
[koha.git] / C4 / Creators / Profile.pm
1 package C4::Creators::Profile;
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 use C4::Creators::Lib 1.000000 qw(get_unit_values);
11
12 BEGIN {
13     use version; our $VERSION = qv('3.07.00.049');
14 }
15
16 sub _check_params {
17     my $given_params = {};
18     my $exit_code = 0;
19     my @valid_profile_params = (
20         'printer_name',
21         'template_id',
22         'paper_bin',
23         'offset_horz',
24         'offset_vert',
25         'creep_horz',
26         'creep_vert',
27         'units',
28         'creator',
29     );
30     if (scalar(@_) >1) {
31         $given_params = {@_};
32         foreach my $key (keys %{$given_params}) {
33             if (!(grep m/$key/, @valid_profile_params)) {
34                 warn sprintf('Unrecognized parameter type of "%s".', $key);
35                 $exit_code = 1;
36             }
37         }
38     }
39     else {
40         if (!(grep m/$_/, @valid_profile_params)) {
41             warn sprintf('Unrecognized parameter type of "%s".', $_);
42             $exit_code = 1;
43         }
44     }
45     return $exit_code;
46 }
47
48 sub _conv_points {
49     my $self = shift;
50     my @unit_value = grep {$_->{'type'} eq $self->{units}} @{get_unit_values()};
51     $self->{offset_horz}        = $self->{offset_horz} * $unit_value[0]->{'value'};
52     $self->{offset_vert}        = $self->{offset_vert} * $unit_value[0]->{'value'};
53     $self->{creep_horz}         = $self->{creep_horz} * $unit_value[0]->{'value'};
54     $self->{creep_vert}         = $self->{creep_vert} * $unit_value[0]->{'value'};
55     return $self;
56 }
57
58 sub new {
59     my $invocant = shift;
60     if (_check_params(@_) eq 1) {
61         return -1;
62     }
63     my $type = ref($invocant) || $invocant;
64     my $self = {
65         printer_name    => 'Default Printer',
66         template_id     => '',
67         paper_bin       => 'Tray 1',
68         offset_horz     => 0,
69         offset_vert     => 0,
70         creep_horz      => 0,
71         creep_vert      => 0,
72         units           => 'POINT',
73         @_,
74     };
75     bless ($self, $type);
76     return $self;
77 }
78
79 sub retrieve {
80     my $invocant = shift;
81     my %opts = @_;
82     my $type = ref($invocant) || $invocant;
83     my $query = "SELECT * FROM printers_profile WHERE profile_id = ? AND creator = ?";
84     my $sth = C4::Context->dbh->prepare($query);
85     $sth->execute($opts{'profile_id'}, $opts{'creator'});
86     if ($sth->err) {
87         warn sprintf('Database returned the following error: %s', $sth->errstr);
88         return -1;
89     }
90     my $self = $sth->fetchrow_hashref;
91     $self = _conv_points($self) if ($opts{convert} && $opts{convert} == 1);
92     bless ($self, $type);
93     return $self;
94 }
95
96 sub delete {
97     my $self = {};
98     my %opts = ();
99     my $call_type = '';
100     my @params = ();
101     if (ref($_[0])) {
102         $self = shift;  # check to see if this is a method call
103         $call_type = 'C4::'. $self->{'creator'} .'::Profile->delete';
104         push @params, $self->{'profile_id'}, $self->{'creator'};
105     }
106     else {
107         my $class = shift; #XXX: is this too hackish?
108         %opts = @_;
109         $call_type = $class . "::delete";
110         push @params, $opts{'profile_id'}, $opts{'creator'};
111     }
112     if (scalar(@params) < 2) {   # If there is no profile id or creator type then we cannot delete it
113         warn sprintf('%s : Cannot delete profile as the profile id is invalid or non-existant.', $call_type) if !$params[0];
114         warn sprintf('%s : Cannot delete profile as the creator type is invalid or non-existant.', $call_type) if !$params[1];
115         return -1;
116     }
117     my $query = "DELETE FROM printers_profile WHERE profile_id = ? AND creator = ?";
118     my $sth = C4::Context->dbh->prepare($query);
119 #    $sth->{'TraceLevel'} = 3;
120     $sth->execute(@params);
121     if ($sth->err) {
122         warn sprintf('Database returned the following error on attempted DELETE: %s', $sth->errstr);
123         return -1;
124     }
125     return 0;
126 }
127
128 sub save {
129     my $self = shift;
130     if ($self->{'profile_id'}) {        # if we have an profile_id, the record exists and needs UPDATE
131         my @params;
132         my $query = "UPDATE printers_profile SET ";
133         foreach my $key (keys %{$self}) {
134             next if ($key eq 'profile_id') || ($key eq 'creator');
135             push (@params, $self->{$key});
136             $query .= "$key=?, ";
137         }
138         $query = substr($query, 0, (length($query)-2));
139         push (@params, $self->{'profile_id'}, $self->{'creator'});
140         $query .= " WHERE profile_id=? AND creator=?;";
141         my $sth = C4::Context->dbh->prepare($query);
142 #        $sth->{'TraceLevel'} = 3;
143         $sth->execute(@params);
144         if ($sth->err) {
145             warn sprintf('Database returned the following error on attempted UPDATE: %s', $sth->errstr);
146             return -1;
147         }
148         return $self->{'profile_id'};
149     }
150     else {                      # otherwise create a new record
151         my @params;
152         my $query = "INSERT INTO printers_profile (";
153         foreach my $key (keys %{$self}) {
154             push (@params, $self->{$key});
155             $query .= "$key, ";
156         }
157         $query = substr($query, 0, (length($query)-2));
158         $query .= ") VALUES (";
159         for (my $i=1; $i<=(scalar keys %$self); $i++) {
160             $query .= "?,";
161         }
162         $query = substr($query, 0, (length($query)-1));
163         $query .= ");";
164         my $sth = C4::Context->dbh->prepare($query);
165         $sth->execute(@params);
166         if ($sth->err) {
167             warn sprintf('Database returned the following error on attempted INSERT: %s', $sth->errstr);
168             return -1;
169         }
170         my $sth1 = C4::Context->dbh->prepare("SELECT MAX(profile_id) FROM printers_profile;");
171         $sth1->execute();
172         my $tmpl_id = $sth1->fetchrow_array;
173         return $tmpl_id;
174     }
175 }
176
177 sub get_attr {
178     my $self = shift;
179     if (_check_params(@_) eq 1) {
180         return -1;
181     }
182     my ($attr) = @_;
183     if (exists($self->{$attr})) {
184         return $self->{$attr};
185     }
186     else {
187         warn sprintf('%s is currently undefined.', $attr);
188         return -1;
189     }
190 }
191
192 sub set_attr {
193     my $self = shift;
194     if (_check_params(@_) eq 1) {
195         return -1;
196     }
197     my %attrs = @_;
198     foreach my $attrib (keys(%attrs)) {
199         $self->{$attrib} = $attrs{$attrib};
200     };
201     return 0;
202 }
203
204 1;
205 __END__
206
207 =head1 NAME
208
209 C4::Labels::Profile - A class for creating and manipulating profile objects in Koha
210
211 =head1 ABSTRACT
212
213 This module provides methods for creating, retrieving, and otherwise manipulating label profile objects used by Koha to create and export labels.
214
215 =head1 METHODS
216
217 =head2 new()
218
219     Invoking the I<new> method constructs a new profile object containing the default values for a template.
220     The following parameters are optionally accepted as key => value pairs:
221
222         C<printer_name>         The name of the printer to which this profile applies.
223         C<template_id>          The template to which this profile may be applied. NOTE: There may be multiple profiles which may be applied to the same template.
224         C<paper_bin>            The paper bin of the above printer to which this profile applies. NOTE: printer name, template id, and paper bin must form a unique combination.
225         C<offset_horz>          Amount of compensation for horizontal offset (position of text on a single label). This amount is measured in the units supplied by the units parameter in this profile.
226         C<offset_vert>          Amount of compensation for vertical offset.
227         C<creep_horz>           Amount of compensation for horizontal creep (tendency of text to 'creep' off of the labels over the span of the entire page).
228         C<creep_vert>           Amount of compensation for vertical creep.
229         C<units>                The units of measure used for this template. These B<must> match the measures you supply above or
230                                 bad things will happen to your document. NOTE: The only supported units at present are:
231
232 =over 9
233
234 =item .
235 POINT   = Postscript Points (This is the base unit in the Koha label creator.)
236
237 =item .
238 AGATE   = Adobe Agates (5.1428571 points per)
239
240 =item .
241 INCH    = US Inches (72 points per)
242
243 =item .
244 MM      = SI Millimeters (2.83464567 points per)
245
246 =item .
247 CM      = SI Centimeters (28.3464567 points per)
248
249 =back
250
251     example:
252         C<my $profile = C4::Labels::Profile->new(); # Creates and returns a new profile object>
253
254         C<my $profile = C4::Labels::Profile->new(template_id => 1, paper_bin => 'Bypass Tray', offset_horz => 0.02, units => 'POINT'); # Creates and returns a new profile object using
255             the supplied values to override the defaults>
256
257     B<NOTE:> This profile is I<not> written to the database until save() is invoked. You have been warned!
258
259 =head2 retrieve(profile_id => $profile_id, convert => 1)
260
261     Invoking the I<retrieve> method constructs a new profile object containing the current values for profile_id. The method returns a new object upon success and 1 upon failure.
262     Errors are logged to the Apache log. One further option maybe accessed. See the examples below for further description.
263
264     examples:
265
266         C<my $profile = C4::Labels::Profile->retrieve(profile_id => 1); # Retrieves profile record 1 and returns an object containing the record>
267
268         C<my $profile = C4::Labels::Profile->retrieve(profile_id => 1, convert => 1); # Retrieves profile record 1, converts the units to points and returns an object containing the record>
269
270 =head2 delete()
271
272     Invoking the delete method attempts to delete the profile from the database. The method returns -1 upon failure. Errors are logged to the Apache log.
273     NOTE: This method may also be called as a function and passed a key/value pair simply deleteing that profile from the database. See the example below.
274
275     examples:
276         C<my $exitstat = $profile->delete(); # to delete the record behind the $profile object>
277         C<my $exitstat = C4::Labels::Profile::delete(profile_id => 1); # to delete profile record 1>
278
279 =head2 save()
280
281     Invoking the I<save> method attempts to insert the profile into the database if the profile is new and update the existing profile record if the profile exists. The method returns
282     the new record profile_id upon success and -1 upon failure (This avoids conflicting with a record profile_id of 1). Errors are logged to the Apache log.
283
284     example:
285         C<my $exitstat = $profile->save(); # to save the record behind the $profile object>
286
287 =head2 get_attr($attribute)
288
289     Invoking the I<get_attr> method will return the value of the requested attribute or -1 on errors.
290
291     example:
292         C<my $value = $profile->get_attr($attribute);>
293
294 =head2 set_attr(attribute => value, attribute_2 => value)
295
296     Invoking the I<set_attr> method will set the value of the supplied attributes to the supplied values. The method accepts key/value pairs separated by commas.
297
298     example:
299         $profile->set_attr(attribute => value);
300
301 =head1 AUTHOR
302
303 Chris Nighswonger <cnighswonger AT foundations DOT edu>
304
305 =head1 COPYRIGHT
306
307 Copyright 2009 Foundations Bible College.
308
309 =head1 LICENSE
310
311 This file is part of Koha.
312
313 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
314 Foundation; either version 2 of the License, or (at your option) any later version.
315
316 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,
317 Fifth Floor, Boston, MA 02110-1301 USA.
318
319 =head1 DISCLAIMER OF WARRANTY
320
321 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
322 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
323
324 =cut
325
326 #=head1
327 #drawbox( ($left_margin), ($top_margin), ($page_width-(2*$left_margin)), ($page_height-(2*$top_margin)) ); # FIXME: Breakout code to print alignment page for printer profile setup
328 #
329 #=head2 draw_boundaries
330 #
331 # sub draw_boundaries ($llx_spine, $llx_circ1, $llx_circ2,
332 #                $lly, $spine_width, $label_height, $circ_width)
333 #
334 #This sub draws boundary lines where the label outlines are, to aid in printer testing, and debugging.
335 #
336 #=cut
337 #
338 ##       FIXME: Template use for profile adjustment...
339 ##sub draw_boundaries {
340 ##
341 ##    my (
342 ##        $llx_spine, $llx_circ1,  $llx_circ2, $lly,
343 ##        $spine_width, $label_height, $circ_width
344 ##    ) = @_;
345 ##
346 ##    my $lly_initial = ( ( 792 - 36 ) - 90 );
347 ##    $lly            = $lly_initial; # FIXME - why are we ignoring the y_pos parameter by redefining it?
348 ##    my $i             = 1;
349 ##
350 ##    for ( $i = 1 ; $i <= 8 ; $i++ ) {
351 ##
352 ##        _draw_box( $llx_spine, $lly, ($spine_width), ($label_height) );
353 ##
354 ##   #warn "OLD BOXES  x=$llx_spine, y=$lly, w=$spine_width, h=$label_height";
355 ##        _draw_box( $llx_circ1, $lly, ($circ_width), ($label_height) );
356 ##        _draw_box( $llx_circ2, $lly, ($circ_width), ($label_height) );
357 ##
358 ##        $lly = ( $lly - $label_height );
359 ##
360 ##    }
361 ##}
362 #
363 #
364 #
365 #=cut