public ActionResult SaveAndCopy(IncidentAction incidentAction, bool applyAction, long businessRiskId, int userId)
    {
        var res = ActionResult.NoAction;

        if (incidentAction.Id < 1)
        {
            res = incidentAction.Insert(userId);
        }
        else
        {
            res = incidentAction.Update(userId);
        }

        if (applyAction)
        {
            var risk = BusinessRisk.ById(incidentAction.CompanyId, businessRiskId);
            incidentAction.BusinessRiskId   = risk.Id;
            incidentAction.WhatHappenedOn   = risk.DateStart;
            incidentAction.Causes           = risk.Causes;
            incidentAction.ClosedBy         = null;
            incidentAction.ClosedExecutor   = null;
            incidentAction.ClosedExecutorOn = null;
            incidentAction.ClosedOn         = null;
            res = incidentAction.Insert(userId);
        }

        return(res);
    }
Beispiel #2
0
        public static ReadOnlyCollection <IncidentCost> AllCosts(long incidentId, int companyId)
        {
            var costs       = ByIncidentId(incidentId, companyId).ToList();
            var actionCosts = new ReadOnlyCollection <IncidentActionCost>(new List <IncidentActionCost>());
            var action      = IncidentAction.ByIncidentId(incidentId, companyId);

            if (action.Id > 0)
            {
                actionCosts = IncidentActionCost.GetByIncidentActionId(action.Id, companyId);
                foreach (var actionCost in actionCosts)
                {
                    costs.Add(new IncidentCost
                    {
                        Id             = actionCost.Id,
                        IncidentId     = incidentId,
                        BusinessRiskId = actionCost.IncidentActionId,
                        Description    = actionCost.Description,
                        Quantity       = actionCost.Quantity,
                        CompanyId      = actionCost.CompanyId,
                        Responsible    = actionCost.Responsible,
                        Amount         = actionCost.Amount,
                        Active         = actionCost.Active,
                        Source         = "A",
                        Date           = actionCost.Date
                    });
                }
            }

            return(new ReadOnlyCollection <IncidentCost>(costs));
        }
Beispiel #3
0
    public ActionResult Update(Oportunity oportunity, int applicationUserId)
    {
        var res = oportunity.Update(applicationUserId);

        if (oportunity.FinalDate.HasValue && oportunity.FinalDate.Value.Year < 2000)
        {
            oportunity.FinalDate = null;
        }

        if (res.Success && oportunity.FinalDate.HasValue)
        {
            var newOportunity = new Oportunity
            {
                Code                 = oportunity.Code,
                CompanyId            = oportunity.CompanyId,
                DateStart            = oportunity.FinalDate.Value,
                Cost                 = oportunity.FinalCost,
                Impact               = oportunity.FinalImpact,
                Description          = oportunity.Description,
                ApplyAction          = oportunity.FinalApplyAction.Value,
                Result               = oportunity.FinalResult,
                Causes               = oportunity.Causes,
                Notes                = oportunity.Notes,
                ItemDescription      = oportunity.ItemDescription,
                PreviousOportunityId = oportunity.Id,
                Process              = oportunity.Process,
                Rule                 = oportunity.Rule,
                Control              = oportunity.Control
            };

            res = newOportunity.Insert(applicationUserId);
            var employee     = Employee.ByUserId(applicationUserId);
            var actualAction = IncidentAction.ByOportunityId(oportunity.Id, oportunity.CompanyId);
            var newAction    = new IncidentAction
            {
                Oportunity     = newOportunity,
                Origin         = actualAction.Origin,
                ReporterType   = actualAction.ReporterType,
                WhatHappened   = actualAction.WhatHappened,
                WhatHappenedBy = employee,
                WhatHappenedOn = newOportunity.DateStart,
                Causes         = actualAction.Causes,
                CausesBy       = employee,
                CausesOn       = newOportunity.DateStart,
                ActionType     = actualAction.ActionType,
                Description    = actualAction.Description,
                CompanyId      = actualAction.CompanyId,
                Provider       = actualAction.Provider,
                Customer       = actualAction.Customer,
                Department     = actualAction.Department
            };

            res = newAction.Insert(applicationUserId);
        }

        return(res);
    }
    public ActionResult Save(IncidentAction incidentAction, int userId)
    {
        var res = ActionResult.NoAction;

        if (incidentAction.Id < 1)
        {
            res = incidentAction.Insert(userId);
        }
        else
        {
            res = incidentAction.Update(userId);
        }

        return(res);
    }
Beispiel #5
0
        public static ActionResult SaveAction(IncidentAction action, int userId)
        {
            if (action == null)
            {
                return(ActionResult.NoAction);
            }

            if (action.Id == 0)
            {
                return(action.Insert(userId));
            }
            else
            {
                return(action.Update(userId));
            }
        }
    private void RenderRealActions()
    {
        if (this.Auditory.Status < 4)
        {
            return;
        }

        var res     = new StringBuilder();
        var actions = IncidentAction.ByAuditoryId(this.auditoryId, this.company.Id);

        foreach (var action in actions)
        {
            res.Append(action.ListAuditoryRow(this.Dictionary, this.user.Grants));
        }

        this.LtActionsData.Text      = res.ToString();
        this.LtActionsDataCount.Text = actions.Count.ToString();
    }
    public string GetFilter(int companyId, DateTime?from, DateTime?to, bool statusIdnetified, bool statusAnalyzed, bool statusInProgress, bool statusClose, bool typeImprovement, bool typeFix, bool typePrevent, int origin, int reporter)
    {
        var filter = new StringBuilder("{");

        filter.Append(Tools.JsonPair("companyId", companyId)).Append(",");
        filter.Append(Tools.JsonPair("from", from)).Append(",");
        filter.Append(Tools.JsonPair("to", to)).Append(",");
        filter.Append(Tools.JsonPair("statusIdnetified", statusIdnetified)).Append(",");
        filter.Append(Tools.JsonPair("statusAnalyzed", statusAnalyzed)).Append(",");
        filter.Append(Tools.JsonPair("statusInProgress", statusInProgress)).Append(",");
        filter.Append(Tools.JsonPair("statusClose", statusClose)).Append(",");
        filter.Append(Tools.JsonPair("typeImprovement", typeImprovement)).Append(",");
        filter.Append(Tools.JsonPair("typeFix", typeFix)).Append(",");
        filter.Append(Tools.JsonPair("typePrevent", typePrevent)).Append(",");
        filter.Append(Tools.JsonPair("reporter", reporter)).Append(",");
        filter.Append(Tools.JsonPair("origin", origin)).Append("}");
        Session["IncidentActionFilter"] = filter.ToString();
        return(IncidentAction.FilterList(companyId, from, to, statusIdnetified, statusAnalyzed, statusInProgress, statusClose, typeImprovement, typeFix, typePrevent, origin, reporter));
    }
Beispiel #8
0
        public static ActionResult Inactivate(int oportunityId, int companyId, int applicationUserId)
        {
            var res = ActionResult.NoAction;

            using (var cmd = new SqlCommand("Oportunity_Inactivate"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cns"].ConnectionString))
                {
                    cmd.Connection = cnn;
                    cmd.Parameters.Add(DataParameter.Input("Id", oportunityId));
                    cmd.Parameters.Add(DataParameter.Input("CompanyId", companyId));
                    cmd.Parameters.Add(DataParameter.Input("ApplicationUserId", applicationUserId));
                    try
                    {
                        cmd.Connection.Open();
                        cmd.ExecuteNonQuery();
                        res.SetSuccess();
                        if (res.Success)
                        {
                            Tools.DeleteAttachs(companyId, "Oportunity", oportunityId);
                        }

                        var action = IncidentAction.ByOportunityId(oportunityId, companyId);
                        if (action != null)
                        {
                            action.CompanyId = companyId;
                            action.Delete(applicationUserId);
                        }
                    }
                    finally
                    {
                        if (cmd.Connection.State != ConnectionState.Closed)
                        {
                            cmd.Connection.Close();
                        }
                    }
                }
            }

            return(res);
        }
    private void RenderActionHistory()
    {
        var incidentActionCollection = IncidentAction.ByOportunityCode(this.Oportunity.Code, this.Company.Id);
        var res = new StringBuilder();

        //var searchItem = new List<string>();
        foreach (var incidentAction in incidentActionCollection.Where(ia => ia.Oportunity.Id != this.OportunityId).OrderBy(incidentAction => incidentAction.WhatHappenedOn))
        {
            //if (!searchItem.Contains(incidentAction.Description))
            //{
            //    searchItem.Add(incidentAction.Description);
            //}

            res.Append(incidentAction.ListBusinessRiskRow(this.Dictionary, this.ApplicationUser.Grants));

            //if (incidentAction.Oportunity.Id != this.OportunityId)
            //{
            historyActionActive = true;
            //}
        }

        this.OportunityActionData.Text = res.ToString();
    }
    /// <summary>Main action to load page elements</summary>
    private void Go()
    {
        this.Company         = this.Session["company"] as Company;
        this.Dictionary      = this.Session["Dictionary"] as Dictionary <string, string>;
        this.ApplicationUser = this.Session["User"] as ApplicationUser;
        this.Session["User"] = this.ApplicationUser;

        if (this.Request.QueryString["id"] != null)
        {
            this.OportunityId = Convert.ToInt64(this.Request.QueryString["id"]);
        }

        string label = "Item_Oportunity";

        this.master           = this.Master as Giso;
        this.master.AdminPage = true;
        //this.master.Titulo = label;
        string serverPath = this.Request.Url.AbsoluteUri.Replace(this.Request.RawUrl.Substring(1), string.Empty);

        if (this.ApplicationUser.HasGrantToRead(ApplicationGrant.Oportunity))
        {
            this.master.AddBreadCrumb("Item_BusinessRisksAndOportunities", "BusinessRisksList.aspx", Constant.NotLeaft);
        }
        else
        {
            this.master.AddBreadCrumb("Item_Oportunity_Detail");
        }

        this.master.AddBreadCrumb("Item_Oportunity_Detail");
        if (!this.Page.IsPostBack)
        {
            //this.LtTrazas.Text = ActivityTrace.RenderTraceTableForItem(this.businessRisk, TargetTypes.BusinessRisk);
        }

        this.formFooter = new FormFooter();
        this.formFooter.AddButton(new UIButton {
            Id = "BtnPrint", Icon = "icon-file-pdf", Text = this.Dictionary["Common_PrintPdf"], Action = "success"
        });
        this.formFooter.AddButton(new UIButton {
            Id = "BtnSave", Icon = "icon-ok", Action = "success", Text = this.Dictionary["Common_Accept"]
        });
        this.formFooter.AddButton(new UIButton {
            Id = "BtnCancel", Icon = "icon-undo", Text = this.Dictionary["Common_Cancel"]
        });

        this.formFooterActions = new FormFooter();
        this.formFooterActions.AddButton(new UIButton {
            Id = "BtnSave2", Icon = "icon-ok", Action = "success", Text = this.Dictionary["Common_Accept"]
        });
        this.formFooterActions.AddButton(new UIButton {
            Id = "BtnCancel2", Icon = "icon-undo", Text = this.Dictionary["Common_Cancel"]
        });

        if (this.OportunityId != -1)
        {
            this.Oportunity     = Oportunity.ById(this.OportunityId, this.Company.Id);
            this.IncidentAction = IncidentAction.ByOportunityId(this.Oportunity.Id, this.Company.Id);
            if (this.Oportunity.CompanyId != this.Company.Id)
            {
                this.Response.Redirect("NoAccesible.aspx", Constant.EndResponse);
                Context.ApplicationInstance.CompleteRequest();
                this.Oportunity = Oportunity.Empty;
            }

            this.formFooter.ModifiedBy = this.Oportunity.ModifiedBy.Description;
            this.formFooter.ModifiedOn = this.Oportunity.ModifiedOn;
            label = string.Format(CultureInfo.InvariantCulture, "{0}: <strong>{1}</strong>", this.Dictionary["Item_Oportunity"], this.Oportunity.Description);
            this.master.TitleInvariant = true;
            this.master.Titulo         = label;
        }
        else
        {
            this.master.Titulo         = this.Dictionary["Item_Oportunity_Detail"];
            this.master.TitleInvariant = true;
            this.Oportunity            = Oportunity.Empty;
            this.IncidentAction        = IncidentAction.Empty;
        }

        this.RenderProcess();
        this.RenderLimit();
        this.RenderProbabilitySeverity();
        this.RenderActionsForm();
        this.RenderActionHistory();
        this.RenderDocuments();

        this.tabBar.AddTab(new Tab {
            Id = "home", Selected = true, Active = true, Label = this.Dictionary["Item_Oportunity_Tab_Basic"], Available = true
        });
        this.tabBar.AddTab(new Tab {
            Id = "accion", Available = this.ApplicationUser.HasGrantToRead(ApplicationGrant.IncidentActions), Active = true, Label = this.Dictionary["Item_Oportunity_Tab_Action"], Hidden = true
        });
        this.tabBar.AddTab(new Tab {
            Id = "costes", Available = this.ApplicationUser.HasGrantToRead(ApplicationGrant.IncidentActions) && this.ApplicationUser.HasGrantToRead(ApplicationGrant.Cost), Active = true, Label = this.Dictionary["Item_Oportunity_Tab_Costs"], Hidden = true
        });
        this.tabBar.AddTab(new Tab {
            Id = "graphic", Available = true, Active = true, Label = this.Dictionary["Item_Oportunity_Tab_Graphics"], Hidden = true
        });
        this.tabBar.AddTab(new Tab {
            Id = "historyActions", Available = this.ApplicationUser.HasGrantToRead(ApplicationGrant.IncidentActions), Active = historyActionActive == true, Label = this.Dictionary["Item_Oportunity_Tab_HistoryActions"], Hidden = !historyActionActive
        });
        this.tabBar.AddTab(new Tab {
            Id = "uploadFiles", Available = true, Active = true, Label = this.Dictionary["Item_Oportunity_Tab_UploadFiles"], Hidden = this.Oportunity.Id < 1
        });
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        long actionId   = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company    = new Company(companyId);
        var  res        = ActionResult.NoAction;
        var  user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  action     = IncidentAction.ById(actionId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(action.Description);

        formatedDescription = formatedDescription.Replace(@"\", "/");

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_IncidentAction"],
            formatedDescription,
            DateTime.Now);

        string type         = string.Empty;
        string origin       = string.Empty;
        string originSufix  = string.Empty;
        string reporterType = string.Empty;
        string reporter     = string.Empty;

        if (action.ActionType == 1)
        {
            type = dictionary["Item_IncidentAction_Type1"];
        }
        if (action.ActionType == 2)
        {
            type = dictionary["Item_IncidentAction_Type2"];
        }
        if (action.ActionType == 3)
        {
            type = dictionary["Item_IncidentAction_Type3"];
        }

        if (action.Origin == 1)
        {
            origin = dictionary["Item_IncidentAction_Origin1"];
        }
        if (action.Origin == 2)
        {
            origin = dictionary["Item_IncidentAction_Origin2"];
        }
        if (action.Origin == 3)
        {
            if (action.IncidentId.HasValue)
            {
                var incident = Incident.GetById(action.IncidentId.Value, action.CompanyId);
                origin = string.Format(
                    CultureInfo.InvariantCulture,
                    @"{0}: {1}",
                    dictionary["Item_Incident"],
                    incident.Description);
            }
        }

        if (action.Origin == 4)
        {
            if (action.BusinessRiskId.HasValue)
            {
                if (action.BusinessRiskId > Constant.DefaultId)
                {
                    var businessRisk = BusinessRisk.ById(action.CompanyId, action.BusinessRiskId.Value);
                    origin      = businessRisk.Description;
                    originSufix = " (" + dictionary["Item_BusinessRisk"] + ")";
                }
            }
        }
        if (action.Origin == 5)
        {
            if (action.ObjetivoId.HasValue)
            {
                if (action.ObjetivoId > Constant.DefaultId)
                {
                    var objetivo = Objetivo.ById(Convert.ToInt32(action.ObjetivoId.Value), action.CompanyId);
                    origin      = objetivo.Name;
                    originSufix = " (" + dictionary["Item_Objetivo"] + ")";
                }
            }
        }
        if (action.Origin == 6)
        {
            if (action.Oportunity.Id > Constant.DefaultId)
            {
                var oportunidad = Oportunity.ById(Convert.ToInt32(action.Oportunity.Id), action.CompanyId);
                origin      = oportunidad.Description;
                originSufix = " (" + dictionary["Item_Oportunity"] + ")";
            }
        }
        else
        {
            switch (action.ReporterType)
            {
            case 1:
                reporterType = dictionary["Item_IncidentAction_ReporterType1"];
                if (action.Department != null && action.Department.Id > 0)
                {
                    var department = Department.ById(action.Department.Id, action.CompanyId);
                    reporter = department.Description;
                }
                break;

            case 2:
                reporterType = dictionary["Item_IncidentAction_ReporterType2"];
                if (action.Provider != null && action.Provider.Id > 0)
                {
                    var provider = Provider.ById(action.Provider.Id, action.CompanyId);
                    reporter = provider.Description;
                }
                break;

            case 3:
                reporterType = dictionary["Item_IncidentAction_ReporterType3"];
                if (action.Customer != null && action.Customer.Id > 0)
                {
                    var customer = Customer.ById(action.Customer.Id, action.CompanyId);
                    reporter = customer.Description;
                }
                break;

            default:
                break;
            }
        }

        string status   = string.Empty;
        var    document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55);
        var    writer   = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = action.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_IncidentAction"].ToUpperInvariant()
        };

        document.Open();
        var styles = new iTextSharp.text.html.simpleparser.StyleSheet();
        var hw     = new iTextSharp.text.html.simpleparser.HTMLWorker(document);

        var widths = new float[] { 15f, 30f, 15f, 30f };
        var table  = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(widths);
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;

        var alignLeft  = Element.ALIGN_LEFT;
        var alignRight = Element.ALIGN_RIGHT;

        var labelFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.DARK_GRAY);
        var valueFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.BLACK);

        // Descripción
        table.AddCell(LabelCell(dictionary["Item_IncidentAction"], Rectangle.NO_BORDER));
        table.AddCell(ValueCell(action.Number.ToString() + " - " + action.Description, ToolsPdf.BorderNone, alignLeft, 3));

        // Tipo
        table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Type"], Rectangle.NO_BORDER));
        table.AddCell(ValueCell(type, ToolsPdf.BorderNone, alignLeft, 1));

        // Origen
        table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Origin"], Rectangle.NO_BORDER));
        table.AddCell(ValueCell(origin + originSufix, ToolsPdf.BorderNone, alignLeft, 3));

        // Reportador
        if (action.Origin != 4 && action.Origin != 5 && !string.IsNullOrEmpty(reporter))
        {
            table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Reporter"], Rectangle.NO_BORDER));
            table.AddCell(ValueCell(reporterType + " (" + reporter + ")", ToolsPdf.BorderNone, alignLeft, 3));
        }

        // WhatHappend
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4));
        table.AddCell(BlankRow());
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2));

        // Causes
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4));
        table.AddCell(BlankRow());
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.CausesBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.CausesOn), borderBR, alignRight, 2));

        // Actions
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4));
        table.AddCell(BlankRow());
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.ActionsBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_DateExecution"], action.ActionsOn), borderBR, alignRight, 2));

        // Monitoring
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, ToolsPdf.BorderAll, alignLeft, 4));

        // Close
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], action.ClosedBy.FullName), borderTBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1:dd/MM/yyyy}", dictionary["Common_DateClose"], action.ClosedOn), borderTBR, alignRight, 2));

        // Notes
        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + action.Notes, ToolsPdf.BorderAll, alignLeft, 4));

        document.Add(table);

        // Costes
        var costs = IncidentActionCost.GetByIncidentActionId(actionId, companyId);

        if (costs.Count > 0)
        {
            var times           = new Font(arial, 8, Font.NORMAL, BaseColor.BLACK);
            var fontSummary     = new Font(arial, 9, Font.BOLD, BaseColor.BLACK);
            var headerFontFinal = new Font(headerFont, 9, Font.NORMAL, BaseColor.BLACK);

            // @alex: hay que crear la tabla con 6 columnas en lugar de 5
            //var tableCosts = new PdfPTable(5)
            var tableCosts = new PdfPTable(6)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 1,
                SpacingBefore       = 20f,
                SpacingAfter        = 30f
            };

            // @alex: se añade una nueva columna de 10f para la fecha
            //tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 20f });
            tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 10f, 20f });

            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"]));
            // @alex: se añade una nueva cabecera
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Date"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"]));

            decimal total       = 0;
            decimal totalAccion = 0;
            int     cont        = 0;
            int     contAccion  = 0;

            // Acciones
            foreach (var cost in costs.Where(c => c.Active == true))
            {
                tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times));

                // @alex: se añade la columna en la misma posición que en el listado de la ficha
                tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Date, times));

                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times));
                total      += cost.Amount * cost.Quantity;
                totalAccion = cost.Amount * cost.Quantity;
                cont++;
                contAccion++;
            }

            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                           CultureInfo.InvariantCulture,
                                                           @"{0} {2}: {1}",
                                                           dictionary["Common_RegisterCount"],
                                                           contAccion,
                                                           dictionary["Item_IncidentAction"]), times))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 3//@ alex: al haber una columna más el colspan crece de 2 a 3
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(total), times))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT,
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times)))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 1
            });


            document.SetPageSize(PageSize.A4.Rotate());
            document.NewPage();
            document.Add(tableCosts);
        }

        document.Close();

        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Accion.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Beispiel #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var alignRight  = Element.ALIGN_RIGHT;

        long oportunityId = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId    = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company      = new Company(companyId);
        var  res          = ActionResult.NoAction;
        var  user         = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary   = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  oportunity   = Oportunity.ById(oportunityId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(oportunity.Description);

        var alignLeft = Element.ALIGN_LEFT;

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Oportunity"],
            formatedDescription,
            DateTime.Now);

        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);
        var document        = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = oportunity.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Oportunity"]
        };

        writer.PageEvent = pageEventHandler;
        document.Open();

        #region Dades bàsiques
        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 50f, 30f, 50f });

        table.AddCell(new PdfPCell(new Phrase(oportunity.Description, descriptionFont))
        {
            Colspan             = 4,
            Border              = Rectangle.NO_BORDER,
            PaddingTop          = 10f,
            PaddingBottom       = 10f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });

        table.AddCell(TitleCell(dictionary["Item_BusinessRisk_Tab_Basic"], 4));

        table.AddCell(TitleLabel(dictionary["Item_BusinessRisk_LabelField_DateStart"]));
        table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", oportunity.DateStart)));

        table.AddCell(TitleLabel(dictionary["Item_Process"]));
        table.AddCell(TitleData(oportunity.Process.Description));

        table.AddCell(TitleLabel(dictionary["Item_Rule"]));
        table.AddCell(TitleData(oportunity.Rule.Description));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"]));
        table.AddCell(TitleData(oportunity.Rule.Limit.ToString()));

        string costText = oportunity.Cost.ToString();
        if (costText == "0")
        {
            costText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"]));
        table.AddCell(TitleData(costText));

        string impactText = oportunity.Impact.ToString();
        if (impactText == "0")
        {
            impactText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"]));
        table.AddCell(TitleData(impactText));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"]));
        table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"]));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Description"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Description, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Causes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Causes, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Control"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Control, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Notes, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());

        table.AddCell(TitleCell(dictionary["Item_Oportunity_Tab_Graphics"], 4));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"]));
        table.AddCell(TitleData(oportunity.Rule.Limit.ToString()));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"]));
        table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"]));

        string finalCostText = oportunity.FinalCost.ToString();
        if (finalCostText == "0")
        {
            finalCostText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"]));
        table.AddCell(TitleData(finalCostText));

        string finalImpactText = oportunity.FinalImpact.ToString();
        if (finalImpactText == "0")
        {
            finalImpactText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"]));
        table.AddCell(TitleData(finalImpactText));

        document.Add(table);
        #endregion

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            // Añadir posible acción
            var action = IncidentAction.ByOportunityId(oportunity.Id, companyId);
            if (action.Id > 0)
            {
                var tableAction = new PdfPTable(4)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 0
                };

                tableAction.SetWidths(new float[] { 15f, 30f, 15f, 30f });

                // Descripción
                var headerFont = new Font(this.arial, 15, Font.NORMAL, BaseColor.BLACK);
                tableAction.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_PDF_ActionPageTitle"], headerFont))
                {
                    Colspan             = 4,
                    Border              = ToolsPdf.BorderBottom,
                    HorizontalAlignment = Rectangle.ALIGN_CENTER
                });
                tableAction.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Description"], Rectangle.NO_BORDER));
                tableAction.AddCell(ValueCell(action.Description, ToolsPdf.BorderNone, alignLeft, 3));

                // WhatHappend
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow());
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2));

                // Causes
                var causesFullName = string.Empty;
                var causesDate     = string.Empty;
                if (action.CausesBy != null)
                {
                    causesFullName = action.CausesBy.FullName;
                    causesDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CausesOn);
                }
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow());
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + causesFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_Date"], causesDate), borderBR, alignRight, 2));

                // Actions
                var actionFullName = string.Empty;
                var actionDate     = string.Empty;
                if (action.ActionsBy != null)
                {
                    actionFullName = action.ActionsBy.FullName;
                    actionDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ActionsOn);
                }
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow());
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + actionFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_DateExecution"], actionDate), borderBR, alignRight, 2));

                // Monitoring
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, ToolsPdf.BorderAll, alignLeft, 4));

                // Close
                var closedFullName = string.Empty;
                var closedDate     = string.Empty;
                if (action.ClosedBy != null)
                {
                    closedFullName = action.ClosedBy.FullName;
                    closedDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ClosedOn);
                }
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], closedFullName), borderTBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Common_DateClose"], closedDate), borderTBR, alignRight, 2));

                // Notes
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Notes, ToolsPdf.BorderAll, alignLeft, 4));

                document.NewPage();
                document.Add(tableAction);
            }

            #region Historico acciones
            var historico = IncidentAction.ByOportunityCode(oportunity.Code, company.Id).Where(ia => ia.Oportunity.Id != oportunity.Id).OrderBy(incidentAction => incidentAction.WhatHappenedOn).ToList();
            if (historico.Count > 0)
            {
                var backgroundColor = new iTS.BaseColor(225, 225, 225);
                var rowPair         = new iTS.BaseColor(255, 255, 255);
                var rowEven         = new iTS.BaseColor(240, 240, 240);
                var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableHistoric = new iTSpdf.PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableHistoric.SetWidths(new float[] { 20f, 30f, 120f, 20f, 20f });

                tableHistoric.AddCell(new PdfPCell(new Phrase(dictionary["Item_BusinessRisk_Tab_HistoryActions"], descriptionFont))
                {
                    Colspan             = 5,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK);
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Close"]));

                int cont = 0;
                foreach (var accion in historico)
                {
                    string statusText = dictionary["Item_Incident_Status1"];

                    if (accion.CausesOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status2"];
                    }

                    if (accion.ActionsOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status3"];
                    }

                    if (accion.ClosedOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status4"];
                    }

                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.WhatHappenedOn, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCell(statusText, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCell(accion.Description, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ActionsOn, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ClosedOn, ToolsPdf.LayoutFonts.Times));

                    cont++;
                }

                tableHistoric.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times))
                {
                    Border  = ToolsPdf.BorderTop,
                    Colspan = 5,
                    Padding = 8f
                });

                document.Add(tableHistoric);
            }
            #endregion

            #region Costes
            var costs = IncidentActionCost.ByOportunityId(oportunity.Id, company.Id);
            if (costs.Count > 0)
            {
                var backgroundColor = new iTS.BaseColor(225, 225, 225);
                var rowPair         = new iTS.BaseColor(255, 255, 255);
                var rowEven         = new iTS.BaseColor(240, 240, 240);
                var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableCost = new iTSpdf.PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableCost.SetWidths(new float[] { 90f, 40f, 30f, 60f, 20f });

                tableCost.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_Tab_Costs"], descriptionFont))
                {
                    Colspan             = 5,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK);
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"]));

                int     cont      = 0;
                decimal costTotal = 0;
                foreach (var cost in costs)
                {
                    tableCost.AddCell(ToolsPdf.DataCell(cost.Description, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount * cost.Quantity, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCell(cost.Responsible.FullName, ToolsPdf.LayoutFonts.Times));

                    costTotal += cost.Amount * cost.Quantity;
                    cont++;
                }

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times))
                {
                    Border  = ToolsPdf.BorderTop,
                    Colspan = 2,
                    Padding = 8f
                });

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(costTotal), ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });



                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });

                document.Add(tableCost);
            }

            #endregion
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Beispiel #13
0
    public static ActionResult PDF(
        int companyId,
        string from,
        string to,
        bool statusIdnetified,
        bool statusAnalyzed,
        bool statusInProgress,
        bool statusClose,
        int origin,
        int departmentId,
        int providerId,
        int customerId,
        string listOrder,
        string filterText)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);
        var fileName            = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_IncidentList"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_IncidentList"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair         = new iTS.BaseColor(255, 255, 255);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        // ------------ FONTS
        var awesomeFont     = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\fontawesome-webfont.ttf", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

        criteriaFont = new iTS.Font(arial, 10, iTS.Font.NORMAL, iTS.BaseColor.BLACK);
        var titleFont  = new iTS.Font(arial, 18, iTS.Font.BOLD, iTS.BaseColor.BLACK);
        var symbolFont = new iTS.Font(awesomeFont, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

        var fontAwesomeIcon = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\fontawesome-webfont.ttf", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        fontAwe = new Font(fontAwesomeIcon, 10);
        // -------------------

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), titleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        var borderNone = iTS.Rectangle.NO_BORDER;

        #region Criteria
        var criteriatable = new iTSpdf.PdfPTable(2)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 8f, 50f });

        #region texts

        var criteriaOrigin = dictionary["Item_Incident_Origin0"];
        if (origin == 1)
        {
            if (departmentId > 0)
            {
                var department = Department.ById(departmentId, companyId);
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin1"], department.Description);
            }
            else
            {
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin1"], dictionary["Common_All_Male_Plural"]);
            }
        }
        if (origin == 2)
        {
            if (providerId > 0)
            {
                var provider = Provider.ById(providerId, companyId);
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin2"], provider.Description);
            }
            else
            {
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin2"], dictionary["Common_All_Male_Plural"]);
            }
        }
        if (origin == 3)
        {
            if (customerId > 0)
            {
                var customer = Customer.ById(customerId, companyId);
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin3"], customer.Description);
            }
            else
            {
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin3"], dictionary["Common_All_Male_Plural"]);
            }
        }

        var periode = string.Empty;
        if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_Incident_List_Filter_From"] + " " + from;
        }
        else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_Incident_List_Filter_To"] + " " + to;
        }
        else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = from + " " + to;
        }
        else
        {
            periode = dictionary["Common_All_Male"];
        }

        var typetext  = string.Empty;
        var firstType = false;

        var statusText  = string.Empty;
        var firstStatus = true;
        if (statusIdnetified)
        {
            firstStatus = false;
            statusText += dictionary["Item_IndicentAction_Status1"];
        }
        if (statusAnalyzed)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }

            statusText += dictionary["Item_IndicentAction_Status2"];
            firstStatus = false;
        }
        if (statusInProgress)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }

            statusText += dictionary["Item_IndicentAction_Status3"];
            firstType   = false;
        }
        if (statusClose)
        {
            if (!firstType)
            {
                statusText += " - ";
            }

            statusText += dictionary["Item_IndicentAction_Status4"];
            firstType   = false;
        }
        #endregion

        ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode);
        if (!string.IsNullOrEmpty(filterText))
        //{
        //    ToolsPdf.AddCriteria(criteriatable, string.Empty, string.Empty);
        //}
        //else
        {
            ToolsPdf.AddCriteria(criteriatable, dictionary["Common_PDF_Filter_Contains"], filterText);
        }

        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Origin"], criteriaOrigin);
        pdfDoc.Add(criteriatable);
        #endregion

        var table = new iTSpdf.PdfPTable(8)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 5f, 35f, 10f, 10f, 20f, 8f, 10f, 10f });

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Label_Number"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Open"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Origin"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_ActionNumber"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Cost"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Close"]));

        int     cont      = 0;
        decimal totalCost = 0;
        var     data      = HttpContext.Current.Session["IncidentFilterData"] as List <IncidentFilterItem>;
        bool    pair      = false;

        foreach (IncidentFilterItem item in data)
        {
            var originValue = string.Empty;
            if (!string.IsNullOrEmpty(item.Customer.Description))
            {
                originValue = item.Customer.Description;
            }
            if (!string.IsNullOrEmpty(item.Provider.Description))
            {
                originValue = item.Provider.Description;
            }
            if (!string.IsNullOrEmpty(item.Department.Description))
            {
                originValue = item.Department.Description;
            }

            item.OriginText = originValue;
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.Open).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.Open).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.OriginText).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.OriginText).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.Action.Description).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.Action.Description).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.Amount).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.Amount).ToList();
            break;

        case "TH6|ASC":
            data = data.OrderBy(d => d.Close).ToList();
            break;

        case "TH6|DESC":
            data = data.OrderByDescending(d => d.Close).ToList();
            break;
        }

        foreach (var incidentFilter in data)
        {
            if (!string.IsNullOrEmpty(filterText))
            {
                var match = incidentFilter.Description;
                match += "|" + incidentFilter.Code;
                match += "|" + incidentFilter.Customer.Description;
                match += "|" + incidentFilter.Provider.Description;
                match += "|" + incidentFilter.Department.Description;


                if (match.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1)
                {
                    continue;
                }
            }

            cont++;
            totalCost += incidentFilter.Amount;
            var incident = Incident.GetById(incidentFilter.Id, companyId);
            var action   = IncidentAction.ByIncidentId(incident.Id, companyId);

            var lineBackground = pair ? rowEven : rowPair;
            // pair = !pair;

            var statustext = string.Empty;
            switch (incidentFilter.Status)
            {
            case 1: statustext = dictionary["Item_IndicentAction_Status1"]; break;

            case 2: statustext = dictionary["Item_IndicentAction_Status2"]; break;

            case 3: statustext = dictionary["Item_IndicentAction_Status3"]; break;

            case 4: statustext = dictionary["Item_IndicentAction_Status4"]; break;

            default: statusText = string.Empty; break;
            }

            var actionDescription = string.Empty;
            if (!string.IsNullOrEmpty(action.Description))
            {
                actionDescription = dictionary["Common_Yes"];
            }

            var originText = string.Empty;
            switch (incidentFilter.Origin)
            {
            case 1: originText = dictionary["Item_IncidentAction_Origin1"]; break;

            case 2: originText = dictionary["Item_IncidentAction_Origin2"]; break;

            case 3: originText = dictionary["Item_IncidentAction_Origin3"]; break;

            case 4: originText = dictionary["Item_IncidentAction_Origin4"]; break;

            default: originText = string.Empty; break;
            }

            table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Code, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(incidentFilter.Description, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Open, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(statustext, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(incidentFilter.OriginText, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(actionDescription, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellMoney(incidentFilter.Amount, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Close, ToolsPdf.LayoutFonts.Times));
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 4
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(totalCost), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Colspan         = 2
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
 public ActionResult Restore(int incidentActionId, int companyId, int applicationUserId)
 {
     return(IncidentAction.Restore(incidentActionId, companyId, applicationUserId));
 }
 public ActionResult Anulate(int incidentActionId, int companyId, int applicationUserId, DateTime date, int responsible)
 {
     return(IncidentAction.Anulate(incidentActionId, companyId, applicationUserId, date, responsible));
 }
Beispiel #16
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var incidentId = Convert.ToInt64(Request.QueryString["id"]);
        var companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var company    = new Company(companyId);
        var res        = ActionResult.NoAction;
        var user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var incident   = Incident.GetById(incidentId, user.CompanyId);
        var path       = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(incident.Description);

        var fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Incident"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        string type         = string.Empty;
        string origin       = string.Empty;
        string originSufix  = string.Empty;
        string reporterType = string.Empty;
        string reporter     = string.Empty;

        if (incident.Origin == 1)
        {
            origin = dictionary["Item_Incident_Origin1"];
        }
        if (incident.Origin == 2)
        {
            origin = dictionary["Item_Incident_Origin2"];
        }
        if (incident.Origin == 3)
        {
            origin = dictionary["Item_Incident_Origin3"];
        }

        if (incident.Department.Id > 0)
        {
            reporterType = dictionary["Item_Incident_Origin1"];
            reporter     = Department.ById(incident.Department.Id, incident.CompanyId).Description;
        }
        else if (incident.Provider.Id > 0)
        {
            reporterType = dictionary["Item_Incident_Origin2"];
            reporter     = Provider.ById(incident.Provider.Id, incident.CompanyId).Description;
        }
        else if (incident.Customer.Id > 0)
        {
            reporterType = dictionary["Item_Incident_Origin3"];
            reporter     = Customer.ById(incident.Customer.Id, incident.CompanyId).Description;
        }

        string status = string.Empty;

        var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = incident.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Incident"]
        };

        pageEventHandler.Titles = new List <string>
        {
            dictionary["Item_IncidentAction"]
        };

        writer.PageEvent = pageEventHandler;
        document.Open();

        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 15f, 30f, 15f, 30f });

        var borderNone  = Rectangle.NO_BORDER;
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderAll   = Rectangle.RIGHT_BORDER + Rectangle.TOP_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;

        var alignLeft  = Element.ALIGN_LEFT;
        var alignRight = Element.ALIGN_RIGHT;

        var labelFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.DARK_GRAY);
        var valueFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.BLACK);

        // Descripción
        table.AddCell(LabelCell(dictionary["Item_Incident"], Rectangle.NO_BORDER));
        table.AddCell(ValueCell(incident.Code.ToString() + " - " + incident.Description, borderNone, alignLeft, 3));

        // Reportador
        if (incident.Origin != 4)
        {
            table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Reporter"], Rectangle.NO_BORDER));
            table.AddCell(ValueCell(reporterType + " (" + reporter + ")", borderNone, alignLeft, 3));
        }

        // WhatHappend
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.WhatHappened, borderSides, alignLeft, 4));
        table.AddCell(BlankRow(4));
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], incident.WhatHappenedOn), borderBR, alignRight, 2));

        // Causes
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.Causes, borderSides, alignLeft, 4));
        table.AddCell(BlankRow(4));
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.CausesBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], incident.CausesOn), borderBR, alignRight, 2));

        // Actions
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_Incident_Label_Actions"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.Actions, borderSides, alignLeft, 4));
        table.AddCell(BlankRow(4));
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.ActionsBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_DateExecution"], incident.ActionsOn), borderBR, alignRight, 2));

        // Close
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], incident.ClosedBy.FullName), borderTBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1:dd/MM/yyyy}", dictionary["Common_DateClose"], incident.ClosedOn), borderTBR, alignRight, 2));

        // Notes
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.Notes, borderAll, alignLeft, 4));

        document.Add(table);

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            // Añadir posible acción
            var action = IncidentAction.ByIncidentId(incident.Id, companyId);
            if (action.Id > 0)
            {
                var tableAction = new PdfPTable(4)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 0
                };

                tableAction.SetWidths(new float[] { 15f, 30f, 15f, 30f });

                // Descripción
                var headerFont = new Font(this.arial, 15, Font.NORMAL, BaseColor.BLACK);
                tableAction.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_PDF_ActionPageTitle"], headerFont))
                {
                    Colspan             = 4,
                    Border              = ToolsPdf.BorderBottom,
                    HorizontalAlignment = Rectangle.ALIGN_CENTER
                });
                tableAction.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Description"], Rectangle.NO_BORDER));
                tableAction.AddCell(ValueCell(action.Description, borderNone, alignLeft, 3));

                // WhatHappend
                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow(4));
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2));

                // Causes
                var causesFullName = string.Empty;
                var causesDate     = string.Empty;
                if (action.CausesBy != null)
                {
                    causesFullName = action.CausesBy.FullName;
                    causesDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CausesOn);
                }

                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow(4));
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + causesFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_Date"], causesDate), borderBR, alignRight, 2));

                // Actions
                var actionFullName = string.Empty;
                var actionDate     = string.Empty;
                if (action.ActionsBy != null)
                {
                    actionFullName = action.ActionsBy.FullName;
                    actionDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ActionsOn);
                }

                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow(4));
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + actionFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_DateExecution"], actionDate), borderBR, alignRight, 2));

                // Monitoring
                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, borderAll, alignLeft, 4));

                // Close
                var closedFullName = string.Empty;
                var closedDate     = string.Empty;
                if (action.ClosedBy != null)
                {
                    closedFullName = action.ClosedBy.FullName;
                    closedDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ClosedOn);
                }

                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], closedFullName), borderTBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Common_DateClose"], closedDate), borderTBR, alignRight, 2));

                // Notes
                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Notes, borderAll, alignLeft, 4));

                document.NewPage();
                document.Add(tableAction);
            }
        }

        // Costes
        var costs = IncidentCost.AllCosts(incidentId, companyId);

        if (costs.Count > 0)
        {
            var times           = new Font(arial, 8, Font.NORMAL, BaseColor.BLACK);
            var fontSummary     = new Font(arial, 9, Font.BOLD, BaseColor.BLACK);
            var headerFontFinal = new Font(headerFont, 9, Font.NORMAL, BaseColor.BLACK);
            var tableCosts      = new PdfPTable(5)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 1,
                SpacingBefore       = 20f,
                SpacingAfter        = 30f
            };

            tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 20f });

            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"]));

            decimal total           = 0;
            decimal totalIncidencia = 0;
            decimal totalAccion     = 0;
            int     cont            = 0;
            int     contIncidencia  = 0;
            int     contAccion      = 0;
            foreach (var cost in costs.Where(c => c.Source == "I"))
            {
                tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times));
                total           += cost.Amount * cost.Quantity;
                totalIncidencia += cost.Amount * cost.Quantity;
                cont++;
                contIncidencia++;
            }

            if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
            {
                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                               CultureInfo.InvariantCulture,
                                                               @"{0} {2}: {1}",
                                                               dictionary["Common_RegisterCount"],
                                                               contIncidencia,
                                                               dictionary["Item_Incident"]), times))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 2
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT,
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(totalIncidencia), times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT,
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times)))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 1
                });
            }

            if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
            {
                // Acciones
                foreach (var cost in costs.Where(c => c.Source == "A"))
                {
                    tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times));
                    tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times));
                    tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times));
                    tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times));
                    tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times));
                    total      += cost.Amount * cost.Quantity;
                    totalAccion = cost.Amount * cost.Quantity;
                    cont++;
                    contAccion++;
                }

                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                               CultureInfo.InvariantCulture,
                                                               @"{0} {2}: {1}",
                                                               dictionary["Common_RegisterCount"],
                                                               contAccion,
                                                               dictionary["Item_IncidentAction"]), times))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 2
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(totalAccion), times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT,
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times)))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 1
                });
            }

            // resumen
            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                           CultureInfo.InvariantCulture,
                                                           @"{0}: {1}",
                                                           dictionary["Common_RegisterCount"],
                                                           cont), fontSummary))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 2
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], fontSummary))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(total), fontSummary))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT,
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, fontSummary)))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 1
            });

            document.SetPageSize(PageSize.A4.Rotate());
            document.NewPage();
            document.Add(tableCosts);
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Incidencia.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Beispiel #17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        long auditoryId = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company    = new Company(companyId);
        var  res        = ActionResult.NoAction;
        var  user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  auditory   = Auditory.ById(auditoryId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }



        string formatedDescription = auditory.Description.Replace("?", string.Empty);

        formatedDescription = formatedDescription.Replace("#", string.Empty);
        formatedDescription = formatedDescription.Replace("/", string.Empty);
        formatedDescription = formatedDescription.Replace("\\", string.Empty);
        formatedDescription = formatedDescription.Replace(":", string.Empty);
        formatedDescription = formatedDescription.Replace(";", string.Empty);
        formatedDescription = formatedDescription.Replace(".", string.Empty);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Auditory"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);
        var document        = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = auditory.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Auditory"]
        };

        writer.PageEvent = pageEventHandler;
        document.Open();

        #region Dades bàsiques
        // Ficha pincipal

        var planning = AuditoryPlanning.ByAuditory(auditory.Id, auditory.CompanyId);
        var table    = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 50f, 30f, 50f });

        table.AddCell(new PdfPCell(new Phrase(auditory.Description, descriptionFont))
        {
            Colspan             = 4,
            Border              = Rectangle.NO_BORDER,
            PaddingTop          = 20f,
            PaddingBottom       = 20f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });


        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Type"]));
        table.AddCell(TitleData(dictionary["Item_Adutory_Type_Label_" + auditory.Type.ToString()]));

        if (auditory.Provider.Id > 0)
        {
            table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Provider"]));
            table.AddCell(TitleData(auditory.Provider.Description));
        }
        else if (auditory.Customer.Id > 0)
        {
            table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Customer"]));
            table.AddCell(TitleData(auditory.Customer.Description));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 2));
        }

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Rules"]));
        var  rulesText = string.Empty;
        bool firstRule = true;
        foreach (var rule in auditory.Rules)
        {
            if (firstRule)
            {
                firstRule = false;
            }
            else
            {
                rulesText += ", ";
            }

            rulesText += rule.Description;
        }
        table.AddCell(TitleData(rulesText, 3));

        var previewDateText = string.Empty;
        if (planning != null && planning.Count > 0)
        {
            previewDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", planning.OrderBy(p => p.Date).First().Date);
        }


        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_InternalResponsible"]));
        table.AddCell(TitleData(auditory.InternalResponsible.FullName, 3));

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PannedDate"]));
        //table.AddCell(TitleData(previewDateText));

        table.AddCell(TitleLabel(dictionary["Item_Audiotry_PDF_Planned"]));
        if (auditory.PlannedBy.Id > 0)
        {
            var planningText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.PlannedBy.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-");
            table.AddCell(TitleData(planningText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PlanningDate"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Closing"]));
        if (auditory.ClosedBy.Employee.Id > 0)
        {
            var closedText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.ClosedBy.Employee.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-");
            table.AddCell(TitleData(closedText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ClosedOn"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Validation"]));
        if (auditory.ValidatedBy.Id > 0)
        {
            var validatedText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.ValidatedBy.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-");
            table.AddCell(TitleData(validatedText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ValidatedOn"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Scope"]));
        table.AddCell(TitleData(auditory.Scope, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Address"]));
        table.AddCell(TitleData(auditory.EnterpriseAddress, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Notes"]));
        table.AddCell(TitleData(string.IsNullOrEmpty(auditory.Notes.Trim()) ? "-" : auditory.Notes, 3));

        document.Add(table);
        #endregion


        if (auditory.Status > 2)
        {
            var widthsPlanning = new float[] { 30f, 20f, 25f, 60f, 60f, 60f };
            var tablePlanning  = new PdfPTable(widthsPlanning.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tablePlanning.SetWidths(widthsPlanning);
            tablePlanning.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_PlanningTable_Title"], descriptionFont))
            {
                Colspan             = 6,
                Border              = Rectangle.NO_BORDER,
                PaddingTop          = 20f,
                PaddingBottom       = 20f,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Date"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Hour"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Duration"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Process"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Auditor"]));
            tablePlanning.AddCell(ToolsPdf.HeaderCell(dictionary["Item_AuditoryPlanning_Header_Audited"]));

            foreach (var pla in planning)
            {
                var hourText = string.Empty;
                var hours    = 0;
                var minutes  = pla.Hour;
                while (minutes > 59)
                {
                    hours++;
                    minutes -= 60;
                }
                hourText = string.Format(CultureInfo.InvariantCulture, "{0:0}:{1:00}", hours, minutes);

                var auditedText = pla.ProviderName;
                if (string.IsNullOrEmpty(auditedText))
                {
                    auditedText = pla.Audited.FullName;
                }

                tablePlanning.AddCell(ToolsPdf.DataCellCenter(pla.Date));
                tablePlanning.AddCell(ToolsPdf.DataCellCenter(hourText));
                tablePlanning.AddCell(ToolsPdf.DataCellCenter(pla.Duration));
                tablePlanning.AddCell(ToolsPdf.DataCell(pla.Process.Description));
                tablePlanning.AddCell(ToolsPdf.DataCell(pla.Auditor.Description));
                tablePlanning.AddCell(ToolsPdf.DataCell(auditedText));
            }

            document.Add(tablePlanning);

            document.SetPageSize(PageSize.A4.Rotate());
            document.NewPage();

            var widthsTroballes = new float[] { 30f, 30f, 20f, 8f };
            var tableTroballes  = new PdfPTable(widthsTroballes.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableTroballes.SetWidths(widthsTroballes);
            tableTroballes.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_Title_Found"], descriptionFont))
            {
                Colspan             = 4,
                Border              = Rectangle.NO_BORDER,
                PaddingTop          = 20f,
                PaddingBottom       = 20f,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Found"]));
            tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Requirement"]));
            tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Result"]));
            tableTroballes.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Action"]));

            var troballes = AuditoryCuestionarioFound.ByAuditory(auditory.Id, auditory.CompanyId);
            foreach (var troballa in troballes)
            {
                tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Text));
                tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Requeriment));
                tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Unconformity));
                tableTroballes.AddCell(ToolsPdf.DataCell(troballa.Action ? dictionary["Common_Yes"] : dictionary["Common_No"]));
            }

            document.Add(tableTroballes);



            var widthsMillores = new float[] { 80f, 8f };
            var tableMillores  = new PdfPTable(widthsMillores.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableMillores.SetWidths(widthsMillores);
            tableMillores.AddCell(new PdfPCell(new Phrase(dictionary["Item_Auditory_Title_Improvements"], descriptionFont))
            {
                Colspan             = 4,
                Border              = Rectangle.NO_BORDER,
                PaddingTop          = 20f,
                PaddingBottom       = 20f,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            tableMillores.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Improvement"]));
            tableMillores.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Auditory_Header_Action"]));

            var millores = AuditoryCuestionarioImprovement.ByAuditory(auditory.Id, auditory.CompanyId);
            foreach (var millora in millores)
            {
                tableMillores.AddCell(ToolsPdf.DataCell(millora.Text));
                tableMillores.AddCell(ToolsPdf.DataCell(millora.Action ? dictionary["Common_Yes"] : dictionary["Common_No"]));
            }

            document.Add(tableMillores);

            if (!string.IsNullOrEmpty(auditory.PuntosFuertes.Trim()))
            {
                document.Add(new Phrase(Environment.NewLine));
                document.Add(new Phrase(dictionary["Item_Auditory_Label_PuntosFuertes"], new Font(this.arial, 10, Font.BOLD, BaseColor.BLACK)));
                document.Add(new Phrase(Environment.NewLine));
                document.Add(new Phrase(auditory.PuntosFuertes));
            }

            var actions = IncidentAction.ByAuditoryId(auditory.Id, auditory.CompanyId);
            if (actions != null && actions.Count > 0)
            {
                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var widthsActions = new float[] { 8f, 80f };
                var tableActions  = new PdfPTable(widthsActions.Length)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 0
                };

                tableActions.SetWidths(widthsActions);
                tableActions.AddCell(new PdfPCell(new Phrase(dictionary["Item_IncidentActions"], descriptionFont))
                {
                    Colspan             = 4,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                tableActions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Type"]));
                tableActions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));

                foreach (var action in actions)
                {
                    string actionTypeText = string.Empty;
                    switch (action.ActionType)
                    {
                    default:
                    case 1: actionTypeText = dictionary["Item_IncidentAction_Type1"]; break;

                    case 2: actionTypeText = dictionary["Item_IncidentAction_Type2"]; break;

                    case 3: actionTypeText = dictionary["Item_IncidentAction_Type3"]; break;
                    }
                    tableActions.AddCell(ToolsPdf.DataCell(actionTypeText));
                    tableActions.AddCell(ToolsPdf.DataCell(action.Description));
                }

                document.Add(tableActions);
            }
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Beispiel #18
0
    /// <summary>Begin page running after session validations</summary>
    private void Go()
    {
        if (this.Request.QueryString["id"] != null)
        {
            this.IncidentId = Convert.ToInt64(this.Request.QueryString["id"]);
        }

        if (this.Request.QueryString["New"] != null)
        {
            this.ReturnScript = "document.location = 'IncidentList.aspx';";
        }
        else
        {
            this.ReturnScript = "document.location = referrer;";
        }

        this.formFooter       = new FormFooter();
        this.formFooterAction = new FormFooter();

        this.ApplicationUser  = (ApplicationUser)Session["User"];
        this.company          = (Company)Session["company"];
        this.Dictionary       = Session["Dictionary"] as Dictionary <string, string>;
        this.master           = this.Master as Giso;
        this.master.AdminPage = true;
        string serverPath = this.Request.Url.AbsoluteUri.Replace(this.Request.RawUrl.Substring(1), string.Empty);

        this.master.AddBreadCrumb("Item_Incidents", "IncidentList.aspx", Constant.NotLeaft);
        this.master.AddBreadCrumb("Item_Incident_Detail");
        this.grantToWrite = this.ApplicationUser.HasGrantToWrite(ApplicationGrant.Incident);

        if (this.IncidentId > 0)
        {
            this.Incident = Incident.GetById(this.IncidentId, this.company.Id);
            if (this.Incident.CompanyId != this.company.Id)
            {
                this.Response.Redirect("NoAccesible.aspx", Constant.EndResponse);
                Context.ApplicationInstance.CompleteRequest();
                this.Incident = Incident.Empty;
            }

            this.master.TitleInvariant = true;
            this.master.Titulo         = string.Format(CultureInfo.InvariantCulture, "{0}: <strong>{2} - {1}</strong>", this.Dictionary["Item_Incident"], this.Incident.Description, this.Incident.Code.ToString());

            this.formFooter.ModifiedBy = this.Incident.ModifiedBy.Description;
            this.formFooter.ModifiedOn = this.Incident.ModifiedOn;
            this.formFooter.AddButton(new UIButton {
                Id = "BtnPrint", Icon = "icon-file-pdf", Text = this.Dictionary["Common_PrintPdf"], Action = "success", ColumnsSpan = 12
            });
            this.formFooter.AddButton(new UIButton {
                Id = "BtnRestaurar", Icon = "icon-undo", Text = this.Dictionary["Item_Incident_Btn_Restaurar"], Action = "primary", Hidden = !this.Incident.ClosedOn.HasValue
            });
            this.formFooter.AddButton(new UIButton {
                Id = "BtnAnular", Icon = "icon-ban-circle", Text = this.Dictionary["Item_Incident_Btn_Anular"], Action = "danger", Hidden = this.Incident.ClosedOn.HasValue
            });
            this.formFooter.AddButton(new UIButton {
                Id = "BtnSave", Icon = "icon-ok", Text = this.Dictionary["Common_Accept"], Action = "success"
            });
            this.formFooter.AddButton(new UIButton {
                Id = "BtnCancel", Icon = "icon-undo", Text = this.Dictionary["Common_Cancel"]
            });

            this.master.ItemCode = this.Incident.Description;

            this.IncidentAction = IncidentAction.ByIncidentId(this.IncidentId, this.company.Id);

            this.formFooterAction.ModifiedBy = this.Incident.ModifiedBy.Description;
            this.formFooterAction.ModifiedOn = this.Incident.ModifiedOn;
            this.formFooterAction.AddButton(new UIButton {
                Id = "BtnRestaurarAction", Icon = "icon-undo", Text = this.Dictionary["Item_Incident_Btn_RestaurarAction"], Action = "primary"
            });
            this.formFooterAction.AddButton(new UIButton {
                Id = "BtnAnularAction", Icon = "icon-ban-circle", Text = this.Dictionary["Item_Incident_Btn_AnularAction"], Action = "danger"
            });
            this.formFooterAction.AddButton(new UIButton {
                Id = "BtnSaveAction", Icon = "icon-ok", Text = this.Dictionary["Common_Accept"], Action = "success"
            });
            this.formFooterAction.AddButton(new UIButton {
                Id = "BtnCancelAction", Icon = "icon-undo", Text = this.Dictionary["Common_Cancel"]
            });

            if (this.IncidentAction.Id == 0)
            {
                DateTime?today = DateTime.Now.Date;
                this.IncidentAction.WhatHappened   = this.Incident.WhatHappened;
                this.IncidentAction.WhatHappenedBy = this.Incident.WhatHappenedBy;
                this.IncidentAction.WhatHappenedOn = this.Incident.WhatHappenedOn == null ? null : today;
                this.IncidentAction.Causes         = this.Incident.Causes;
                this.IncidentAction.CausesBy       = this.Incident.CausesBy;
                this.IncidentAction.CausesOn       = this.Incident.CausesOn == null ? null : today;
                this.IncidentAction.Actions        = this.Incident.Actions;
                this.IncidentAction.ActionsBy      = this.Incident.ActionsBy;
                this.IncidentAction.ActionsOn      = this.IncidentAction.ActionsOn == null ? null : today;
                this.IncidentAction.ClosedBy       = this.Incident.ClosedBy;
                this.IncidentAction.ClosedOn       = this.Incident.ClosedOn == null ? null : today;
            }

            this.RenderDocuments();
        }
        else
        {
            this.master.Titulo         = "Item_Incident_Detail";
            this.Incident              = Incident.Empty;
            this.IncidentAction        = IncidentAction.Empty;
            this.formFooter.ModifiedBy = this.Dictionary["Common_New"];
            this.formFooter.ModifiedOn = DateTime.Now;
            this.formFooter.AddButton(new UIButton {
                Id = "BtnSave", Icon = "icon-ok", Text = this.Dictionary["Common_Accept"], Action = "success"
            });
            this.formFooter.AddButton(new UIButton {
                Id = "BtnCancel", Icon = "icon-undo", Text = this.Dictionary["Common_Cancel"]
            });

            this.formFooter.ModifiedBy = this.Dictionary["Common_New"];
            this.formFooter.ModifiedOn = DateTime.Now;
            this.formFooterAction.AddButton(new UIButton {
                Id = "BtnSaveAction", Icon = "icon-ok", Text = this.Dictionary["Common_Accept"], Action = "success"
            });
            this.formFooterAction.AddButton(new UIButton {
                Id = "BtnCancelAction", Icon = "icon-undo", Text = this.Dictionary["Common_Cancel"]
            });
        }

        this.tabBar.AddTab(new Tab {
            Id = "home", Selected = true, Active = true, Label = this.Dictionary["Item_Incident_Tab_Basic"], Available = true
        });
        this.tabBar.AddTab(new Tab {
            Id = "accion", Available = this.ApplicationUser.HasGrantToRead(ApplicationGrant.IncidentActions), Active = true, Hidden = this.IncidentId < 1, Label = this.Dictionary["Item_Incident_Tab_Action"]
        });
        this.tabBar.AddTab(new Tab {
            Id = "costes", Available = this.ApplicationUser.HasGrantToRead(ApplicationGrant.Cost) && this.IncidentId > 0, Hidden = this.IncidentId < 1, Active = this.IncidentId > 0, Label = this.Dictionary["Item_Incident_Tab_Costs"]
        });
        this.tabBar.AddTab(new Tab {
            Id = "uploadFiles", Available = true, Active = this.IncidentId > 0, Hidden = this.IncidentId < 1, Label = this.Dictionary["Item_Incident_Tab_UploadFiles"]
        });
        //// this.tabBar.AddTab(new Tab { Id = "trazas", Available = this.user.HasGrantToRead(ApplicationGrant.Trace) && this.IncidentId > 0, Active = this.IncidentId > 0, Label = this.dictionary["Item_Incident_Tab_Traces"] });

        this.RenderForm();
        this.RenderActionForm();

        this.ProviderBarPopups = new BarPopup()
        {
            Id                = "Provider",
            DeleteMessage     = this.Dictionary["Common_DeleteMessage"],
            BarWidth          = 600,
            UpdateWidth       = 600,
            DeleteWidth       = 600,
            Required          = true,
            RequiredMessage   = this.Dictionary["Common_Required"],
            Duplicated        = true,
            DuplicatedMessage = this.Dictionary["Common_Error_NameAlreadyExists"],
            Description       = "Proveedor",
            FieldName         = this.Dictionary["Common_Name"],
            BarTitle          = this.Dictionary["Item_Providers"]
        };

        this.CustomerBarPopups = new BarPopup()
        {
            Id                = "Customer",
            DeleteMessage     = this.Dictionary["Common_DeleteMessage"],
            BarWidth          = 600,
            UpdateWidth       = 600,
            DeleteWidth       = 600,
            Required          = true,
            RequiredMessage   = this.Dictionary["Common_Required"],
            Duplicated        = true,
            DuplicatedMessage = this.Dictionary["Common_Error_NameAlreadyExists"],
            Description       = "Cliente",
            FieldName         = this.Dictionary["Common_Name"],
            BarTitle          = this.Dictionary["Item_Customers"]
        };
    }
Beispiel #19
0
        public ActionResult BusinessRiskUpdate(BusinessRisk newBusinessRisk, int companyId, int userId)
        {
            var res = newBusinessRisk.Update(userId);

            if (res.Success)
            {
                if (newBusinessRisk.FinalDate.HasValue && newBusinessRisk.FinalAction == 3)
                {
                    var newBusinessRiskEvaluated = new BusinessRisk
                    {
                        Description            = newBusinessRisk.Description,
                        Code                   = newBusinessRisk.Code,
                        DateStart              = newBusinessRisk.FinalDate.Value,
                        Notes                  = newBusinessRisk.Notes,
                        ItemDescription        = newBusinessRisk.ItemDescription,
                        Causes                 = newBusinessRisk.Causes,
                        FinalSeverity          = 0,
                        FinalProbability       = 0,
                        FinalResult            = 0,
                        FinalDate              = null,
                        StartProbability       = newBusinessRisk.FinalProbability,
                        StartSeverity          = newBusinessRisk.FinalSeverity,
                        StartResult            = newBusinessRisk.FinalResult,
                        StartAction            = 3,
                        Active                 = true,
                        CompanyId              = newBusinessRisk.CompanyId,
                        PreviousBusinessRiskId = newBusinessRisk.Id,
                        Result                 = Convert.ToInt32(newBusinessRisk.FinalResult),
                        Process                = newBusinessRisk.Process,
                        ProcessId              = newBusinessRisk.Process.Id,
                        Rules                  = newBusinessRisk.Rules
                    };

                    res = newBusinessRiskEvaluated.Insert(userId);

                    var newUser = ApplicationUser.GetById(userId, companyId);

                    var newAction = new IncidentAction
                    {
                        IncidentId     = 0,
                        BusinessRiskId = newBusinessRiskEvaluated.Id,
                        Description    = newBusinessRisk.Description,
                        WhatHappened   = newBusinessRisk.ItemDescription,
                        WhatHappenedBy = newUser.Employee,
                        WhatHappenedOn = newBusinessRisk.FinalDate,
                        Causes         = newBusinessRiskEvaluated.Causes,
                        CausesBy       = newUser.Employee,
                        CausesOn       = newBusinessRisk.FinalDate,
                        CompanyId      = newBusinessRiskEvaluated.CompanyId,
                        ReporterType   = 1,
                        Origin         = 4,
                        ActionType     = 3
                    };

                    newAction.Insert(userId);
                }

                this.Session["Company"] = new Company(companyId);
            }

            return(res);
        }
Beispiel #20
0
    /// <summary>Begin page running after session validations</summary>
    private void Go()
    {
        if (this.Request.QueryString["id"] != null)
        {
            this.IncidentActionId = Convert.ToInt64(this.Request.QueryString["id"]);
        }

        if (this.Request.QueryString["New"] != null)
        {
            this.returnScript = "document.location = 'ActionsList.aspx';";
        }
        else
        {
            this.returnScript = "document.location = referrer;";
        }

        this.ApplicationUser  = Session["User"] as ApplicationUser;
        this.Company          = Session["company"] as Company;
        this.Dictionary       = Session["Dictionary"] as Dictionary <string, string>;
        this.master           = this.Master as Giso;
        this.master.AdminPage = true;
        string serverPath = this.Request.Url.AbsoluteUri.Replace(this.Request.RawUrl.Substring(1), string.Empty);

        if (this.ApplicationUser.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            this.master.AddBreadCrumb("Item_IncidentActions", "ActionList.aspx", Constant.NotLeaft);
        }
        else
        {
            this.master.AddBreadCrumb("Item_IncidentActions");
        }

        this.master.AddBreadCrumb("Item_IncidentActions_Detail");
        this.grantToWrite = this.ApplicationUser.HasGrantToWrite(ApplicationGrant.IncidentActions);
        this.Incident     = Incident.Empty;

        if (this.IncidentActionId > 0)
        {
            this.IncidentAction = IncidentAction.ById(this.IncidentActionId, this.Company.Id);
            if (this.IncidentAction.CompanyId != this.Company.Id)
            {
                this.Response.Redirect("NoAccesible.aspx", Constant.EndResponse);
                Context.ApplicationInstance.CompleteRequest();
                this.IncidentAction = IncidentAction.Empty;
            }

            this.master.TitleInvariant = true;
            this.master.Titulo         = string.Format(CultureInfo.InvariantCulture, "{0}: <strong>{2} - {1}</strong>", this.Dictionary["Item_IncidentAction"], this.IncidentAction.Description, this.IncidentAction.Number.ToString());

            this.formFooter = new FormFooter
            {
                ModifiedBy = this.IncidentAction.ModifiedBy.Description,
                ModifiedOn = this.IncidentAction.ModifiedOn
            };

            this.formFooter.AddButton(new UIButton {
                Id = "BtnRestaurar", Icon = "icon-undo", Text = this.Dictionary["Item_IncidentAction_Btn_Restaurar"], Action = "primary"
            });
            this.formFooter.AddButton(new UIButton {
                Id = "BtnAnular", Icon = "icon-ban-circle", Text = this.Dictionary["Item_IncidentAction_Btn_Anular"], Action = "danger"
            });
            this.formFooter.AddButton(new UIButton {
                Id = "BtnPrint", Icon = "icon-file-pdf", Text = this.Dictionary["Common_PrintPdf"], Action = "success", ColumnsSpan = 12
            });
            this.formFooter.AddButton(new UIButton {
                Id = "BtnSave", Icon = "icon-ok", Text = this.Dictionary["Common_Accept"], Action = "success", ColumnsSpan = 12
            });
            this.formFooter.AddButton(new UIButton {
                Id = "BtnCancel", Icon = "icon-undo", Text = this.Dictionary["Common_Cancel"], ColumnsSpan = 12
            });

            this.master.ItemCode = this.IncidentAction.Description;
            this.OriginItemLink  = this.Dictionary["Item_IncidentAction_Origin2"];

            if (this.IncidentAction.IncidentId.HasValue && this.IncidentAction.IncidentId > 0)
            {
                this.Incident       = Incident.GetById(this.IncidentAction.IncidentId.Value, this.Company.Id);
                this.OriginItemLink = this.Dictionary["Item_IncidentAction_Origin3"] + " " + this.Incident.Link;
            }

            if (this.IncidentAction.BusinessRiskId.HasValue && this.IncidentAction.BusinessRiskId > 0)
            {
                this.BusinessRisk   = BusinessRisk.ById(this.Company.Id, this.IncidentAction.BusinessRiskId.Value);
                this.OriginItemLink = this.Dictionary["Item_IncidentAction_Origin4"] + " " + this.BusinessRisk.Link;
            }

            if (this.IncidentAction.Objetivo.Id > 0)
            {
                this.Objetivo       = this.IncidentAction.Objetivo;
                this.OriginItemLink = this.Dictionary["Item_IncidentAction_Origin5"] + " " + this.Objetivo.Link;
            }

            if (this.IncidentAction.Oportunity.Id > 0)
            {
                this.Oportunity     = this.IncidentAction.Oportunity;
                this.OriginItemLink = this.Dictionary["Item_IncidentAction_Origin6"] + " " + this.Oportunity.Link;
            }

            if (this.IncidentAction.Origin == 1)
            {
                if (this.IncidentAction.AuditoryId != null && this.IncidentAction.AuditoryId > 0)
                {
                    var auditory = Auditory.ById(this.IncidentAction.AuditoryId.Value, this.Company.Id);
                    this.OriginItemLink = string.Format(
                        CultureInfo.InvariantCulture,
                        @"{0} - {1}",
                        this.Dictionary["Item_IncidentAction_Origin1"],
                        auditory.Link);
                }
                else
                {
                    this.OriginItemLink = this.Dictionary["Item_IncidentAction_Origin1"];
                }
            }

            this.RenderDocuments();
        }
        else
        {
            this.master.Titulo  = "Item_IncidentActions_Detail";
            this.IncidentAction = IncidentAction.Empty;
            this.formFooter     = new FormFooter(this.Dictionary, this.grantToWrite);

            if (this.Request.QueryString["o"] != null)
            {
                var objetivoId = Convert.ToInt32(this.Request.QueryString["o"]);
                this.Objetivo = Objetivo.ById(objetivoId, this.Company.Id);
                this.IncidentAction.Description    = this.Objetivo.Name;
                this.IncidentAction.Origin         = 5;
                this.IncidentAction.Objetivo       = this.Objetivo;
                this.IncidentAction.WhatHappened   = this.Objetivo.Description;
                this.IncidentAction.WhatHappenedOn = DateTime.Now;
            }

            this.OriginItemLink = this.Dictionary["Item_IncidentAction_Origin2"];

            if (this.IncidentAction.Origin == 1)
            {
                this.OriginItemLink = this.Dictionary["Item_IncidentAction_Origin1"];
            }
            else if (this.IncidentAction.Origin == 5)
            {
                this.OriginItemLink = string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}: {1}",
                    this.Dictionary["Item_IncidentAction_Origin5"],
                    this.Objetivo.Link);
            }
        }

        this.tabBar.AddTab(new Tab {
            Id = "home", Selected = true, Active = true, Label = this.Dictionary["Item_IncidentAction_Tab_Basic"], Available = true
        });
        this.tabBar.AddTab(new Tab {
            Id = "costes", Available = this.ApplicationUser.HasGrantToRead(ApplicationGrant.Cost) && this.IncidentActionId > 0, Active = this.IncidentActionId > 0, Label = this.Dictionary["Item_IncidentAction_Tab_Costs"]
        });
        this.tabBar.AddTab(new Tab {
            Id = "uploadFiles", Available = true, Active = this.IncidentActionId > 0, Hidden = this.IncidentActionId < 1, Label = this.Dictionary["Item_IncidentAction_Tab_UploadFiles"]
        });
        // this.tabBar.AddTab(new Tab { Id = "trazas", Available = this.user.HasTraceGrant() && this.IncidentActionId > 0, Active = this.IncidentActionId > 0, Label = this.dictionary["Item_IncidentAction_Tab_Traces"] });

        this.RenderForm();

        this.ProviderBarPopups = new BarPopup
        {
            Id                = "Provider",
            DeleteMessage     = this.Dictionary["Common_DeleteMessage"],
            BarWidth          = 600,
            UpdateWidth       = 600,
            DeleteWidth       = 600,
            Required          = true,
            RequiredMessage   = this.Dictionary["Common_Required"],
            Duplicated        = true,
            DuplicatedMessage = this.Dictionary["Common_Error_NameAlreadyExists"],
            Description       = "Proveedor",
            FieldName         = this.Dictionary["Item_Provider"],
            BarTitle          = this.Dictionary["Item_Providers"]
        };

        this.CustomerBarPopups = new BarPopup
        {
            Id                = "Customer",
            DeleteMessage     = this.Dictionary["Common_DeleteMessage"],
            BarWidth          = 600,
            UpdateWidth       = 600,
            DeleteWidth       = 600,
            Required          = true,
            RequiredMessage   = this.Dictionary["Common_Required"],
            Duplicated        = true,
            DuplicatedMessage = this.Dictionary["Common_Error_NameAlreadyExists"],
            Description       = "Cliente",
            FieldName         = this.Dictionary["Item_Customer"],
            BarTitle          = this.Dictionary["Item_Customers"]
        };
    }
Beispiel #21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int objetivoId = Convert.ToInt32(Request.QueryString["id"]);
        int companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var company    = new Company(companyId);
        var res        = ActionResult.NoAction;
        var user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var objetivo   = Objetivo.ById(objetivoId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(objetivo.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Objetivo"],
            formatedDescription,
            DateTime.Now);

        string type         = string.Empty;
        string origin       = string.Empty;
        string originSufix  = string.Empty;
        string reporterType = string.Empty;
        string reporter     = string.Empty;
        string status       = string.Empty;

        var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55);
        var writer   = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = objetivo.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Objetivo"].ToUpperInvariant()
        };

        document.Open();

        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 15f, 30f, 15f, 30f });

        ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Name"], objetivo.Name, 3);
        ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Responsible"], objetivo.Responsible.FullName, 3);
        ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_DateStart"], objetivo.StartDate);
        ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_ClosePreviewDate"], objetivo.PreviewEndDate);

        if (objetivo.VinculatedToIndicator)
        {
            var indicador = Indicador.ById(objetivo.IndicatorId.Value, companyId);
            ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Indicator"], indicador.Description);
            ToolsPdf.AddDataLabel(table, dictionary["Item_Objetivo_FieldLabel_Periodicity"], indicador.Periodicity);
        }

        AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Description"], objetivo.Description, 4);
        AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Methodology"], objetivo.Methodology, 4);
        AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Resources"], objetivo.Resources, 4);
        AddTextArea(table, dictionary["Item_Objetivo_FieldLabel_Notes"], objetivo.Notes, 4);

        document.Add(table);

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            #region Acciones
            if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
            {
                var acciones = IncidentAction.ByObjetivoId(objetivoId, companyId);
                if (acciones.Count > 0)
                {
                    document.SetPageSize(PageSize.A4.Rotate());
                    document.NewPage();

                    var tableAcciones = new PdfPTable(5)
                    {
                        WidthPercentage     = 100,
                        HorizontalAlignment = 1,
                        SpacingBefore       = 20f
                    };

                    tableAcciones.SetWidths(new float[] { 20f, 120f, 20f, 20f, 20f });
                    ToolsPdf.AddTableTitle(tableAcciones, dictionary["Item_Objetivo_ActionsReportTitle"]);
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"]));
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"]));
                    tableAcciones.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Cost"]));

                    int     cont          = 0;
                    decimal totalAcciones = 0;
                    foreach (var accion in acciones)
                    {
                        tableAcciones.AddCell(ToolsPdf.DataCell(accion.Status));
                        tableAcciones.AddCell(ToolsPdf.DataCell(accion.Description));
                        tableAcciones.AddCell(ToolsPdf.DataCell(accion.WhatHappenedOn));
                        tableAcciones.AddCell(ToolsPdf.DataCell(accion.ActionsOn));
                        tableAcciones.AddCell(ToolsPdf.DataCell(0));
                        cont++;
                        var costs = IncidentActionCost.GetByIncidentActionId(accion.Id, company.Id);
                        foreach (var cost in costs)
                        {
                            totalAcciones = cost.Amount;
                        }
                    }

                    // TotalRow
                    tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                    {
                        Border = Rectangle.TOP_BORDER,
                        HorizontalAlignment = Element.ALIGN_LEFT,
                        Padding             = 8f
                    });

                    tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold))
                    {
                        Border = Rectangle.TOP_BORDER,
                        HorizontalAlignment = Element.ALIGN_RIGHT,
                        Padding             = 8f
                    });

                    tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                    {
                        Border = Rectangle.TOP_BORDER,
                        HorizontalAlignment = Element.ALIGN_LEFT,
                        Padding             = 8f,
                        Colspan             = 2
                    });

                    tableAcciones.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", totalAcciones), ToolsPdf.LayoutFonts.TimesBold))
                    {
                        Border = Rectangle.TOP_BORDER,
                        HorizontalAlignment = Element.ALIGN_RIGHT,
                        Padding             = 8f
                    });

                    tableAcciones.AddCell(new PdfPCell(new Phrase(string.Empty))
                    {
                        Colspan = 3, Border = Rectangle.TOP_BORDER
                    });

                    document.Add(tableAcciones);
                }
            }
            #endregion
        }

        #region Registros
        if (objetivo.VinculatedToIndicator)
        {
            var registros = IndicadorRegistro.ByIndicadorId(objetivo.IndicatorId.Value, companyId).ToList();
            if (registros.Count > 0)
            {
                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableRegistros = new PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableRegistros.SetWidths(new float[] { 20f, 20f, 120f, 40f, 50f });
                ToolsPdf.AddTableTitle(tableRegistros, dictionary["Item_Objetivo_RecordsReportTitle"]);
                tableRegistros.AddCell(ToolsPdf.HeaderCell("*" + dictionary["Item_Indicador_TableRecords_Header_Value"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"]));

                int cont = 0;
                foreach (var registro in registros)
                {
                    string meta = dictionary["Common_Comparer_" + registro.MetaComparer] + " " + registro.Meta.ToString();
                    // WEKE ALEX: con datacellmoney el dato debe ser decimal y lo poen con dos decimales
                    tableRegistros.AddCell(ToolsPdf.DataCellMoney(registro.Value));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Date));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Comments));
                    tableRegistros.AddCell(ToolsPdf.DataCell(meta));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName));
                    cont++;
                }

                // TotalRow
                tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_LEFT,
                    Padding             = 8f
                });

                tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    Padding             = 8f
                });

                tableRegistros.AddCell(new PdfPCell(new Phrase(string.Empty))
                {
                    Colspan = 3, Border = Rectangle.TOP_BORDER
                });

                document.Add(tableRegistros);
            }
        }
        else
        {
            var registros = ObjetivoRegistro.GetByObjetivo(objetivoId, companyId).ToList();
            if (registros.Count > 0)
            {
                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableRegistros = new PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableRegistros.SetWidths(new float[] { 20f, 120f, 20f, 40f, 50f });

                tableRegistros.AddCell(new PdfPCell(new Phrase(dictionary["Item_Objetivo_RecordsReportTitle"]))
                {
                    Colspan             = 5,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Value"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Date"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Comments"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Meta"]));
                tableRegistros.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Indicador_TableRecords_Header_Responsible"]));

                int cont = 0;
                foreach (var registro in registros)
                {
                    string meta = dictionary["Common_Comparer_" + registro.MetaComparer] + " " + registro.Meta.ToString();
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Value));
                    tableRegistros.AddCell(ToolsPdf.DataCellCenter(registro.Date));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Comments));
                    tableRegistros.AddCell(ToolsPdf.DataCell(meta));
                    tableRegistros.AddCell(ToolsPdf.DataCell(registro.Responsible.FullName));
                    cont++;
                }

                // TotalRow
                tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_LEFT,
                    Padding             = 8f
                });

                tableRegistros.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    Padding             = 8f
                });

                tableRegistros.AddCell(new PdfPCell(new Phrase(string.Empty))
                {
                    Colspan = 3, Border = Rectangle.TOP_BORDER
                });

                document.Add(tableRegistros);
            }
        }
        #endregion

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            #region Historico
            var historico = ObjetivoHistorico.ByObjetivoId(objetivoId);
            if (historico.Count > 0)
            {
                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableHistorico = new PdfPTable(4)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableHistorico.SetWidths(new float[] { 20f, 20f, 120f, 50f });
                ToolsPdf.AddTableTitle(tableHistorico, dictionary["Item_Objetivo_TabHistoric"]);
                tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_FieldLabel_Action"]));
                tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IndicatorRecord_FieldLabel_Date"]));
                tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_ObjetivoRecord_FieldLabel_Reason"]));
                tableHistorico.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_FieldLabel_CloseResponsible"]));

                int cont = 0;
                foreach (var objetivoHistorico in historico)
                {
                    var actionText  = string.Empty;
                    var description = string.Empty;

                    if (objetivoHistorico.Reason == "Restore")
                    {
                        actionText = dictionary["Item_ObjetivoHistorico_StatusRestore"];
                    }
                    else
                    {
                        actionText  = dictionary["Item_ObjetivoHistorico_StatusAnulate"];
                        description = objetivoHistorico.Reason;
                    }

                    tableHistorico.AddCell(ToolsPdf.DataCell(actionText));
                    tableHistorico.AddCell(ToolsPdf.DataCell(objetivoHistorico.Date));
                    tableHistorico.AddCell(ToolsPdf.DataCell(description));
                    tableHistorico.AddCell(ToolsPdf.DataCell(objetivoHistorico.Employee.FullName));
                    cont++;
                }

                // TotalRow
                tableHistorico.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_LEFT,
                    Padding             = 8f
                });

                tableHistorico.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#0.00}", cont), ToolsPdf.LayoutFonts.TimesBold))
                {
                    Border = Rectangle.TOP_BORDER,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    Padding             = 8f
                });

                tableHistorico.AddCell(new PdfPCell(new Phrase(string.Empty))
                {
                    Colspan = 2, Border = Rectangle.TOP_BORDER
                });

                document.Add(tableHistorico);
            }
            #endregion
        }

        document.Close();

        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Accion.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        long auditoryId = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company    = new Company(companyId);
        var  res        = ActionResult.NoAction;
        var  user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  auditory   = Auditory.ById(auditoryId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }



        string formatedDescription = auditory.Description.Replace("?", string.Empty);

        formatedDescription = formatedDescription.Replace("#", string.Empty);
        formatedDescription = formatedDescription.Replace("/", string.Empty);
        formatedDescription = formatedDescription.Replace("\\", string.Empty);
        formatedDescription = formatedDescription.Replace(":", string.Empty);
        formatedDescription = formatedDescription.Replace(";", string.Empty);
        formatedDescription = formatedDescription.Replace(".", string.Empty);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Auditory"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);
        var document        = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = auditory.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Auditory"]
        };

        writer.PageEvent = pageEventHandler;
        document.Open();

        #region Dades bàsiques
        // Ficha pincipal
        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 50f, 30f, 50f });

        table.AddCell(new PdfPCell(new Phrase(auditory.Description, descriptionFont))
        {
            Colspan             = 4,
            Border              = Rectangle.NO_BORDER,
            PaddingTop          = 20f,
            PaddingBottom       = 20f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Type"]));
        table.AddCell(TitleData(dictionary["Item_Adutory_Type_Label_" + auditory.Type.ToString()]));

        if (auditory.Provider.Id > 0)
        {
            table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Provider"]));
            table.AddCell(TitleData(auditory.Provider.Description));
        }
        else if (auditory.Customer.Id > 0)
        {
            table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Customer"]));
            table.AddCell(TitleData(auditory.Customer.Description));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 2));
        }

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Rules"]));
        var  rulesText = string.Empty;
        bool firstRule = true;
        foreach (var rule in auditory.Rules)
        {
            if (firstRule)
            {
                firstRule = false;
            }
            else
            {
                rulesText += ", ";
            }

            rulesText += rule.Description;
        }
        table.AddCell(TitleData(rulesText, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_InternalResponsible"]));
        table.AddCell(TitleData(auditory.InternalResponsible.FullName, 3));

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PannedDate"]));
        //table.AddCell(TitleData(previewDateText));

        table.AddCell(TitleLabel(dictionary["Item_Audiotry_PDF_Planned"]));
        if (auditory.PlannedBy.Id > 0)
        {
            var planningText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.PlannedBy.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-");
            table.AddCell(TitleData(planningText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_PlanningDate"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.PlannedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Closing"]));
        if (auditory.ClosedBy.Employee.Id > 0)
        {
            var closedText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.ClosedBy.Employee.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-");
            table.AddCell(TitleData(closedText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ClosedOn"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ClosedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_PDF_Validation"]));
        if (auditory.ValidatedBy.Id > 0)
        {
            var validatedText = string.Format(
                CultureInfo.InvariantCulture,
                "{0} {1} {2}",
                auditory.ValidatedBy.FullName,
                dictionary["Item_Auditory_PDF_Label_date"],
                string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-");
            table.AddCell(TitleData(validatedText, 3));
        }
        else
        {
            table.AddCell(TitleData(string.Empty, 3));
        }

        //table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_ValidatedOn"]));
        //table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", auditory.ValidatedOn) ?? "-"));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Address"]));
        table.AddCell(TitleData(auditory.EnterpriseAddress, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_AuditorTeam"]));
        table.AddCell(TitleData(auditory.AuditorTeam, 3));

        table.AddCell(TitleLabel(dictionary["Item_Auditory_Label_Notes"]));
        table.AddCell(TitleData(string.IsNullOrEmpty(auditory.Notes.Trim()) ? "-" : auditory.Notes, 3));

        document.Add(table);
        #endregion

        if (auditory.Status > 3)
        {
            document.SetPageSize(PageSize.A4.Rotate());
            document.NewPage();


            var widthsActions = new float[] { 5f, 30f, 5f };
            var tableAccions  = new PdfPTable(widthsActions.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 0
            };

            tableAccions.SetWidths(widthsActions);
            tableAccions.AddCell(new PdfPCell(new Phrase(dictionary["Item_IncidentActions"], descriptionFont))
            {
                Colspan             = 3,
                Border              = Rectangle.NO_BORDER,
                PaddingTop          = 20f,
                PaddingBottom       = 20f,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            tableAccions.AddCell(ToolsPdf.HeaderCell(dictionary["Tipo"]));
            tableAccions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction"]));
            tableAccions.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));

            var accions = IncidentAction.ByAuditoryId(auditory.Id, auditory.CompanyId);
            foreach (var accio in accions)
            {
                tableAccions.AddCell(ToolsPdf.DataCell(dictionary["Item_IncidentAction_Type" + accio.ActionType.ToString()]));
                tableAccions.AddCell(ToolsPdf.DataCell(accio.Description));
                tableAccions.AddCell(ToolsPdf.DataCell(accio.WhatHappenedOn));
            }

            document.Add(tableAccions);
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }