Bug 7295: More granular permissions for baskets
[koha.git] / serials / subscription-add.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18 use strict;
19 use warnings;
20
21 use CGI;
22 use Date::Calc qw(Today Day_of_Year Week_of_Year Add_Delta_Days Add_Delta_YM);
23 use C4::Koha;
24 use C4::Biblio;
25 use C4::Auth;
26 use C4::Dates qw/format_date format_date_in_iso/;
27 use C4::Acquisition;
28 use C4::Output;
29 use C4::Context;
30 use C4::Branch; # GetBranches
31 use C4::Serials;
32 use C4::Serials::Frequency;
33 use C4::Serials::Numberpattern;
34 use C4::Letters;
35 use Carp;
36
37 #use Smart::Comments;
38
39 our $query = CGI->new;
40 my $op = $query->param('op') || '';
41 my $dbh = C4::Context->dbh;
42 my $sub_length;
43
44 my @budgets;
45
46 # Permission needed if it is a modification : edit_subscription
47 # Permission needed otherwise (nothing or dup) : create_subscription
48 my $permission = ($op eq "modify") ? "edit_subscription" : "create_subscription";
49
50 my ($template, $loggedinuser, $cookie)
51 = get_template_and_user({template_name => "serials/subscription-add.tt",
52                                 query => $query,
53                                 type => "intranet",
54                                 authnotrequired => 0,
55                                 flagsrequired => {serials => $permission},
56                                 debug => 1,
57                                 });
58
59
60
61 my $sub_on;
62 my @subscription_types = (qw(issues weeks months));
63 my @sub_type_data;
64
65 my $subs;
66 our $firstissuedate;
67
68 if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
69
70     my $subscriptionid = $query->param('subscriptionid');
71     $subs = GetSubscription($subscriptionid);
72
73     ## FIXME : Check rights to edit if mod. Could/Should display an error message.
74     if ($subs->{'cannotedit'} && $op eq 'modify'){
75       carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
76       print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
77     }
78     $firstissuedate = $subs->{firstacquidate} || '';  # in iso format.
79     for (qw(startdate firstacquidate histstartdate enddate histenddate)) {
80         next unless defined $subs->{$_};
81         # TODO : Handle date formats properly.
82          if ($subs->{$_} eq '0000-00-00') {
83             $subs->{$_} = ''
84         } else {
85             $subs->{$_} = $subs->{$_};
86         }
87           }
88       if (!defined $subs->{letter}) {
89           $subs->{letter}= q{};
90       }
91     letter_loop($subs->{'letter'}, $template);
92     my $nextexpected = GetNextExpected($subscriptionid);
93     $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
94     $subs->{nextacquidate} = $nextexpected->{planneddate}  if($op eq 'modify');
95     unless($op eq 'modsubscription') {
96         foreach my $length_unit (qw(numberlength weeklength monthlength)) {
97             if ($subs->{$length_unit}) {
98                 $sub_length=$subs->{$length_unit};
99                 $sub_on=$length_unit;
100                 last;
101             }
102         }
103
104         $template->param( %{$subs} );
105         $template->param(
106                     $op => 1,
107                     "subtype_$sub_on" => 1,
108                     sublength =>$sub_length,
109                     history => ($op eq 'modify'),
110                     firstacquiyear => substr($firstissuedate,0,4),
111                     );
112
113         if($op eq 'modify') {
114             my ($serials_number) = GetSerials($subscriptionid);
115             if($serials_number > 1) {
116                 $template->param(more_than_one_serial => 1);
117             }
118         }
119     }
120
121     if ( $op eq 'dup' ) {
122         my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
123         my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
124         $template->param( dont_export_field_loop => \@fields_id );
125     }
126 }
127
128 my $userenv = C4::Context->userenv;
129 my $onlymine =
130      C4::Context->preference('IndependentBranches')
131   && $userenv
132   && $userenv->{flags} % 2 != 1
133   && (
134     not C4::Auth::haspermission( $userenv->{id}, { serials => 'superserials' } )
135   )
136   && $userenv->{branch};
137
138 my $branches = GetBranches($onlymine);
139 my $branchloop;
140 for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %{$branches}) {
141     my $selected = 0;
142     $selected = 1 if (defined($subs) && $thisbranch eq $subs->{'branchcode'});
143     push @{$branchloop}, {
144         value => $thisbranch,
145         selected => $selected,
146         branchname => $branches->{$thisbranch}->{'branchname'},
147     };
148 }
149
150 my $locations_loop = GetAuthorisedValues("LOC",$subs->{'location'});
151
152 $template->param(branchloop => $branchloop,
153     locations_loop=>$locations_loop,
154 );
155 # prepare template variables common to all $op conditions:
156 if ($op!~/^mod/) {
157     letter_loop(q{}, $template);
158 }
159
160 if ($op eq 'addsubscription') {
161     redirect_add_subscription();
162 } elsif ($op eq 'modsubscription') {
163     redirect_mod_subscription();
164 } else {
165         while (@subscription_types) {
166            my $sub_type = shift @subscription_types;
167            my %row = ( 'name' => $sub_type );
168            if ( defined $sub_on and $sub_on eq $sub_type ) {
169              $row{'selected'} = ' selected';
170            } else {
171              $row{'selected'} = '';
172            }
173            push( @sub_type_data, \%row );
174         }
175     $template->param(subtype => \@sub_type_data);
176
177     letter_loop( '', $template ) if ($op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify');
178
179     my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
180     if (defined $new_biblionumber) {
181         my $bib = GetBiblioData($new_biblionumber);
182         if (defined $bib) {
183             $template->param(bibnum      => $new_biblionumber);
184             $template->param(bibliotitle => $bib->{title});
185         }
186     }
187
188     $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
189
190     my @frequencies = GetSubscriptionFrequencies;
191     my @frqloop;
192     foreach my $freq (@frequencies) {
193         my $selected = 0;
194         $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
195         my $row = {
196             id => $freq->{'id'},
197             selected => $selected,
198             label => $freq->{'description'},
199         };
200         push @frqloop, $row;
201     }
202     $template->param(frequencies => \@frqloop);
203
204     my @numpatterns = GetSubscriptionNumberpatterns;
205     my @numberpatternloop;
206     foreach my $numpattern (@numpatterns) {
207         my $selected = 0;
208         $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
209         my $row = {
210             id => $numpattern->{'id'},
211             selected => $selected,
212             label => $numpattern->{'label'},
213         };
214         push @numberpatternloop, $row;
215     }
216     $template->param(numberpatterns => \@numberpatternloop);
217
218     # Get installed locales
219     # FIXME this will not work with all environments.
220     # If call to locale fails, @locales will be an empty array, which is fine.
221     my @locales = map {
222         chomp;
223         # we don't want POSIX and C locales
224         /^C|^POSIX$/ ? () : $_
225     } `locale -a`;
226     $template->param(locales => \@locales);
227
228     output_html_with_http_headers $query, $cookie, $template->output;
229 }
230
231 sub letter_loop {
232     my ($selected_letter, $templte) = @_;
233     my $letters = GetLetters('serial');
234     my $letterloop;
235     foreach my $thisletter (keys %{$letters}) {
236         push @{$letterloop}, {
237             value => $thisletter,
238             selected => $thisletter eq $selected_letter,
239             lettername => $letters->{$thisletter},
240         };
241     }
242     $templte->param(letterloop => $letterloop);
243     return;
244 }
245
246 sub _get_sub_length {
247     my ($type, $length) = @_;
248     return
249         (
250             $type eq 'issues' ? $length : 0,
251             $type eq 'weeks'   ? $length : 0,
252             $type eq 'months'  ? $length : 0,
253         );
254 }
255
256 sub _guess_enddate {
257     my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
258     my ($year, $month, $day);
259     my $enddate;
260     if($numberlength != 0) {
261         my $frequency = GetSubscriptionFrequency($frequencyid);
262         if($frequency->{'unit'} eq 'day') {
263             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
264         } elsif($frequency->{'unit'} eq 'week') {
265             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
266         } elsif($frequency->{'unit'} eq 'month') {
267             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
268         } elsif($frequency->{'unit'} eq 'year') {
269             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
270         }
271     } elsif($weeklength != 0) {
272         ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
273     } elsif($monthlength != 0) {
274         ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
275     }
276     if(defined $year) {
277         $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
278     } else {
279         undef $enddate;
280     }
281     return $enddate;
282 }
283
284 sub redirect_add_subscription {
285     my $auser          = $query->param('user');
286     my $branchcode     = $query->param('branchcode');
287     my $aqbooksellerid = $query->param('aqbooksellerid');
288     my $cost           = $query->param('cost');
289     my $aqbudgetid     = $query->param('aqbudgetid');
290     my $periodicity    = $query->param('frequency');
291     my @irregularity   = $query->param('irregularity');
292     my $numberpattern  = $query->param('numbering_pattern');
293     my $locale         = $query->param('locale');
294     my $graceperiod    = $query->param('graceperiod') || 0;
295
296     my $subtype = $query->param('subtype');
297     my $sublength = $query->param('sublength');
298     my ( $numberlength, $weeklength, $monthlength )
299         = _get_sub_length( $subtype, $sublength );
300     my $add1              = $query->param('add1');
301     my $lastvalue1        = $query->param('lastvalue1');
302     my $innerloop1        = $query->param('innerloop1');
303     my $innerloop2        = $query->param('innerloop2');
304     my $lastvalue2        = $query->param('lastvalue2');
305     my $lastvalue3        = $query->param('lastvalue3');
306     my $innerloop3        = $query->param('innerloop3');
307     my $status            = 1;
308     my $biblionumber      = $query->param('biblionumber');
309     my $callnumber        = $query->param('callnumber');
310     my $notes             = $query->param('notes');
311     my $internalnotes     = $query->param('internalnotes');
312     my $letter            = $query->param('letter');
313     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
314     my $serialsadditems   = $query->param('serialsadditems');
315     my $staffdisplaycount = $query->param('staffdisplaycount');
316     my $opacdisplaycount  = $query->param('opacdisplaycount');
317     my $location          = $query->param('location');
318     my $skip_serialseq    = $query->param('skip_serialseq');
319     my $startdate = format_date_in_iso( $query->param('startdate') );
320     my $enddate = format_date_in_iso( $query->param('enddate') );
321     my $firstacquidate  = format_date_in_iso($query->param('firstacquidate'));
322     if(!defined $enddate || $enddate eq '') {
323         if($subtype eq "issues") {
324             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
325         } else {
326             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
327         }
328     }
329
330     my $subscriptionid = NewSubscription(
331         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
332         $startdate, $periodicity, $numberlength, $weeklength,
333         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
334         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
335         join(";",@irregularity), $numberpattern, $locale, $callnumber,
336         $manualhistory, $internalnotes, $serialsadditems,
337         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
338         $skip_serialseq
339     );
340
341     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
342     return;
343 }
344
345 sub redirect_mod_subscription {
346     my $subscriptionid = $query->param('subscriptionid');
347     my @irregularity = $query->param('irregularity');
348     my $auser = $query->param('user');
349     my $librarian => $query->param('librarian'),
350     my $branchcode = $query->param('branchcode');
351     my $cost = $query->param('cost');
352     my $aqbooksellerid = $query->param('aqbooksellerid');
353     my $biblionumber = $query->param('biblionumber');
354     my $aqbudgetid = $query->param('aqbudgetid');
355     my $startdate = format_date_in_iso($query->param('startdate'));
356     my $firstacquidate = format_date_in_iso( $query->param('firstacquidate') );
357     my $nextacquidate = $query->param('nextacquidate') ?
358                             format_date_in_iso($query->param('nextacquidate')):
359                             $firstacquidate;
360     my $enddate = format_date_in_iso($query->param('enddate'));
361     my $periodicity = $query->param('frequency');
362
363     my $subtype = $query->param('subtype');
364     my $sublength = $query->param('sublength');
365     my ($numberlength, $weeklength, $monthlength)
366         = _get_sub_length( $subtype, $sublength );
367     my $numberpattern = $query->param('numbering_pattern');
368     my $locale = $query->param('locale');
369     my $lastvalue1 = $query->param('lastvalue1');
370     my $innerloop1 = $query->param('innerloop1');
371     my $lastvalue2 = $query->param('lastvalue2');
372     my $innerloop2 = $query->param('innerloop2');
373     my $lastvalue3 = $query->param('lastvalue3');
374     my $innerloop3 = $query->param('innerloop3');
375     my $status = 1;
376     my $callnumber = $query->param('callnumber');
377     my $notes = $query->param('notes');
378     my $internalnotes = $query->param('internalnotes');
379     my $letter = $query->param('letter');
380     my $manualhistory = $query->param('manualhist') ? 1 : 0;
381     my $serialsadditems = $query->param('serialsadditems');
382         my $staffdisplaycount = $query->param('staffdisplaycount');
383         my $opacdisplaycount = $query->param('opacdisplaycount');
384     my $graceperiod     = $query->param('graceperiod') || 0;
385     my $location = $query->param('location');
386     my $skip_serialseq    = $query->param('skip_serialseq');
387
388     # Guess end date
389     if(!defined $enddate || $enddate eq '') {
390         if($subtype eq "issues") {
391             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
392         } else {
393             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
394         }
395     }
396
397     my $nextexpected = GetNextExpected($subscriptionid);
398     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
399     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
400         ModNextExpected($subscriptionid, $nextacquidate);
401         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
402         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
403     }
404
405     ModSubscription(
406         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
407         $periodicity, $firstacquidate, join(";",@irregularity),
408         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
409         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
410         $status, $biblionumber, $callnumber, $notes, $letter,
411         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
412         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
413         $skip_serialseq
414     );
415
416     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
417     return;
418 }