Bug 6254: DBrev 3.17.00.004
[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 $onlymine =
129      C4::Context->preference('IndependentBranches')
130   && C4::Context->userenv
131   && !C4::Context->IsSuperLibrarian
132   && (
133     not C4::Auth::haspermission( C4::Context->userenv->{id}, { serials => 'superserials' } )
134   )
135   && C4::Context->userenv->{branch};
136 my $branches = GetBranches($onlymine);
137 my $branchloop;
138 for my $thisbranch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %{$branches}) {
139     my $selected = 0;
140     $selected = 1 if (defined($subs) && $thisbranch eq $subs->{'branchcode'});
141     push @{$branchloop}, {
142         value => $thisbranch,
143         selected => $selected,
144         branchname => $branches->{$thisbranch}->{'branchname'},
145     };
146 }
147
148 my $locations_loop = GetAuthorisedValues("LOC",$subs->{'location'});
149
150 $template->param(branchloop => $branchloop,
151     locations_loop=>$locations_loop,
152 );
153 # prepare template variables common to all $op conditions:
154 if ($op!~/^mod/) {
155     letter_loop(q{}, $template);
156 }
157
158 if ($op eq 'addsubscription') {
159     redirect_add_subscription();
160 } elsif ($op eq 'modsubscription') {
161     redirect_mod_subscription();
162 } else {
163         while (@subscription_types) {
164            my $sub_type = shift @subscription_types;
165            my %row = ( 'name' => $sub_type );
166            if ( defined $sub_on and $sub_on eq $sub_type ) {
167              $row{'selected'} = ' selected';
168            } else {
169              $row{'selected'} = '';
170            }
171            push( @sub_type_data, \%row );
172         }
173     $template->param(subtype => \@sub_type_data);
174
175     letter_loop( '', $template ) if ($op ne 'modsubscription' && $op ne 'dup' && $op ne 'modify');
176
177     my $new_biblionumber = $query->param('biblionumber_for_new_subscription');
178     if (defined $new_biblionumber) {
179         my $bib = GetBiblioData($new_biblionumber);
180         if (defined $bib) {
181             $template->param(bibnum      => $new_biblionumber);
182             $template->param(bibliotitle => $bib->{title});
183         }
184     }
185
186     $template->param((uc(C4::Context->preference("marcflavour"))) => 1);
187
188     my @frequencies = GetSubscriptionFrequencies;
189     my @frqloop;
190     foreach my $freq (@frequencies) {
191         my $selected = 0;
192         $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity});
193         my $row = {
194             id => $freq->{'id'},
195             selected => $selected,
196             label => $freq->{'description'},
197         };
198         push @frqloop, $row;
199     }
200     $template->param(frequencies => \@frqloop);
201
202     my @numpatterns = GetSubscriptionNumberpatterns;
203     my @numberpatternloop;
204     foreach my $numpattern (@numpatterns) {
205         my $selected = 0;
206         $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern});
207         my $row = {
208             id => $numpattern->{'id'},
209             selected => $selected,
210             label => $numpattern->{'label'},
211         };
212         push @numberpatternloop, $row;
213     }
214     $template->param(numberpatterns => \@numberpatternloop);
215
216     my $languages = [ map {
217         {
218             language => $_->{iso639_2_code},
219             description => $_->{language_description} || $_->{language}
220         }
221     } @{ C4::Languages::getAllLanguages() } ];
222
223     $template->param( locales => $languages );
224
225     output_html_with_http_headers $query, $cookie, $template->output;
226 }
227
228 sub letter_loop {
229     my ($selected_letter, $templte) = @_;
230     my $letters = GetLetters('serial');
231     my $letterloop;
232     foreach my $thisletter (keys %{$letters}) {
233         push @{$letterloop}, {
234             value => $thisletter,
235             selected => $thisletter eq $selected_letter,
236             lettername => $letters->{$thisletter},
237         };
238     }
239     $templte->param(letterloop => $letterloop);
240     return;
241 }
242
243 sub _get_sub_length {
244     my ($type, $length) = @_;
245     return
246         (
247             $type eq 'issues' ? $length : 0,
248             $type eq 'weeks'   ? $length : 0,
249             $type eq 'months'  ? $length : 0,
250         );
251 }
252
253 sub _guess_enddate {
254     my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_;
255     my ($year, $month, $day);
256     my $enddate;
257     if($numberlength != 0) {
258         my $frequency = GetSubscriptionFrequency($frequencyid);
259         if($frequency->{'unit'} eq 'day') {
260             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
261         } elsif($frequency->{'unit'} eq 'week') {
262             ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
263         } elsif($frequency->{'unit'} eq 'month') {
264             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'});
265         } elsif($frequency->{'unit'} eq 'year') {
266             ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0);
267         }
268     } elsif($weeklength != 0) {
269         ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7);
270     } elsif($monthlength != 0) {
271         ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength);
272     }
273     if(defined $year) {
274         $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day);
275     } else {
276         undef $enddate;
277     }
278     return $enddate;
279 }
280
281 sub redirect_add_subscription {
282     my $auser          = $query->param('user');
283     my $branchcode     = $query->param('branchcode');
284     my $aqbooksellerid = $query->param('aqbooksellerid');
285     my $cost           = $query->param('cost');
286     my $aqbudgetid     = $query->param('aqbudgetid');
287     my $periodicity    = $query->param('frequency');
288     my @irregularity   = $query->param('irregularity');
289     my $numberpattern  = $query->param('numbering_pattern');
290     my $locale         = $query->param('locale');
291     my $graceperiod    = $query->param('graceperiod') || 0;
292
293     my $subtype = $query->param('subtype');
294     my $sublength = $query->param('sublength');
295     my ( $numberlength, $weeklength, $monthlength )
296         = _get_sub_length( $subtype, $sublength );
297     my $add1              = $query->param('add1');
298     my $lastvalue1        = $query->param('lastvalue1');
299     my $innerloop1        = $query->param('innerloop1');
300     my $innerloop2        = $query->param('innerloop2');
301     my $lastvalue2        = $query->param('lastvalue2');
302     my $lastvalue3        = $query->param('lastvalue3');
303     my $innerloop3        = $query->param('innerloop3');
304     my $status            = 1;
305     my $biblionumber      = $query->param('biblionumber');
306     my $callnumber        = $query->param('callnumber');
307     my $notes             = $query->param('notes');
308     my $internalnotes     = $query->param('internalnotes');
309     my $letter            = $query->param('letter');
310     my $manualhistory     = $query->param('manualhist') ? 1 : 0;
311     my $serialsadditems   = $query->param('serialsadditems');
312     my $staffdisplaycount = $query->param('staffdisplaycount');
313     my $opacdisplaycount  = $query->param('opacdisplaycount');
314     my $location          = $query->param('location');
315     my $skip_serialseq    = $query->param('skip_serialseq');
316     my $startdate = format_date_in_iso( $query->param('startdate') );
317     my $enddate = format_date_in_iso( $query->param('enddate') );
318     my $firstacquidate  = format_date_in_iso($query->param('firstacquidate'));
319     if(!defined $enddate || $enddate eq '') {
320         if($subtype eq "issues") {
321             $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
322         } else {
323             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
324         }
325     }
326
327     my $subscriptionid = NewSubscription(
328         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber,
329         $startdate, $periodicity, $numberlength, $weeklength,
330         $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2,
331         $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate,
332         join(";",@irregularity), $numberpattern, $locale, $callnumber,
333         $manualhistory, $internalnotes, $serialsadditems,
334         $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate,
335         $skip_serialseq
336     );
337
338     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
339     return;
340 }
341
342 sub redirect_mod_subscription {
343     my $subscriptionid = $query->param('subscriptionid');
344     my @irregularity = $query->param('irregularity');
345     my $auser = $query->param('user');
346     my $librarian => $query->param('librarian'),
347     my $branchcode = $query->param('branchcode');
348     my $cost = $query->param('cost');
349     my $aqbooksellerid = $query->param('aqbooksellerid');
350     my $biblionumber = $query->param('biblionumber');
351     my $aqbudgetid = $query->param('aqbudgetid');
352     my $startdate = format_date_in_iso($query->param('startdate'));
353     my $firstacquidate = format_date_in_iso( $query->param('firstacquidate') );
354     my $nextacquidate = $query->param('nextacquidate') ?
355                             format_date_in_iso($query->param('nextacquidate')):
356                             $firstacquidate;
357     my $enddate = format_date_in_iso($query->param('enddate'));
358     my $periodicity = $query->param('frequency');
359
360     my $subtype = $query->param('subtype');
361     my $sublength = $query->param('sublength');
362     my ($numberlength, $weeklength, $monthlength)
363         = _get_sub_length( $subtype, $sublength );
364     my $numberpattern = $query->param('numbering_pattern');
365     my $locale = $query->param('locale');
366     my $lastvalue1 = $query->param('lastvalue1');
367     my $innerloop1 = $query->param('innerloop1');
368     my $lastvalue2 = $query->param('lastvalue2');
369     my $innerloop2 = $query->param('innerloop2');
370     my $lastvalue3 = $query->param('lastvalue3');
371     my $innerloop3 = $query->param('innerloop3');
372     my $status = 1;
373     my $callnumber = $query->param('callnumber');
374     my $notes = $query->param('notes');
375     my $internalnotes = $query->param('internalnotes');
376     my $letter = $query->param('letter');
377     my $manualhistory = $query->param('manualhist') ? 1 : 0;
378     my $serialsadditems = $query->param('serialsadditems');
379         my $staffdisplaycount = $query->param('staffdisplaycount');
380         my $opacdisplaycount = $query->param('opacdisplaycount');
381     my $graceperiod     = $query->param('graceperiod') || 0;
382     my $location = $query->param('location');
383     my $skip_serialseq    = $query->param('skip_serialseq');
384
385     # Guess end date
386     if(!defined $enddate || $enddate eq '') {
387         if($subtype eq "issues") {
388             $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength);
389         } else {
390             $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength);
391         }
392     }
393
394     my $nextexpected = GetNextExpected($subscriptionid);
395     #  If it's  a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary.
396     if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) {
397         ModNextExpected($subscriptionid, $nextacquidate);
398         # if we have not received any issues yet, then we also must change the firstacquidate for the subs.
399         $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue});
400     }
401
402     ModSubscription(
403         $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate,
404         $periodicity, $firstacquidate, join(";",@irregularity),
405         $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1,
406         $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3,
407         $status, $biblionumber, $callnumber, $notes, $letter,
408         $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount,
409         $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid,
410         $skip_serialseq
411     );
412
413     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
414     return;
415 }