﻿/*
  焊接日报、下料专项审核、焊缝外观检测
  日期：2026-08-07
*/
IF COL_LENGTH(N'dbo.HJGL_PreWeldCuttingCheck', N'ReviewState') IS NULL
BEGIN
    ALTER TABLE dbo.HJGL_PreWeldCuttingCheck
        ADD ReviewState INT NOT NULL CONSTRAINT DF_HJGL_PreWeldCuttingCheck_ReviewState DEFAULT (0);
END;
GO

IF COL_LENGTH(N'dbo.HJGL_PreWeldCuttingCheck', N'SpecialReviewerId') IS NULL
    ALTER TABLE dbo.HJGL_PreWeldCuttingCheck ADD SpecialReviewerId NVARCHAR(50) NULL;
IF COL_LENGTH(N'dbo.HJGL_PreWeldCuttingCheck', N'ReviewerId') IS NULL
    ALTER TABLE dbo.HJGL_PreWeldCuttingCheck ADD ReviewerId NVARCHAR(50) NULL;
IF COL_LENGTH(N'dbo.HJGL_PreWeldCuttingCheck', N'ReviewTime') IS NULL
    ALTER TABLE dbo.HJGL_PreWeldCuttingCheck ADD ReviewTime DATETIME NULL;
GO

IF OBJECT_ID(N'dbo.HJGL_PreWeldCuttingCheckMaterial', N'U') IS NULL
BEGIN
    CREATE TABLE dbo.HJGL_PreWeldCuttingCheckMaterial
    (
        CuttingCheckMaterialId NVARCHAR(50) NOT NULL CONSTRAINT PK_HJGL_PreWeldCuttingCheckMaterial PRIMARY KEY,
        CuttingCheckId NVARCHAR(50) NOT NULL,
        PipeLineMatId NVARCHAR(50) NOT NULL,
        MaterialSide INT NOT NULL,
        OriginalMainCode NVARCHAR(100) NULL,
        ReportedMainCode NVARCHAR(100) NULL,
        IsBatchChanged BIT NOT NULL CONSTRAINT DF_HJGL_PreWeldCuttingCheckMaterial_IsBatchChanged DEFAULT (0),
        CONSTRAINT FK_HJGL_PreWeldCuttingCheckMaterial_Check FOREIGN KEY (CuttingCheckId)
            REFERENCES dbo.HJGL_PreWeldCuttingCheck(CuttingCheckId)
    );
    CREATE INDEX IX_HJGL_PreWeldCuttingCheckMaterial_Check
        ON dbo.HJGL_PreWeldCuttingCheckMaterial(CuttingCheckId, MaterialSide);
    CREATE INDEX IX_HJGL_PreWeldCuttingCheckMaterial_Material
        ON dbo.HJGL_PreWeldCuttingCheckMaterial(PipeLineMatId, IsBatchChanged);
END;
GO

IF OBJECT_ID(N'dbo.HJGL_WeldAppearanceCheck', N'U') IS NULL
BEGIN
    CREATE TABLE dbo.HJGL_WeldAppearanceCheck
    (
        AppearanceCheckId NVARCHAR(50) NOT NULL CONSTRAINT PK_HJGL_WeldAppearanceCheck PRIMARY KEY,
        ProjectId NVARCHAR(50) NOT NULL,
        WeldJointId NVARCHAR(50) NOT NULL,
        IsQualified BIT NOT NULL,
        CheckPerson NVARCHAR(50) NOT NULL,
        CheckTime DATETIME NOT NULL,
        Remark NVARCHAR(500) NULL,
        CreateUser NVARCHAR(50) NULL,
        CreateTime DATETIME NOT NULL,
        ModifyUser NVARCHAR(50) NULL,
        ModifyTime DATETIME NULL,
        CONSTRAINT FK_HJGL_WeldAppearanceCheck_WeldJoint FOREIGN KEY (WeldJointId)
            REFERENCES dbo.HJGL_WeldJoint(WeldJointId)
    );
    CREATE INDEX IX_HJGL_WeldAppearanceCheck_JointLatest
        ON dbo.HJGL_WeldAppearanceCheck(WeldJointId, CheckTime DESC, CreateTime DESC);
    CREATE INDEX IX_HJGL_WeldAppearanceCheck_Project
        ON dbo.HJGL_WeldAppearanceCheck(ProjectId, CheckTime DESC);
END;
GO

IF NOT EXISTS (SELECT 1 FROM dbo.Sys_Menu WHERE MenuId = N'A4C8F8A1-1A27-4B63-A6DF-3F8AAE67C901')
BEGIN
    INSERT dbo.Sys_Menu(MenuId, MenuName, Url, SortIndex, SuperMenu, MenuType, IsOffice, IsEnd, IsUsed)
    VALUES(N'A4C8F8A1-1A27-4B63-A6DF-3F8AAE67C901', N'焊缝外观检测记录',
           N'HJGL/WeldingManage/WeldAppearanceCheck.aspx', 60,
           N'4D36E99E-B3D8-4C61-826A-CBD98EC51515', N'Menu_HJGL', 0, 1, 1);
END;
GO

DECLARE @AppearanceMenuId NVARCHAR(50) = N'A4C8F8A1-1A27-4B63-A6DF-3F8AAE67C901';
IF NOT EXISTS (SELECT 1 FROM dbo.Sys_ButtonToMenu WHERE MenuId=@AppearanceMenuId AND ButtonName=N'新增')
    INSERT dbo.Sys_ButtonToMenu(ButtonToMenuId, MenuId, ButtonName, SortIndex) VALUES(NEWID(), @AppearanceMenuId, N'新增', 1);
IF NOT EXISTS (SELECT 1 FROM dbo.Sys_ButtonToMenu WHERE MenuId=@AppearanceMenuId AND ButtonName=N'保存')
    INSERT dbo.Sys_ButtonToMenu(ButtonToMenuId, MenuId, ButtonName, SortIndex) VALUES(NEWID(), @AppearanceMenuId, N'保存', 2);
IF NOT EXISTS (SELECT 1 FROM dbo.Sys_ButtonToMenu WHERE MenuId=@AppearanceMenuId AND ButtonName=N'修改')
    INSERT dbo.Sys_ButtonToMenu(ButtonToMenuId, MenuId, ButtonName, SortIndex) VALUES(NEWID(), @AppearanceMenuId, N'修改', 3);
IF NOT EXISTS (SELECT 1 FROM dbo.Sys_ButtonToMenu WHERE MenuId=@AppearanceMenuId AND ButtonName=N'删除')
    INSERT dbo.Sys_ButtonToMenu(ButtonToMenuId, MenuId, ButtonName, SortIndex) VALUES(NEWID(), @AppearanceMenuId, N'删除', 4);
GO

ALTER view [dbo].[View_HJGL_WeldJoint] as
    SELECT jot.[ProjectId]                                                                                                          --项目Id
         , pipe.[UnitWorkId]                                                                                                        --单位工程Id
         , uw.UnitWorkName                                                                                                          --单位工程
         , pipe.[UnitId]                                                                                                            --单位Id
         , unit.UnitName                                                                                                            --单位
         , jot.[PipelineCode]                                                                                                       --管线号
         , pipe.[SingleNumber]                                                                                                      --单线图号
         , pipe.[SingleName]                                                                                                        --图纸名称
         , pipe.[MediumId]                                                                                                          --介质Id
         , medium.MediumCode
         , medium.MediumName                                                                                                        --介质名称
         , pipe.[PipingClassId]                                                                                                     --管道等级Id
         , pipingClass.PipingClassCode                                                                                              --管道等级
         , pipe.[DetectionRateId]                                                                                                   --探伤比例Id
         , dr.DetectionRateCode                                                                                                     --探伤比例（例如5，10，20）
         , pipe.DetectionType                                                                                                       --探伤类型Id(可能多个，中间用|分隔)
         , STUFF((SELECT ',' + DetectionTypeCode
                  FROM Base_DetectionType
                  WHERE CHARINDEX('|' + LTRIM(DetectionTypeId) + '|', '|' + pipe.DetectionType + '|') > 0
                  FOR XML PATH('')), 1, 1, '')                                                        AS DetectionTypeStr           --探伤类型（可能多个，中间用,分隔）
         , pipe.DesignTemperature                                                                                                   --设计温度℃
         , pipe.DesignPress                                                                                                         --设计压力Mpa(g)
         , pipe.TestMedium                                                                                                          --压力试验介质Id
         , tm.MediumName                                                                              AS TestMediumName             --压力试验介质
         , pipe.TestPressure                                                                                                        --压力试验压力Mpa(g)
         , pipe.PressurePipingClassId                                                                                               --压力管道级别Id
         , ppc.PressurePipingClassCode                                                                                              --压力管道级别
         , pipe.PipeLenth                                                                                                           --管线长度(m)
         , pipe.LeakMedium                                                                                                          --泄露性试验介质Id
         , tm2.MediumName                                                                             AS LeakMediumName             --泄露性试验介质
         , pipe.LeakPressure                                                                                                        --泄露性试验压力Mpa(g)
         , pipe.PCMedium                                                                                                            --吹洗要求Id
         , pm.PurgeMethodCode                                                                                                       --吹洗要求
         , pipe.VacuumPressure                                                                                                      --真空试验压力Kpa(a)
         , pipe.MaterialId                                                                                                          --材质Id
         , mat.MaterialCode                                                                           AS PipeMaterialCode           --材质
         , pipe.Remark                                                                                AS PipeRemark                 --备注
         , jot.FlowingSection                                                                        as FlowingSection             --流水段
         , jot.[WeldJointId]                                                                                                        --焊口Id
         , jot.[WeldJointCode]                                                                                                      --焊口号
         , jot.[Material1Id]                                                                                                        --材质1Id
         , mat1.MaterialCode                                                                          AS Material1Code              --材质1
         , jot.[Material2Id]                                                                                                        --材质2Id
         , mat2.MaterialCode                                                                          AS Material2Code              --材质2
         , jot.[Dia]                                                                                                                --外径
         , jot.DNDia                                                                                                                --DN公称直径
         , jot.[Size]                                                                                                               --达因
         , jot.[Thickness]                                                                                                          --壁厚
         , jot.[Specification]                                                                                                      --规格
         , jot.[WeldTypeId]                                                                                                         --焊缝类型Id
         , WeldType.WeldTypeCode                                                                                                    --焊缝类型
         , jot.[DetectionTypeId]                                                                                                    --检测类型Id
         , ndt.DetectionTypeCode                                                                                                    --检测类型
         , jot.[Components1Id]                                                                                                      --组件1号Id
         , com1.ComponentsCode                                                                        AS ComponentsCode1            --组件1号
         , jot.[Components2Id]                                                                                                      --组件2号Id
         , com2.ComponentsCode                                                                        AS ComponentsCode2            --组件2号
         , jot.DesignIsHotProess                                                                                                    --是否热处理
         , CASE jot.DesignIsHotProess WHEN 1 THEN '是' ELSE '否' END                                  AS DesignIsHotProessStr       --是否热处理
         , jot.[WeldingMethodId]                                                                                                    --焊接方法Id
         , WeldingMethod.WeldingMethodCode                                                                                          --焊接方法
         , jot.WPQId                                                                                                                --WPS的Id
         , wps.WPQCode                                                                                                              --WPS编号
         , jot.MatchableWPQ                                                                                                         --可匹配WPQ
         , jot.[GrooveTypeId]                                                                                                       --坡口类型Id
         , GrooveType.GrooveTypeCode                                                                                                --坡口类型
         , jot.[WeldingRod]                                                                                                         --焊条Id
         , rod.ConsumablesCode                                                                        AS WeldingRodCode             --焊条
         , jot.[WeldingWire]                                                                                                        --焊丝Id
         , wire.ConsumablesCode                                                                       AS WeldingWireCode            --焊丝
         , jot.PreTemperature                                                                                                       --预热温度
         , jot.[JointAttribute]                                                                                                     --焊口属性
         , jot.TwoJointType                                                                                                         --二次焊口新增类型
         , pipe.PipeArea                                                                                                            --工厂预制/现场安装
         , daily.WeldingDate                                                                          as WeldingDateD
         , CONVERT(VARCHAR(100), daily.WeldingDate, 23)                                               AS WeldingDate                --焊接日期
         , BackingWelder.WelderCode                                                                   AS BackingWelderCode          --打底焊工
         , CoverWelder.WelderCode                                                                     AS CoverWelderCode            --盖面焊工
         , CoverWelderTeamGroup.TeamGroupName                                                         as CoverWelderTeamGroupName   ----盖面焊工班组
         , BackingWelderTeamGroup.TeamGroupName                                                       as BackingWelderTeamGroupName --打底焊工班组
         , (CASE (SELECT COUNT(*)
                  FROM [dbo].[HJGL_HotProess_TrustItem] hpti
                  WHERE hpti.WeldJointId = jot.WeldJointId)
                WHEN 0 THEN ''
                ELSE (SELECT TOP 1 ISNULL(ReportNo, '')
                      FROM [dbo].[HJGL_HotProess_Trust] hpt
                               LEFT JOIN [dbo].[HJGL_HotProess_TrustItem] hpti
                                         ON hpti.HotProessTrustId = hpt.HotProessTrustId
                      WHERE hpti.WeldJointId = jot.WeldJointId) END)                                  AS HotProessReportNo          --热处理报告编号
         , (CASE (SELECT TOP 1 IsCompleted
                  FROM [dbo].[HJGL_HotProess_TrustItem] hpti
                  WHERE hpti.WeldJointId = jot.WeldJointId)
                WHEN 1 THEN '完成'
                WHEN 0 THEN '未完成'
                ELSE '未热处理' END)                                                                  AS HotProessResult            --热处理检测结果
         , (CASE (SELECT COUNT(*)
                  FROM [dbo].HJGL_Hard_TrustItem hti
                  WHERE hti.WeldJointId = jot.WeldJointId)
                WHEN 0 THEN ''
                ELSE (SELECT TOP 1 ISNULL(InspectionNum, '')
                      FROM [dbo].HJGL_Hard_Trust ht
                               LEFT JOIN [dbo].HJGL_Hard_TrustItem hti ON hti.HardTrustID = ht.HardTrustID
                      WHERE hti.WeldJointId = jot.WeldJointId) END)                                   AS HardReportNo               --硬度报告编号
         , (CASE (SELECT TOP 1 IsPass
                  FROM [dbo].HJGL_Hard_TrustItem hti
                  WHERE hti.WeldJointId = jot.WeldJointId)
                WHEN 1 THEN '合格'
                WHEN 0 THEN '不合格'
                ELSE '待检测' END)                                                                    AS HardResult                 --硬度检测结果
         , (CASE (SELECT COUNT(*)
                  FROM [dbo].HJGL_Batch_BatchTrustItem bti
                  WHERE bti.WeldJointId = jot.WeldJointId)
                WHEN 0 THEN ''
                ELSE (SELECT TOP 1 TrustBatchCode
                      FROM [dbo].HJGL_Batch_BatchTrust bt
                               LEFT JOIN [dbo].HJGL_Batch_BatchTrustItem bti ON bti.TrustBatchId = bt.TrustBatchId
                      WHERE bti.WeldJointId = jot.WeldJointId) END)                                   AS TrustBatchCode             --委托单编号
         , (CASE (SELECT COUNT(*)
                  FROM [dbo].HJGL_Batch_NDEItem ndei
                           LEFT JOIN [dbo].HJGL_Batch_BatchTrustItem bti ON bti.TrustBatchItemId = ndei.TrustBatchItemId
                  WHERE bti.WeldJointId = jot.WeldJointId)
                WHEN 0 THEN ''
                ELSE (SELECT TOP 1 ISNULL(NDECode, '')
                      FROM [dbo].HJGL_Batch_NDE nde
                               LEFT JOIN [dbo].HJGL_Batch_NDEItem ndei ON ndei.NDEID = nde.NDEID
                               LEFT JOIN [dbo].HJGL_Batch_BatchTrustItem bti
                                         ON bti.TrustBatchItemId = ndei.TrustBatchItemId
                      WHERE bti.WeldJointId = jot.WeldJointId) END)                                   AS NDECode                    --检测单编号
         , (CASE (SELECT TOP 1 CheckResult
                  FROM [dbo].HJGL_Batch_NDEItem ndei
                           LEFT JOIN [dbo].HJGL_Batch_BatchTrustItem bti ON bti.TrustBatchItemId = ndei.TrustBatchItemId
                  WHERE bti.WeldJointId = jot.WeldJointId)
                WHEN '1' THEN '合格'
                WHEN '2' THEN '不合格'
                ELSE '' END)                                                                          AS CheckResult                --检测结果
         , appearance.IsQualified                                                                    AS WeldAppearanceIsQualified
         , CASE WHEN appearance.IsQualified = 1 THEN N'合格'
                WHEN appearance.IsQualified = 0 THEN N'不合格'
                ELSE N'未检测' END                                                                    AS WeldAppearanceResult
         , jot.PipelineId
         , jot.[JointArea]
         , jot.[WeldingLocationId]
         , jot.[HeartNo1]
         , jot.[HeartNo2]
         , jot.[IsHotProess]
         , jot.[WeldingDailyId]
         , jot.[BackingWelderId]
         , jot.[CoverWelderId]
         , jot.WeldingMode
         , jot.Remark
         , jot.IsTwoJoint
         , jot.SubmitMan
         , jot.AuditMan
         , jot.AuditMan2
         , jot.AuditDate
         , jot.AuditDate2
         , jot.WeldJointPoint
         , task.TaskCode
         , WeldingLocation.WeldingLocationCode
         , CASE WHEN jot.WeldingDailyId IS NULL THEN '否' ELSE '是' END                               AS IsWelding
         , CASE WHEN jot.WeldingDailyId IS NULL THEN '未完成' ELSE '已完成' END                       AS IsWeldOK
         , CASE WHEN jot.IsHotProess = 1 THEN '是' ELSE '否' END                                      AS IsHotProessStr
         , BackingWelder.PersonName                                                                   AS BackingWelderName
         , CoverWelder.PersonName                                                                     AS CoverWelderName
         , (CASE
                WHEN CoverWelder.WelderCode IS NOT NULL AND BackingWelder.WelderCode IS NOT NULL
                    THEN CoverWelder.WelderCode + '/' + BackingWelder.WelderCode
                ELSE (ISNULL(CoverWelder.WelderCode, '') + ISNULL(BackingWelder.WelderCode, '')) END) AS WelderCode
         ,                                                                                                                          --焊工
        (CASE
             WHEN mat1.MaterialCode IS NOT NULL AND mat2.MaterialCode IS NOT NULL
                 THEN mat1.MaterialCode + '/' + mat2.MaterialCode
             ELSE (ISNULL(mat1.MaterialCode, '') + ISNULL(mat2.MaterialCode, '')) END)                AS MaterialCode
         ,                                                                                                                          --材质

        daily.WeldingDailyCode
         , pointItem.PointBatchId
         , point.PointBatchCode
         , (CASE
                WHEN pointItem.PointState = '1' THEN '已点口'
                WHEN pointItem.PointState = '2' THEN '已扩透'
                ELSE '' END)                                                                          AS IsPoint
    FROM [dbo].[HJGL_WeldJoint] jot
             LEFT JOIN dbo.HJGL_Pipeline pipe ON pipe.PipelineId = jot.PipelineId
             LEFT JOIN dbo.HJGL_WeldTask task ON task.WeldJointId = jot.WeldJointId
             LEFT JOIN dbo.WBS_UnitWork uw ON uw.UnitWorkId = pipe.UnitWorkId
             LEFT JOIN dbo.HJGL_WeldingDaily AS daily ON daily.WeldingDailyId = jot.WeldingDailyId
             LEFT JOIN dbo.Base_Unit unit ON unit.UnitId = daily.UnitId
             LEFT JOIN Base_WeldType AS WeldType ON WeldType.WeldTypeId = jot.WeldTypeId
             LEFT JOIN dbo.Base_DetectionRate dr ON dr.DetectionRateId = pipe.DetectionRateId
             LEFT JOIN Base_TestMedium tm ON tm.TestMediumId = pipe.TestMedium
             LEFT JOIN Base_TestMedium tm2 ON tm2.TestMediumId = pipe.LeakMedium
             LEFT JOIN Base_PurgeMethod pm ON pm.PurgeMethodId = pipe.PCMedium
             LEFT JOIN Base_PressurePipingClass ppc ON ppc.PressurePipingClassId = pipe.PressurePipingClassId
             LEFT JOIN Base_Material AS mat ON mat.MaterialId = pipe.MaterialId
             LEFT JOIN Base_Material AS mat1 ON mat1.MaterialId = jot.Material1Id
             LEFT JOIN Base_Material AS mat2 ON mat2.MaterialId = jot.Material2Id
             LEFT JOIN Base_WeldingMethod AS WeldingMethod ON WeldingMethod.WeldingMethodId = jot.WeldingMethodId
             LEFT JOIN Base_WeldingLocation AS WeldingLocation
                       ON WeldingLocation.WeldingLocationId = jot.WeldingLocationId
             LEFT JOIN Base_Consumables AS wire ON wire.ConsumablesId = jot.WeldingWire
             LEFT JOIN Base_Consumables AS rod ON rod.ConsumablesId = jot.WeldingRod
             LEFT JOIN Base_GrooveType AS GrooveType ON GrooveType.GrooveTypeId = jot.GrooveTypeId
             LEFT JOIN Base_Components AS com1 ON com1.ComponentsId = jot.Components1Id
             LEFT JOIN Base_Components AS com2 ON com2.ComponentsId = jot.Components2Id
             LEFT JOIN SitePerson_Person AS BackingWelder
                       ON BackingWelder.PersonId = jot.BackingWelderId and BackingWelder.ProjectId = jot.ProjectId
             LEFT JOIN SitePerson_Person AS CoverWelder
                       ON CoverWelder.PersonId = jot.CoverWelderId and CoverWelder.ProjectId = jot.ProjectId
             LEFT JOIN Base_PipingClass AS pipingClass ON pipingClass.PipingClassId = pipe.PipingClassId
             LEFT JOIN dbo.Base_Medium medium ON medium.MediumId = pipe.MediumId
             LEFT JOIN dbo.Base_DetectionType ndt ON ndt.DetectionTypeId = jot.DetectionTypeId
             LEFT JOIN dbo.WPQ_WPQList wps ON wps.WPQId = jot.WPQId
             LEFT JOIN dbo.HJGL_Batch_PointBatchItem pointItem ON pointItem.WeldJointId = jot.WeldJointId
             LEFT JOIN dbo.HJGL_Batch_PointBatch point ON point.PointBatchId = pointItem.PointBatchId
             LEFT JOIN dbo.ProjectData_TeamGroup AS CoverWelderTeamGroup
                       on CoverWelderTeamGroup.TeamGroupId = jot.CoverWelderTeamGroupId and
                          CoverWelderTeamGroup.ProjectId = jot.ProjectId
             LEFT JOIN dbo.ProjectData_TeamGroup AS BackingWelderTeamGroup
                       on BackingWelderTeamGroup.TeamGroupId = jot.BackingWelderTeamGroupId and
                          BackingWelderTeamGroup.ProjectId = jot.ProjectId
             OUTER APPLY
             (
                 SELECT TOP 1 checkItem.IsQualified
                 FROM dbo.HJGL_WeldAppearanceCheck checkItem
                 WHERE checkItem.WeldJointId = jot.WeldJointId
                 ORDER BY checkItem.CheckTime DESC, checkItem.CreateTime DESC, checkItem.AppearanceCheckId DESC
             ) appearance;
GO
