"alle" E-Mail-Adressen per Anhaken als Empfänger hinzufügen können
[kivitendo-erp.git] / sql / Pg-upgrade2 / contacts_convert_cp_birthday_to_date.pl
1 # @tag: contacts_convert_cp_birthday_to_date
2 # @description: Umstellung cp_birthday von Freitext auf Datumsfeld
3 # @depends: release_2_7_0
4 package SL::DBUpgrade2::contacts_convert_cp_birthday_to_date;
5
6 use strict;
7 use utf8;
8
9 use parent qw(SL::DBUpgrade2::Base);
10
11 sub convert_to_date {
12   my ($self, $str) = @_;
13
14   return '' if !$str || ($str =~ m/00.*00.*00.*00/); # 0000-00-00 may be present in old databases.
15
16   my $sth = $self->dbh->prepare('SELECT ?::date AS date') or return undef;
17   $sth->execute($str)                                     or return undef;
18
19   return $sth->fetchrow_hashref->{date};
20 }
21
22 sub run {
23   my ($self) = @_;
24
25   my @data      = ();
26   my @auto_data = ();
27   my $sql       = <<SQL;
28     SELECT
29       cp_id,
30       cp_givenname,
31       cp_name,
32       cp_birthday AS cp_birthday_old
33     FROM contacts
34     ORDER BY cp_id;
35 SQL
36
37   my $sth = $self->dbh->prepare($sql) or die $self->dbh->errstr;
38   $sth->execute or die $self->dbh->errstr;
39
40   my $i = -1;
41   while (my $row = $sth->fetchrow_hashref) {
42     $i++;
43     $row->{cp_birthday} = $self->convert_to_date($::form->{form_submitted} ? $::form->{'cp_birthday_'. $i} : $row->{cp_birthday_old});
44     $row->{row_index}   = $i;
45
46     if ( defined($row->{cp_birthday}) ) {
47        push(@auto_data, $row);
48     } else {
49        push(@data,      $row);
50     }
51   }
52
53   $::form->{data}       = \@data;
54   $::form->{auto_data}  = \@auto_data;
55   $::form->{row_length} = $i;
56
57   if (@data) {
58     print $::form->parse_html_template('dbupgrade/contacts_convert_cp_birthday_to_date_form');
59     return 2;
60   } else {
61     $sql = <<SQL;
62       ALTER TABLE contacts DROP COLUMN cp_birthday;
63       ALTER TABLE contacts ADD COLUMN cp_birthday date;
64 SQL
65
66     $self->dbh->do($sql);
67
68     $sql = <<SQL;
69       UPDATE contacts
70       SET   cp_birthday = ?
71       WHERE cp_id = ?
72 SQL
73
74     $sth = $self->dbh->prepare($sql) or die $self->dbh->errstr;
75
76     foreach (grep { $_->{cp_birthday} ne '' } @auto_data) {
77       $sth->execute($_->{cp_birthday}, $_->{cp_id}) or die $self->dbh->errstr;
78     }
79
80     return 1;
81   }
82 }
83
84 1;