#!/usr/bin/perl -w
# --
##_ CustomerNotification.pl - does customer notification about
#                           their ticket creation and closure
#               with mail if necessary
# by Alexander Scholler <scholler@web.de>
# --
# $Id: TicketNotification.pl,v 1.0 2006/11/22 08:00:00 scholler Exp $
# --
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
# --

# To use this script, the following has to be configured:
# * Add notification-type to DB:
#   INSERT INTO notifications (notification_type , notification_charset, notification_language, subject, text, create_time, create_by, change_time, change_by)  VALUES
#   ('Customer::TicketCreation', 'utf-8', 'en', 'Ticket created!', 'Dear <OTRS_CUSTOMER_DATA_USERFIRSTNAME> <OTRS_CUSTOMER_DATA_USERLASTNAME>.\n\nThanks for your e-mail. We will start working on it as \n<OTRS_TICKET_NUMBER> asap.\n\nYou wrote:\n<OTRS_CUSTOMER_EMAIL[6]>\n\nThanks for using the Service-Desk.', '2006-08-23 07:11:55', 2, '2006-08-23 07:11:55', 2),
#   ('Customer::TicketDone', 'utf-8', 'en', 'Ticket done!', 'Dear <OTRS_CUSTOMER_DATA_USERFIRSTNAME> <OTRS_CUSTOMER_DATA_USERLASTNAME>.\n\nYour ticket is done!\n\nYou wrote:\n<OTRS_CUSTOMER_EMAIL[6]>\n\nThanks for using the Service-Desk.\n', '2006-08-23 07:12:05', 2, '2006-08-23 07:12:05', 2),
#   ('Customer::TicketDone', 'utf-8', 'de', 'Ticket abgeschlossen!', 'Sehr geehrte(r) <OTRS_CUSTOMER_DATA_USERFIRSTNAME> <OTRS_CUSTOMER_DATA_USERLASTNAME>,\n\nIhr Ticket wurde abgeschlossen!\n\nSie haben uns geschrieben:\n<OTRS_CUSTOMER_EMAIL[6]>\n\nDanke dass Sie den Service-Desk genutzt haben!', '2006-08-23 07:09:39', 2, '2006-08-23 07:09:39', 2),
#   ('Customer::TicketCreation', 'utf-8', 'de', 'Ticket erzeugt!', 'Sehr geehrte(r) <OTRS_CUSTOMER_DATA_USERFIRSTNAME> <OTRS_CUSTOMER_DATA_USERLASTNAME>, danke für Ihr Mail. Wir bearbeiten diese unter der Nummer\n<OTRS_TICKET_NUMBER> sobald möglich.\n\nSie haben uns geschrieben:\n<OTRS_CUSTOMER_EMAIL[6]>\n\nDanke dass Sie den Service-Desk nutzen.', '2006-08-23 07:09:56', 2, '2006-08-23 07:09:56', 2);
# * Define a TicketFreeKey/Text-pair, e.g. here #6:
#   $Self->{'TicketFreeKey6'} =  {
#       'customernotification' => 'customer notification on ticket'
#   };
#   $Self->{'TicketFreeText6::DefaultSelection'} =  'cd';
#   $Self->{'TicketFreeText6'} =  {
#       '' => 'none',
#       'd' => 'done',
#       'cd' => 'creation/done',
#   };
#   $Self->{'TicketFreeText6::DefaultSelection'} =  'cd';
# * optional: activate TicketFreeKey/Text to be displayed e.g. on
#   ~/Kernel/Output/HTML/Standard/AgentTicketEmail.dtl 
# [note: script does not check if notification was sent successfully.

# use ../ as lib location
use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);
use lib dirname($RealBin)."/Kernel/cpan-lib";


use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);
use lib dirname($RealBin)."/Kernel/cpan-lib";

use strict;

use vars qw($VERSION %Opts);
$VERSION = '$Revision: 0.1 $';
$VERSION =~ s/^\$.*:\W(.*)\W.+?$/$1/;

use Getopt::Std;
use Date::Pcalc qw(Day_of_Week Day_of_Week_Abbreviation);
use Kernel::Config;
use Kernel::System::Time;
use Kernel::System::Log;
use Kernel::System::Main;
use Kernel::System::DB;
use Kernel::System::Ticket;
use Kernel::System::User;
use Kernel::System::State;

# --
# common objects
# --
my %CommonObject = ();
$CommonObject{ConfigObject} = Kernel::Config->new();
$CommonObject{LogObject} = Kernel::System::Log->new(
    LogPrefix => 'OTRS-CustomerNotificationJobs',
    %CommonObject,
);
$CommonObject{MainObject} = Kernel::System::Main->new(%CommonObject);
$CommonObject{TimeObject} = Kernel::System::Time->new(%CommonObject);
$CommonObject{DBObject} = Kernel::System::DB->new(%CommonObject);
$CommonObject{TicketObject} = Kernel::System::Ticket->new(%CommonObject);
$CommonObject{UserObject} = Kernel::System::User->new(%CommonObject);
$CommonObject{StateObject} = Kernel::System::State->new(%CommonObject);

# --
# check args
# --
getopts('hESf:', \%Opts);
if ($Opts{'h'} or !($Opts{'E'} or $Opts{'S'}) or !$Opts{'f'}) {
    print "CustomerNotification.pl <Revision $VERSION> - notify customer about their tickets created and done\n";
    print "by Alexander Scholler <scholler\@web.de>\n";
    print "usage: TicketNotification.pl [-h] [-E] [-S] -f {n}\n";
    print " with  -h print this message\n";
    print "       -E notify created tickets\n";
    print "       -S notify done tickets\n";
    print "       -f {n} n-th freevalue/text-field should be used\n";
    print " -E or/and -S must be present to do notification\n";
    exit 1;
}

# get closed states to do notification
my @ClosedStateIDs = (
                   $CommonObject{StateObject}->StateGetStatesByType(
                       StateType => ['closed'],
                       Result => 'ID',
                   ),
               );
# get removed states which should not be taken into consideration
my @RemovedStateIDs = (
                   $CommonObject{StateObject}->StateGetStatesByType(
                       StateType => ['removed'],
                       Result => 'ID',
                   ),
               );

# get freekey/text
my @freekey = keys(%{$CommonObject{ConfigObject}->Get("TicketFreeKey$Opts{'f'}")});
my @freetext = keys(%{$CommonObject{ConfigObject}->Get("TicketFreeText$Opts{'f'}")});

# first to create-, then done-notification
foreach my $notification (qw(E S)) {
    # shall this notification really be done
    next unless $Opts{$notification};
    print "Now processing  \"$notification\"-notification...\n";

    my @TicketIDs = ();
    my $SQL;
    if ($notification eq 'E') {
        # search for new tickets with special freetext
        $SQL = "SELECT st.tn, st.id, st.user_id FROM " .
               " ticket st, ticket_state tsd " .
               " WHERE " .
               " st.ticket_state_id = tsd.id " .
               " AND " .
               " st.ticket_state_id NOT IN ( ${\(join ', ', @RemovedStateIDs)} ) AND " .
               " st.freetext$Opts{'f'} LIKE '\%E%'";
    } else {
        # search for closed-tickets with special freetext
        $SQL = "SELECT st.tn, st.id, st.user_id FROM " .
               " ticket st, ticket_state tsd " .
               " WHERE " .
               " st.ticket_state_id = tsd.id " .
               " AND " .
               " st.ticket_state_id IN ( ${\(join ', ', @ClosedStateIDs)} ) AND " .
               " st.freetext$Opts{'f'} LIKE '\%S%'";;
    }
    # include special freekey
    $SQL .= " AND st.freekey$Opts{'f'} = '$freekey[0]'"; # freekey must be correct
    $CommonObject{DBObject}->Prepare(SQL => $SQL);
    while (my @RowTmp = $CommonObject{DBObject}->FetchrowArray()) {
        push (@TicketIDs, $RowTmp[1]);
    }

    foreach (@TicketIDs) {
        my %Ticket = $CommonObject{TicketObject}->TicketGet(TicketID => $_);
        print "Found Ticket $Ticket{TicketNumber}/$Ticket{TicketID}: notification \"$notification\" ";
        if ($notification eq 'E' and $Ticket{"TicketFreeText$Opts{'f'}"} =~ /E/ or
            $notification eq 'S' and $Ticket{"TicketFreeText$Opts{'f'}"} =~ /S/) {
            # --
            # send customer notification
            # --
            print "is now to be send\n";
            $CommonObject{TicketObject}->SendCustomerNotification(
                Type => ($notification eq 'E')?'TicketCreation':'TicketDone',
                CustomerMessageParams => {},
                TicketID => $Ticket{TicketID},
                UserID => 1,
            );
        }
        else {
            print "shall not be send\n";
        }
        # set new ticket-freetext/value
        $CommonObject{TicketObject}->TicketFreeTextSet(
            Counter => $Opts{f},
            Key => $freekey[0],
            Value => ($notification eq 'E')?'S':'',
            TicketID => $Ticket{TicketID},
            UserID => 1,
        );
    }
}

exit (0);

