def format_ticket_html(t):

    template_str = """
        <tr>
        <td>${su}</td>
        <td><a href="https://ggus.eu/ws/ticket_info.php?ticket=${id}">${id}</a></td>
        <td>${status}</td>
        <td class="prio_${prio_class}">${prio}</td>
        <td><h5>${desc}</h5></td>
        <td><span class=\"badge\">${age}</span></td>
        </tr>"""

    ggus_t = get_ggus_ticket(ticket_id(t))
    assigned_time = ggus_t.assigned_time()
    age = (datetime.now() - assigned_time).days


    template = Template(template_str)
    ticket_str = template.substitute({"id":ticket_id(t),
                         "desc": ticket_short_description(t),
                         "su": ticket_su(t),
                         "prio_class" : ticket_priority(t).replace(' ','_'),
                         "prio": ticket_priority(t),
                         "age": age,
                         "related": None,
                         "status": ticket_status(t)
                         })

    return ticket_str
def classify_status(tickets):
    
    status_classification = {}
    
    for i in statuses:
        status_classification[i] = []
    
    for t in tickets:
        status = ticket_status(t)
        if status not in statuses:
            raise RuntimeError, "Unknown status: %s" % status
        status_classification[status].append(t)
        
    return status_classification
def print_ticket_history(ticket_list):
    for ticket_no in ticket_list:
        try:
            ticket = get_ticket(ticket_no)
        
            ggus_ticket = get_ggus_ticket(ticket_no)
            print "##########"
            print "Ticket: %s" % ticket_url(ticket)
            print "Summary: %s" % ticket_short_description(ticket)
            print "SU: %s" % ticket_su(ticket)
            print 'Last change: %s' % ticket_date_of_change(ticket)
            print "Priority: %s" % ticket_priority(ticket)
            print "Status: %s" % ticket_status(ticket)
            print
            print "Status History: "
            print
            ggus_ticket.print_status_history()
            print
            print "Priority History: "
            print
            ggus_ticket.print_priority_history()
            print
            print "SLA compliance values:"
            print
            val = ggus_ticket.get_sla_compliance_values2()
            counter = 0
            for v in val:
                
                
                if v.sla_delay:
                    sla_check_str = "Delay: %d business minutes (i.e. %d business hours, or  %d business days)" % (v.sla_delay,
                                                                                                                   v.sla_delay // 60,
                                                                                                                   v.sla_delay // 480)
                else:
                    sla_check_str = "SLA Check OK"    
                
                print "#", counter, " (%s)" % v.su, sla_check_str
                print "Priority when assigned: %s" % v.priority_when_assigned
                print "Assigned to SU %s on: %s" % (v.su, v.assigned_time)
                print "SLA constraint: %s" % sla_constraints[v.priority_when_assigned]
                print "Expected takeover: %s" % v.expected_takeover_time
                print "Actual takeover: %s" % v.out_of_assigned_time
                print "Out of assign status: %s" % v.out_of_assigned_status
                print
                counter = counter + 1
            print "##########"
            print 
            
        except WebFault:
            print >> stderr, "Error loading ticket %s" % (ticket_no)
def print_su_report():
    sus = sorted(emi_support_units.keys(), key=str.lower)
    
    first_line = "su,%s,%s" % (','.join(statuses), ','.join(priorities))
    template_line = "%s,%s" % ('%s', ','.join(['%d' for i in range(len(priorities) + len(statuses))]))
    zero_template = "%s,%s" % ('%s', ','.join(['0' for i in range(len(priorities) + len(statuses))]))
    
    print first_line
    for su in sus:
        tickets = []
        try:
            tickets = get_tickets(open_tickets_for_su(su))
        except WebFault:
            print >> stderr, "No open tickets found for SU %s" % su
            print zero_template % su
            continue
        
        status_classification = {}
        priority_classification = {}
        for i in statuses:
            status_classification[i] = []
        
        for i in priorities:
            priority_classification[i] = []
        
        for t in tickets:
            status = ticket_status(t)
            status_classification[status].append(t)
        
        for t in tickets:
            prio = ticket_priority(t)
            priority_classification[prio].append(t)
        
        print template_line % (su,
                               len(status_classification[statuses[0]]),
                               len(status_classification[statuses[1]]),
                               len(status_classification[statuses[2]]),
                               len(status_classification[statuses[3]]),
                               len(status_classification[statuses[4]]),
                               len(priority_classification[priorities[0]]),
                               len(priority_classification[priorities[1]]),
                               len(priority_classification[priorities[2]]),
                               len(priority_classification[priorities[3]]))
def print_on_hold_report():
    print "Producing on-hold tickets status report. Please be patient..."
    print "As of %s the following tickets are in on-hold status but don't have a related issue registered in GGUS." % datetime.now()
    tickets = get_tickets(open_on_hold_tickets())
    for t in filter(lambda x:ticket_related_issue(x) is None, sorted(tickets, key=ticket_su)):
        ggus_t = get_ggus_ticket(ticket_id(t))
        assigned_time = ggus_t.get_sla_compliance_values()[ticket_su(t)].assigned_time
        print "%-22s: https://ggus.eu/tech/ticket_show.php?ticket=%s ( %-3d days old ) %-15s %-15s \"%s\"" %(ticket_su(t),
                                                                                           ticket_id(t),
                                                                                           (datetime.now()-assigned_time).days,
                                                                                           ticket_priority(t),
                                                                                           ticket_status(t),
                                                                                           ticket_short_description(t))
def print_eta_status_report():
    print "Producing ETA status report. Please be patient..."
    
    tickets = get_tickets(open_very_urgent_and_top_priority_tickets())
    print "As of %s there are %d very urgent and top priority tickets which have ETA not set." % (datetime.now(), len(tickets))
    print
    for t in filter(lambda x:ticket_eta(x) is None, sorted(tickets, key=ticket_priority)):
        ggus_t = get_ggus_ticket(ticket_id(t))
        assigned_time = ggus_t.get_sla_compliance_values()[ticket_su(t)].assigned_time
        print "%-22s: https://ggus.eu/tech/ticket_show.php?ticket=%s ( %-3d days old ) %-15s %-18s \"%s\"" %(ticket_su(t),
                                                                                           ticket_id(t),
                                                                                           (datetime.now()-assigned_time).days,
                                                                                           ticket_priority(t),
                                                                                           ticket_status(t),
                                                                                           ticket_short_description(t))
def print_submitted_tickets_report(start_date, end_date=datetime.now()):
    
    print "Producing EMI support summary report for period %s-%s. Please be patient..." % (start_date.strftime(date_format_str),end_date.strftime(date_format_str))
    print "EMI SUs covered (%d): \n%s" % (len(emi_support_units),"\n".join(sorted(emi_support_units.keys())))
    
    tickets = get_tickets(emi_submitted_tickets_in_period(start_date,end_date))
    
    status_classification = classify_status(tickets)
    priority_classification = classify_priority(tickets)
    su_classification = classify_su(tickets, sus=emi_support_units.keys())
    
    report_template = Template("""${numTickets} tickets were submitted in period ${startDate}-${endDate}. 
The status for these tickets is currently:
        ${numAssigned} assigned,
        ${numInProgress} in progress,
        ${numOnHold} on hold,
        ${numReopened} reopened,
        ${numWaitingForReply} waiting for reply,
        ${numSolved} solved,
        ${numUnsolved} unsolved,
        ${numClosed} closed,
        ${numVerified} verified.
        
The current priority classification of the above tickets is:
        
        ${numTopPriority} top priority,
        ${numVeryUrgent} very urgent,
        ${numUrgent} urgent,
        ${numLessUrgent} less urgent.""")
        
    keys = {'numTickets': len(tickets),
            'startDate': start_date.strftime(date_format_str),
            'endDate': end_date.strftime(date_format_str),
            'numAssigned': len(status_classification['assigned']),
            'numInProgress': len(status_classification['in progress']),
            'numOnHold': len(status_classification['on hold']),
            'numReopened': len(status_classification['reopened']),
            'numSolved': len(status_classification['solved']),
            'numUnsolved': len(status_classification['unsolved']),
            'numClosed' : len(status_classification['closed']),
            'numVerified': len(status_classification['verified']),
            'numWaitingForReply': len(status_classification['waiting for reply']),
            'numTopPriority': len(priority_classification['top priority']),
            'numVeryUrgent': len(priority_classification['very urgent']),
            'numUrgent': len(priority_classification['urgent']),
            'numLessUrgent': len(priority_classification['less urgent'])
            }
        
        
    print report_template.safe_substitute(keys)
    
    sus = sorted(su_classification.keys())
    print
    print "The above tickets are currently assigned to the following SUs:"
    for su in sus:
        print "\n%s: %d" % (su, len(su_classification[su]))
        for t in su_classification[su]:
            print "\thttps://ggus.eu/tech/ticket_show.php?ticket=%s (%s) %s " % (ticket_id(t), ticket_priority(t), ticket_status(t))
            ggus_ticket = get_ggus_ticket(ticket_id(t))
            
            if ggus_ticket.solution_time():
                time_to_solution = "%d" % ggus_ticket.solution_time().days
            else:
                time_to_solution = ""
                
            last_solution_time = ggus_ticket.last_solution_time()
            if not last_solution_time:
                last_solution_time = ""
            
            delay_in_minutes = ggus_ticket_resolution_delay(ggus_ticket)
             
            print "%s;%s;%s;%s;%s;%s;%s;%s;%s" % (su,
                                                  ticket_url(t),
                                                  ticket_status(t),
                                                  ticket_priority(t),
                                                  ticket_creation_time(t),
                                                  ggus_ticket.assigned_time(),
                                                  last_solution_time,
                                                  time_to_solution,
                                                  delay_in_minutes // 60)
    
    print
    print "CSV generation took %d seconds. " % (time.time() - start_time)                                      
        
    
def print_ksa_1_2(start_date,end_date=datetime.now()):
    print >>sys.stderr, "Producing KSA1.2 kpi csv file for period %s-%s. Please be patient..." % (format_date(start_date),format_date(end_date))
    
    csv_header = "su,%s" % ','.join(priorities)
def on_hold_tickets(t):
    return ticket_status(t) == "on hold"
def waiting_for_reply_tickes(t):
    return  ticket_status(t) == "waiting for reply"
def ticket_needs_attention(t):
    val = (ticket_status(t) in ["assigned", "in progress", "reopened"])
    return  val