Bug 9978: Replace license header with the correct license (GPLv3+)
[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
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use strict;
19 use warnings;
20
21 use CGI qw ( -utf8 );
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     my $nextexpected = GetNextExpected($subscriptionid);
92     $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
93     $subs->{nextacquidate} = $nextexpected->{planneddate}  if($op eq 'modify');
94     unless($op eq 'modsubscription') {
95         foreach my $length_unit (qw(numberlength weeklength monthlength)) {
96             if ($subs->{$length_unit}) {
97                 $sub_length=$subs->{$length_unit};
98                 $sub_on=$length_unit;
99                 last;
100             }
101         }
102
103         $template->param( %{$subs} );
104         $template->param(
105                     $op => 1,
106                     "subtype_$sub_on" => 1,
107                     sublength =>$sub_length,
108                     history => ($op eq 'modify'),
109                     firstacquiyear => substr($firstissuedate,0,4),
110                     );
111
112         if($op eq 'modify') {
113             my ($serials_number) = GetSerials($subscriptionid);
114             if($serials_number > 1) {
115                 $template->param(more_than_one_serial => 1);
116             }
117         }
118     }
119
120     if ( $op eq 'dup' ) {
121         my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
122         my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
123         $template->param( dont_export_field_loop => \@fields_id );
124     }
125
126     my $letters = get_letter_loop( $subs->{letter} );
127     $template->param( letterloop => $letters );
128
129 }
130
131 my $onlymine =
132      C4::Context->preference('IndependentBranches')
133   && C4::Context->userenv
134   && !C4::Context->IsSuperLibrarian
135   && (
136     not C4::Auth::haspermission( C4::Context->userenv->{id}, { serials => 'superserials' } )
137   )
138   && C4::Context->userenv->{branch};
139 my $branches = GetBranches($onlymine);
140 my $branchloop;
141 for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %{$branches}) {
142     my $selected = 0;
143     $selected = 1 if (defined($subs) && $thisbranch eq $subs->{'branchcode'});
144     push @{$branchloop}, {
145         value => $thisbranch,
146         selected => $selected,
147         branchname => $branches->{$thisbranch}->{'branchname'},
148     };
149 }
150
151 my $locations_loop = GetAuthorisedValues("LOC",$subs->{'location'});
152
153 $template->param(branchloop => $branchloop,
154     locations_loop=>$locations_loop,
155 );
156 # prepare template variables common to all $op conditions:
157 if ($op!~/^mod/) {
158     my $letters = get_letter_loop();
159     $template->param( letterloop => $letters );
160 }
161
162 if ($op eq 'addsubscription') {
163     redirect_add_subscription();
164 } elsif ($op eq 'modsubscription') {
165     redirect_mod_subscription();
166 } else {
167         while (@subscription_types) {
168            my $sub_type = shift @subscription_types;
169            my %row = ( 'name' => $sub_type );
170            if ( defined $sub_on and $sub_on eq $sub_type ) {
171              $row{'selected'} = ' selected';
172            } else {
173              $row{'selected'} = '';
174            }
175            push( @sub_type_data, \%row );
176         }
177     $template->param(subtype => \@sub_type_data);
178
179     if ( $op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify' ) {
180         my $letters = get_letter_loop();
181         $template->param( letterloop => $letters );
182     }
183
184     my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
185     if (defined $new_biblionumber) {
186         my $bib = GetBiblioData($new_biblionumber);
187         if (defined $bib) {
188             $template->param(bibnum      => $new_biblionumber);
189             $template->param(bibliotitle => $bib->{title});
190         }
191     }
192
193     $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
194
195     my @frequencies = GetSubscriptionFrequencies;
196     my @frqloop;
197     foreach my $freq (@frequencies) {
198         my $selected = 0;
199         $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
200         my $row = {
201             id => $freq->{'id'},
202             selected => $selected,
203             label => $freq->{'description'},
204         };
205         push @frqloop, $row;
206     }
207     $template->param(frequencies => \@frqloop);
208
209     my @numpatterns = GetSubscriptionNumberpatterns;
210     my @numberpatternloop;
211     foreach my $numpattern (@numpatterns) {
212         my $selected = 0;
213         $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
214         my $row = {
215             id => $numpattern->{'id'},
216             selected => $selected,
217             label => $numpattern->{'label'},
218         };
219         push @numberpatternloop, $row;
220     }
221     $template->param(numberpatterns => \@numberpatternloop);
222
223     my $languages = [ map {
224         {
225             language => $_->{iso639_2_code},
226             description => $_->{language_description} || $_->{language}
227         }
228     } @{ C4::Languages::getAllLanguages() } ];
229
230     $template->param( locales => $languages );
231
232     output_html_with_http_headers $query, $cookie, $template->output;
233 }
234
235 sub get_letter_loop {
236     my ($selected_lettercode) = @_;
237     my $letters = GetLetters({ module => 'serial' });
238     return [
239         map {
240             {
241                 value      => $_->{code},
242                 lettername => $_->{name},
243                 ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
244             }
245           } @$letters
246     ];
247 }
248
249 sub _get_sub_length {
250     my ($type, $length) = @_;
251     return
252         (
253             $type eq 'issues' ? $length : 0,
254             $type eq 'weeks'   ? $length : 0,
255             $type eq 'months'  ? $length : 0,
256         );
257 }
258
259 sub _guess_enddate {
260     my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
261     my ($year, $month, $day);
262     my $enddate;
263     if($numberlength != 0) {
264         my $frequency = GetSubscriptionFrequency($frequencyid);
265         if($frequency->{'unit'} eq 'day') {
266             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
267         } elsif($frequency->{'unit'} eq 'week') {
268             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
269         } elsif($frequency->{'unit'} eq 'month') {
270             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
271         } elsif($frequency->{'unit'} eq 'year') {
272             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
273         }
274     } elsif($weeklength != 0) {
275         ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
276     } elsif($monthlength != 0) {
277         ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
278     }
279     if(defined $year) {
280         $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
281     } else {
282         undef $enddate;
283     }
284     return $enddate;
285 }
286
287 sub redirect_add_subscription {
288     my $auser          = $query->param('user');
289     my $branchcode     = $query->param('branchcode');
290     my $aqbooksellerid = $query->param('aqbooksellerid');
291     my $cost           = $query->param('cost');
292     my $aqbudgetid     = $query->param('aqbudgetid');
293     my $periodicity    = $query->param('frequency');
294     my @irregularity   = $query->param('irregularity');
295     my $numberpattern  = $query->param('numbering_pattern');
296     my $locale         = $query->param('locale');
297     my $graceperiod    = $query->param('graceperiod') || 0;
298
299     my $subtype = $query->param('subtype');
300     my $sublength = $query->param('sublength');
301     my ( $numberlength, $weeklength, $monthlength )
302         = _get_sub_length( $subtype, $sublength );
303     my $add1              = $query->param('add1');
304     my $lastvalue1        = $query->param('lastvalue1');
305     my $innerloop1        = $query->param('innerloop1');
306     my $innerloop2        = $query->param('innerloop2');
307     my $lastvalue2        = $query->param('lastvalue2');
308     my $lastvalue3        = $query->param('lastvalue3');
309     my $innerloop3        = $query->param('innerloop3');
310     my $status            = 1;
311     my $biblionumber      = $query->param('biblionumber');
312     my $callnumber        = $query->param('callnumber');
313     my $notes             = $query->param('notes');
314     my $internalnotes     = $query->param('internalnotes');
315     my $letter            = $query->param('letter');
316     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
317     my $serialsadditems   = $query->param('serialsadditems');
318     my $staffdisplaycount = $query->param('staffdisplaycount');
319     my $opacdisplaycount  = $query->param('opacdisplaycount');
320     my $location          = $query->param('location');
321     my $skip_serialseq    = $query->param('skip_serialseq');
322     my $startdate = format_date_in_iso( $query->param('startdate') );
323     my $enddate = format_date_in_iso( $query->param('enddate') );
324     my $firstacquidate  = format_date_in_iso($query->param('firstacquidate'));
325     if(!defined $enddate || $enddate eq '') {
326         if($subtype eq "issues") {
327             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
328         } else {
329             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
330         }
331     }
332
333     my $subscriptionid = NewSubscription(
334         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
335         $startdate, $periodicity, $numberlength, $weeklength,
336         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
337         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
338         join(";",@irregularity), $numberpattern, $locale, $callnumber,
339         $manualhistory, $internalnotes, $serialsadditems,
340         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
341         $skip_serialseq
342     );
343
344     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
345     return;
346 }
347
348 sub redirect_mod_subscription {
349     my $subscriptionid = $query->param('subscriptionid');
350     my @irregularity = $query->param('irregularity');
351     my $auser = $query->param('user');
352     my $librarian => $query->param('librarian'),
353     my $branchcode = $query->param('branchcode');
354     my $cost = $query->param('cost');
355     my $aqbooksellerid = $query->param('aqbooksellerid');
356     my $biblionumber = $query->param('biblionumber');
357     my $aqbudgetid = $query->param('aqbudgetid');
358     my $startdate = format_date_in_iso($query->param('startdate'));
359     my $firstacquidate = format_date_in_iso( $query->param('firstacquidate') );
360     my $nextacquidate = $query->param('nextacquidate') ?
361                             format_date_in_iso($query->param('nextacquidate')):
362                             $firstacquidate;
363     my $enddate = format_date_in_iso($query->param('enddate'));
364     my $periodicity = $query->param('frequency');
365
366     my $subtype = $query->param('subtype');
367     my $sublength = $query->param('sublength');
368     my ($numberlength, $weeklength, $monthlength)
369         = _get_sub_length( $subtype, $sublength );
370     my $numberpattern = $query->param('numbering_pattern');
371     my $locale = $query->param('locale');
372     my $lastvalue1 = $query->param('lastvalue1');
373     my $innerloop1 = $query->param('innerloop1');
374     my $lastvalue2 = $query->param('lastvalue2');
375     my $innerloop2 = $query->param('innerloop2');
376     my $lastvalue3 = $query->param('lastvalue3');
377     my $innerloop3 = $query->param('innerloop3');
378     my $status = 1;
379     my $callnumber = $query->param('callnumber');
380     my $notes = $query->param('notes');
381     my $internalnotes = $query->param('internalnotes');
382     my $letter = $query->param('letter');
383     my $manualhistory = $query->param('manualhist') ? 1 : 0;
384     my $serialsadditems = $query->param('serialsadditems');
385         my $staffdisplaycount = $query->param('staffdisplaycount');
386         my $opacdisplaycount = $query->param('opacdisplaycount');
387     my $graceperiod     = $query->param('graceperiod') || 0;
388     my $location = $query->param('location');
389     my $skip_serialseq    = $query->param('skip_serialseq');
390
391     # Guess end date
392     if(!defined $enddate || $enddate eq '') {
393         if($subtype eq "issues") {
394             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
395         } else {
396             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
397         }
398     }
399
400     my $nextexpected = GetNextExpected($subscriptionid);
401     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
402     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
403         ModNextExpected($subscriptionid, $nextacquidate);
404         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
405         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
406     }
407
408     ModSubscription(
409         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
410         $periodicity, $firstacquidate, join(";",@irregularity),
411         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
412         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
413         $status, $biblionumber, $callnumber, $notes, $letter,
414         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
415         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
416         $skip_serialseq
417     );
418
419     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
420     return;
421 }