Bug 14022: Does not reset the subscription length on editing a subscription
[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
63 my $subs;
64 our $firstissuedate;
65
66 if ($op eq 'modify' || $op eq 'dup' || $op eq 'modsubscription') {
67
68     my $subscriptionid = $query->param('subscriptionid');
69     $subs = GetSubscription($subscriptionid);
70
71     ## FIXME : Check rights to edit if mod. Could/Should display an error message.
72     if ($subs->{'cannotedit'} && $op eq 'modify'){
73       carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed";
74       print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
75     }
76     $firstissuedate = $subs->{firstacquidate} || '';  # in iso format.
77     for (qw(startdate firstacquidate histstartdate enddate histenddate)) {
78         next unless defined $subs->{$_};
79         # TODO : Handle date formats properly.
80          if ($subs->{$_} eq '0000-00-00') {
81             $subs->{$_} = ''
82         } else {
83             $subs->{$_} = $subs->{$_};
84         }
85           }
86       if (!defined $subs->{letter}) {
87           $subs->{letter}= q{};
88       }
89     my $nextexpected = GetNextExpected($subscriptionid);
90     $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ;
91     $subs->{nextacquidate} = $nextexpected->{planneddate}  if($op eq 'modify');
92     unless($op eq 'modsubscription') {
93         foreach my $length_unit (qw(numberlength weeklength monthlength)) {
94             if ($subs->{$length_unit}) {
95                 $sub_length=$subs->{$length_unit};
96                 $sub_on=$length_unit;
97                 last;
98             }
99         }
100
101         $template->param( %{$subs} );
102         $template->param(
103                     $op => 1,
104                     "subtype_$sub_on" => 1,
105                     sublength =>$sub_length,
106                     history => ($op eq 'modify'),
107                     firstacquiyear => substr($firstissuedate,0,4),
108                     );
109
110         if($op eq 'modify') {
111             my ($serials_number) = GetSerials($subscriptionid);
112             if($serials_number > 1) {
113                 $template->param(more_than_one_serial => 1);
114             }
115         }
116     }
117
118     if ( $op eq 'dup' ) {
119         my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput');
120         my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields;
121         $template->param( dont_export_field_loop => \@fields_id );
122     }
123
124     my $letters = get_letter_loop( $subs->{letter} );
125     $template->param( letterloop => $letters );
126
127 }
128
129 my $onlymine =
130      C4::Context->preference('IndependentBranches')
131   && C4::Context->userenv
132   && !C4::Context->IsSuperLibrarian
133   && (
134     not C4::Auth::haspermission( C4::Context->userenv->{id}, { serials => 'superserials' } )
135   )
136   && C4::Context->userenv->{branch};
137 my $branches = GetBranches($onlymine);
138 my $branchloop;
139 for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %{$branches}) {
140     my $selected = 0;
141     $selected = 1 if (defined($subs) && $thisbranch eq $subs->{'branchcode'});
142     push @{$branchloop}, {
143         value => $thisbranch,
144         selected => $selected,
145         branchname => $branches->{$thisbranch}->{'branchname'},
146     };
147 }
148
149 my $locations_loop = GetAuthorisedValues("LOC",$subs->{'location'});
150
151 $template->param(branchloop => $branchloop,
152     locations_loop=>$locations_loop,
153 );
154 # prepare template variables common to all $op conditions:
155 if ($op!~/^mod/) {
156     my $letters = get_letter_loop();
157     $template->param( letterloop => $letters );
158 }
159
160 if ($op eq 'addsubscription') {
161     redirect_add_subscription();
162 } elsif ($op eq 'modsubscription') {
163     redirect_mod_subscription();
164 } else {
165
166     $template->param(
167         subtypes => [ qw( numberlength weeklength monthlength ) ],
168         subtype => $sub_on,
169     );
170
171     if ( $op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify' ) {
172         my $letters = get_letter_loop();
173         $template->param( letterloop => $letters );
174     }
175
176     my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
177     if (defined $new_biblionumber) {
178         my $bib = GetBiblioData($new_biblionumber);
179         if (defined $bib) {
180             $template->param(bibnum      => $new_biblionumber);
181             $template->param(bibliotitle => $bib->{title});
182         }
183     }
184
185     $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
186
187     my @frequencies = GetSubscriptionFrequencies;
188     my @frqloop;
189     foreach my $freq (@frequencies) {
190         my $selected = 0;
191         $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
192         my $row = {
193             id => $freq->{'id'},
194             selected => $selected,
195             label => $freq->{'description'},
196         };
197         push @frqloop, $row;
198     }
199     $template->param(frequencies => \@frqloop);
200
201     my @numpatterns = GetSubscriptionNumberpatterns;
202     my @numberpatternloop;
203     foreach my $numpattern (@numpatterns) {
204         my $selected = 0;
205         $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
206         my $row = {
207             id => $numpattern->{'id'},
208             selected => $selected,
209             label => $numpattern->{'label'},
210         };
211         push @numberpatternloop, $row;
212     }
213     $template->param(numberpatterns => \@numberpatternloop);
214
215     my $languages = [ map {
216         {
217             language => $_->{iso639_2_code},
218             description => $_->{language_description} || $_->{language}
219         }
220     } @{ C4::Languages::getAllLanguages() } ];
221
222     $template->param( locales => $languages );
223
224     output_html_with_http_headers $query, $cookie, $template->output;
225 }
226
227 sub get_letter_loop {
228     my ($selected_lettercode) = @_;
229     my $letters = GetLetters({ module => 'serial' });
230     return [
231         map {
232             {
233                 value      => $_->{code},
234                 lettername => $_->{name},
235                 ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ),
236             }
237           } @$letters
238     ];
239 }
240
241 sub _get_sub_length {
242     my ($type, $length) = @_;
243     return
244         (
245             $type eq 'issues' ? $length : 0,
246             $type eq 'weeks'   ? $length : 0,
247             $type eq 'months'  ? $length : 0,
248         );
249 }
250
251 sub _guess_enddate {
252     my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
253     my ($year, $month, $day);
254     my $enddate;
255     if($numberlength != 0) {
256         my $frequency = GetSubscriptionFrequency($frequencyid);
257         if($frequency->{'unit'} eq 'day') {
258             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
259         } elsif($frequency->{'unit'} eq 'week') {
260             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
261         } elsif($frequency->{'unit'} eq 'month') {
262             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
263         } elsif($frequency->{'unit'} eq 'year') {
264             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
265         }
266     } elsif($weeklength != 0) {
267         ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
268     } elsif($monthlength != 0) {
269         ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
270     }
271     if(defined $year) {
272         $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
273     } else {
274         undef $enddate;
275     }
276     return $enddate;
277 }
278
279 sub redirect_add_subscription {
280     my $auser          = $query->param('user');
281     my $branchcode     = $query->param('branchcode');
282     my $aqbooksellerid = $query->param('aqbooksellerid');
283     my $cost           = $query->param('cost');
284     my $aqbudgetid     = $query->param('aqbudgetid');
285     my $periodicity    = $query->param('frequency');
286     my @irregularity   = $query->param('irregularity');
287     my $numberpattern  = $query->param('numbering_pattern');
288     my $locale         = $query->param('locale');
289     my $graceperiod    = $query->param('graceperiod') || 0;
290
291     my $subtype = $query->param('subtype');
292     my $sublength = $query->param('sublength');
293     my ( $numberlength, $weeklength, $monthlength )
294         = _get_sub_length( $subtype, $sublength );
295     my $add1              = $query->param('add1');
296     my $lastvalue1        = $query->param('lastvalue1');
297     my $innerloop1        = $query->param('innerloop1');
298     my $innerloop2        = $query->param('innerloop2');
299     my $lastvalue2        = $query->param('lastvalue2');
300     my $lastvalue3        = $query->param('lastvalue3');
301     my $innerloop3        = $query->param('innerloop3');
302     my $status            = 1;
303     my $biblionumber      = $query->param('biblionumber');
304     my $callnumber        = $query->param('callnumber');
305     my $notes             = $query->param('notes');
306     my $internalnotes     = $query->param('internalnotes');
307     my $letter            = $query->param('letter');
308     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
309     my $serialsadditems   = $query->param('serialsadditems');
310     my $staffdisplaycount = $query->param('staffdisplaycount');
311     my $opacdisplaycount  = $query->param('opacdisplaycount');
312     my $location          = $query->param('location');
313     my $skip_serialseq    = $query->param('skip_serialseq');
314     my $startdate = format_date_in_iso( $query->param('startdate') );
315     my $enddate = format_date_in_iso( $query->param('enddate') );
316     my $firstacquidate  = format_date_in_iso($query->param('firstacquidate'));
317     if(!defined $enddate || $enddate eq '') {
318         if($subtype eq "issues") {
319             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
320         } else {
321             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
322         }
323     }
324
325     my $subscriptionid = NewSubscription(
326         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
327         $startdate, $periodicity, $numberlength, $weeklength,
328         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
329         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
330         join(";",@irregularity), $numberpattern, $locale, $callnumber,
331         $manualhistory, $internalnotes, $serialsadditems,
332         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
333         $skip_serialseq
334     );
335
336     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
337     return;
338 }
339
340 sub redirect_mod_subscription {
341     my $subscriptionid = $query->param('subscriptionid');
342     my @irregularity = $query->param('irregularity');
343     my $auser = $query->param('user');
344     my $librarian => $query->param('librarian'),
345     my $branchcode = $query->param('branchcode');
346     my $cost = $query->param('cost');
347     my $aqbooksellerid = $query->param('aqbooksellerid');
348     my $biblionumber = $query->param('biblionumber');
349     my $aqbudgetid = $query->param('aqbudgetid');
350     my $startdate = format_date_in_iso($query->param('startdate'));
351     my $firstacquidate = format_date_in_iso( $query->param('firstacquidate') );
352     my $nextacquidate = $query->param('nextacquidate') ?
353                             format_date_in_iso($query->param('nextacquidate')):
354                             $firstacquidate;
355     my $enddate = format_date_in_iso($query->param('enddate'));
356     my $periodicity = $query->param('frequency');
357
358     my $subtype = $query->param('subtype');
359     my $sublength = $query->param('sublength');
360     my ($numberlength, $weeklength, $monthlength)
361         = _get_sub_length( $subtype, $sublength );
362     my $numberpattern = $query->param('numbering_pattern');
363     my $locale = $query->param('locale');
364     my $lastvalue1 = $query->param('lastvalue1');
365     my $innerloop1 = $query->param('innerloop1');
366     my $lastvalue2 = $query->param('lastvalue2');
367     my $innerloop2 = $query->param('innerloop2');
368     my $lastvalue3 = $query->param('lastvalue3');
369     my $innerloop3 = $query->param('innerloop3');
370     my $status = 1;
371     my $callnumber = $query->param('callnumber');
372     my $notes = $query->param('notes');
373     my $internalnotes = $query->param('internalnotes');
374     my $letter = $query->param('letter');
375     my $manualhistory = $query->param('manualhist') ? 1 : 0;
376     my $serialsadditems = $query->param('serialsadditems');
377         my $staffdisplaycount = $query->param('staffdisplaycount');
378         my $opacdisplaycount = $query->param('opacdisplaycount');
379     my $graceperiod     = $query->param('graceperiod') || 0;
380     my $location = $query->param('location');
381     my $skip_serialseq    = $query->param('skip_serialseq');
382
383     # Guess end date
384     if(!defined $enddate || $enddate eq '') {
385         if($subtype eq "issues") {
386             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
387         } else {
388             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
389         }
390     }
391
392     my $nextexpected = GetNextExpected($subscriptionid);
393     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
394     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
395         ModNextExpected($subscriptionid, $nextacquidate);
396         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
397         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
398     }
399
400     ModSubscription(
401         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
402         $periodicity, $firstacquidate, join(";",@irregularity),
403         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
404         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
405         $status, $biblionumber, $callnumber, $notes, $letter,
406         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
407         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
408         $skip_serialseq
409     );
410
411     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
412     return;
413 }