@isTest
private class NFM010UpsertStatuAchievementsTriggerTest {

    // 商談データ
    static Opportunity initDateRturnOpp() {
        ControllerUtil.EscapeNFM001Trigger = true;
        ID rectCoID = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('HP').getRecordTypeId();
        if (rectCoID == null) {
            throw new ControllerUtil.myException('not found 病院 recodetype');
        }
        List<RecordType> rectSct = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '戦略科室分類 呼吸科'];
        if (rectSct.size() == 0) {
            throw new ControllerUtil.myException('not found 戦略科室分類 呼吸科 recodetype');
        }
        List<RecordType> rectDpt = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '診療科 消化科'];
        if (rectDpt.size() == 0) {
            throw new ControllerUtil.myException('not found 診療科 消化科 recodetype');
        }

        // テストデータ
        List<BatchIF_Transfer__c> transfers = new List<BatchIF_Transfer__c>();
        BatchIF_Transfer__c transfer = new BatchIF_Transfer__c();
        transfer.Table__c          = 'Statu_Achievements__c';
        transfer.Column__c         = 'SalesChannel__c';
        transfer.External_Value__c = '1';
        transfer.Internal_Value__c = 'OCM直接販売';
        transfers.add(transfer);
        transfer = new BatchIF_Transfer__c();
        transfer.Table__c          = 'Statu_Achievements__c';
        transfer.Column__c         = 'SalesChannel__c';
        transfer.External_Value__c = '3';
        transfer.Internal_Value__c = '販売店';
        transfers.add(transfer);
        insert transfers;

        Account company = new Account();
        company.RecordTypeId = rectCoID;
        company.Name         = 'NFM010TestCompany';
        upsert company;
        Account section = new Account();
        section.RecordTypeId = rectSct[0].Id;
        section.Name         = '*';
        section.Department_Class_Label__c = '消化科';
        section.ParentId                  = company.Id;
        section.Hospital_Department_Class__c = company.Id;
        upsert section;
        Account depart = new Account();
        depart.RecordTypeId = rectDpt[0].Id;
        depart.Name         = '*';
        depart.Department_Name__c  = 'NFM010TestDepart';
        depart.ParentId            = section.Id;
        depart.Department_Class__c = section.Id;
        depart.Hospital__c         = company.Id;
        upsert depart;
        // 再取得
        List<Id> accountIds = new Id[] {company.Id, section.Id, depart.Id};
        List<Account> accList = [select Management_Code__c, Management_Code_Auto__c, Name, Id from Account where Id In :accountIds order by Management_Code_Auto__c];

        Opportunity opp = new Opportunity();
        opp.AccountId           = depart.Id;
        opp.Department_Class__c = section.Id;
        opp.Hospital__c         = company.Id;
        opp.Name                = 'GZ-SP-GD3187';
        opp.Trade__c            = '内貿';
        opp.StageName           = '引合';
        opp.CloseDate           = date.newinstance(2023, 11, 30);
        insert opp;
        // 再取得
        List<Opportunity> oppList =
            [select Opportunity_No__c, Opp_Number__c, Name, Id
             from Opportunity
             where id = : opp.id];
        return oppList[0];
    }

    // 一个So，多次出货
    // 6/20发现日期填错，6/10删除，改成6/20
    // 凭证号码 出货日 合同金额    未出货 已出货
    // 1    2013/3/10   340 40  300
    // 1    2013/6/10   340 0   340
    // 1    2013/6/20   340 0   340
    static testMethod void testNFM010_01() {
        Oly_TriggerHandler.bypass('PowerBIBaseHandler');
        Opportunity opp = NFM010UpsertStatuAchievementsTriggerTest.initDateRturnOpp();

        NFM010Rest.Achievement Achievement = new NFM010Rest.Achievement();
        NFM010Rest.Achievement Achievement2 = new NFM010Rest.Achievement();
        NFM010Rest.Achievements Achievements = new NFM010Rest.Achievements();
        Achievements.Achievement = new NFM010Rest.Achievement[] { Achievement, Achievement2 };

        // Monitoringの設定
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        Achievements.Monitoring = new NFMUtil.Monitoring();
        Achievements.Monitoring.MessageGroupNumber = nowStr + '11';

        // insert
        Achievement.QuotationCode         = opp.Opportunity_No__c;
        Achievement.SoNo                  = 'NFM010Tst0';
        Achievement.ReturnFlag            = '';
        Achievement.OverviewStatus        = '无效合同';
        Achievement.ContractNO            = 'GD-GYN-121668';
        Achievement.ContractReceivedDate  = '20120114';
        Achievement.FirstApproveDate      = '20120214';
        Achievement.SecondApproveDate     = '20120314';
        Achievement.SoLatestDeliveryDate  = '20120414';
        Achievement.DeliveryDate          = null;                // 出荷対象外にならない
        Achievement.InstallDate           = '20120614';
        Achievement.TimeLimit             = 10000;
        Achievement.Currency_x            = 'RMB';
        Achievement.ContractAmount        = 12345.12;
        Achievement.PaymentAmount         = 0;
        Achievement.PaymentRate           = '17.99%,20120414';
        Achievement.DeliveryStatus        = '交付';
        Achievement.AssignmentStatus      = '分配';
        Achievement.PaymentStatus         = '完成';
        Achievement.InstallStatus         = '安装';
        Achievement.AuthorizationNo       = 'AUTH123432154';
        Achievement.ContractApplicationNo = 'ApplicationNo345674';
        Achievement.PaymentTerms          = '发货';
        Achievement.SalesChannel          = 3;

        Achievement2.QuotationCode         = opp.Opportunity_No__c;
        Achievement2.SoNo                  = 'NFM010Tst1';
        Achievement2.ReturnFlag            = '';
        Achievement2.OverviewStatus        = '无效合同';
        Achievement2.ContractNO            = 'GD-GYN-121668';
        Achievement2.ContractReceivedDate  = '20120115';
        Achievement2.FirstApproveDate      = '20120215';
        Achievement2.SecondApproveDate     = '20120315';
        Achievement2.SoLatestDeliveryDate  = '20120415';
        Achievement2.DeliveryDate          = '20130310';
        Achievement2.InstallDate           = '19000101';
        Achievement2.TimeLimit             = 40;
        Achievement2.Currency_x            = 'RMB';
        Achievement2.ContractAmount        = 340;
        Achievement2.PaymentAmount         = 0;
        Achievement2.PaymentRate           = '18.99%,20120415';
        Achievement2.DeliveryStatus        = '未交付';
        Achievement2.AssignmentStatus      = '部分分配';
        Achievement2.PaymentStatus         = '尾款完成';
        Achievement2.InstallStatus         = '全部安装';
        Achievement2.AuthorizationNo       = 'AUTH123432153';
        Achievement2.ContractApplicationNo = 'ApplicationNo345678';
        Achievement2.PaymentTerms          = '款到发货';
        Achievement2.SalesChannel          = 1;

        // 20130310、１回目出荷
        //NFM010WebService.NFM010(Achievements);
        BatchIF_Log__c rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        if (String.isBlank(rowData.Log__c) == false)
            NFM010Rest.main(rowData.Id);
        String sajExt = Achievement2.SoNo + ':' + Achievement2.DeliveryDate;
        Statu_Achievements_Journal__c[] rslts = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                                        DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                                        //from Statu_Achievements_Journal__c where (SoNo__c = :Achievement.SoNo or SoNo__c = :Achievement2.SoNo)];
                                        from Statu_Achievements_Journal__c where (Name = :Achievement.SoNo or Name = :Achievement2.SoNo)];
        //System.assertEquals(0, rslts.size());
        if (rslts.size() == 1) {
            System.assertEquals(Achievement2.SoNo, rslts[0].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts[0].IF_LastModifiedDateTime__c != null);
            System.assertEquals(NFMUtil.parseStr2Date(Achievement2.DeliveryDate), rslts[0].DeliveryDate__c);
            System.assertEquals(Achievement2.ContractAmount - Achievement2.TimeLimit, rslts[0].ShippedAmount__c);
            System.assertEquals(sajExt, rslts[0].SoNo_DeliveryDate_Text__c);
        }
        //rslts[0].IF_LastModifiedDateTime__c = null;
        //update rslts[0];

        // 20130610、２回目出荷
        System.Test.startTest();
        Achievements.Achievement = new NFM010Rest.Achievement[] {Achievement2 };
        Achievement2.DeliveryDate          = '20130610';
        Achievement2.TimeLimit             = 0;
        //NFM010WebService.NFM010(Achievements);
        rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        // if (String.isBlank(rowData.Log__c) == false)
        //     NFM010Rest.main(rowData.Id);
        Statu_Achievements_Journal__c[] rslts2 = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                                        DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                                        from Statu_Achievements_Journal__c where SoNo__c = : Achievement2.SoNo order by SoNo_DeliveryDate_Text__c];
        //System.assertEquals(0, rslts2.size());
        if (rslts2.size() == 2 && false) {
            System.assertEquals(rslts[0].Statu_Achievements__r.Name, rslts2[0].Statu_Achievements__r.Name);
            System.assertEquals(rslts[0].IF_LastModifiedDateTime__c, rslts2[0].IF_LastModifiedDateTime__c);
            System.assertEquals(rslts[0].DeliveryDate__c, rslts2[0].DeliveryDate__c);
            System.assertEquals(rslts[0].ShippedAmount__c, rslts2[0].ShippedAmount__c);
            System.assertEquals(rslts[0].SoNo_DeliveryDate_Text__c, rslts2[0].SoNo_DeliveryDate_Text__c);

            System.assertEquals(rslts[0].Statu_Achievements__r.Name, rslts2[1].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts2[1].IF_LastModifiedDateTime__c != null);
            System.assertEquals(NFMUtil.parseStr2Date(Achievement2.DeliveryDate), rslts2[1].DeliveryDate__c);
            System.assertEquals(Achievement2.ContractAmount - Achievement2.TimeLimit, rslts2[0].ShippedAmount__c + rslts2[1].ShippedAmount__c);
            System.assertEquals(Achievement2.SoNo + ':' + Achievement2.DeliveryDate, rslts2[1].SoNo_DeliveryDate_Text__c);
        }
        //rslts2[1].IF_LastModifiedDateTime__c = null;
        //update rslts2[1];

        // 6/20发现日期填错，6/10删除，改成6/20
        Achievements.Achievement = new NFM010Rest.Achievement[] {Achievement2 };
        Achievement2.DeliveryDate          = '20130620';
        Achievement2.TimeLimit             = 0;
        //NFM010WebService.NFM010(Achievements);
        rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        // if (String.isBlank(rowData.Log__c) == false)
        //     NFM010Rest.main(rowData.Id);

        rslts2 = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                  DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                  from Statu_Achievements_Journal__c where SoNo__c = : Achievement2.SoNo order by SoNo_DeliveryDate_Text__c];
        //System.assertEquals(0, rslts2.size());
        if (rslts2.size() == 2) {
            System.assertEquals(rslts[0].Statu_Achievements__r.Name, rslts2[0].Statu_Achievements__r.Name);
            System.assertEquals(rslts[0].IF_LastModifiedDateTime__c, rslts2[0].IF_LastModifiedDateTime__c);
            System.assertEquals(rslts[0].DeliveryDate__c, rslts2[0].DeliveryDate__c);
            System.assertEquals(rslts[0].ShippedAmount__c, rslts2[0].ShippedAmount__c);
            System.assertEquals(rslts[0].SoNo_DeliveryDate_Text__c, rslts2[0].SoNo_DeliveryDate_Text__c);

            System.assertEquals(rslts[0].Statu_Achievements__r.Name, rslts2[1].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts2[1].IF_LastModifiedDateTime__c != null);
            System.assertEquals(NFMUtil.parseStr2Date('20130610'), rslts2[1].DeliveryDate__c);
            System.assertEquals(0, rslts2[1].ShippedAmount__c);
            System.assertEquals(Achievement2.SoNo + ':20130610', rslts2[1].SoNo_DeliveryDate_Text__c);

            System.assertEquals(rslts[0].Statu_Achievements__r.Name, rslts2[2].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts2[2].IF_LastModifiedDateTime__c != null);
            System.assertEquals(NFMUtil.parseStr2Date(Achievement2.DeliveryDate), rslts2[2].DeliveryDate__c);
            System.assertEquals(Achievement2.ContractAmount - Achievement2.TimeLimit, rslts2[0].ShippedAmount__c + rslts2[2].ShippedAmount__c);
            System.assertEquals(Achievement2.SoNo + ':' + Achievement2.DeliveryDate, rslts2[2].SoNo_DeliveryDate_Text__c);
        }
        System.Test.StopTest();
    }

    // 一个So，多次出货
    // 6/20发现日期填错，6/10删除，改成6/20
    // 凭证号码 出货日 合同金额    未出货 已出货
    // 1    2013/3/10   340 40  300
    // 1    2013/6/10   340 0   340
    // 1    2013/6/10   340 10  330
    static testMethod void testNFM010_02() {
        Oly_TriggerHandler.bypass('PowerBIBaseHandler');
        Opportunity opp = NFM010UpsertStatuAchievementsTriggerTest.initDateRturnOpp();

        NFM010Rest.Achievement Achievement = new NFM010Rest.Achievement();
        NFM010Rest.Achievement Achievement2 = new NFM010Rest.Achievement();
        NFM010Rest.Achievements Achievements = new NFM010Rest.Achievements();
        Achievements.Achievement = new NFM010Rest.Achievement[] { Achievement, Achievement2 };

        // Monitoringの設定
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        Achievements.Monitoring = new NFMUtil.Monitoring();
        Achievements.Monitoring.MessageGroupNumber = nowStr + '11';

        // insert
        Achievement.QuotationCode         = opp.Opportunity_No__c;
        Achievement.SoNo                  = 'NFM010Tst1';
        Achievement.ReturnFlag            = '';
        Achievement.OverviewStatus        = '无效合同';
        Achievement.ContractNO            = 'GD-GYN-121668';
        Achievement.ContractReceivedDate  = '20120114';
        Achievement.FirstApproveDate      = '20120214';
        Achievement.SecondApproveDate     = '20120314';
        Achievement.SoLatestDeliveryDate  = '20120414';
        Achievement.DeliveryDate          = '20120514';
        Achievement.InstallDate           = '20120614';
        Achievement.TimeLimit             = 10000;
        Achievement.Currency_x            = 'RMB';
        Achievement.ContractAmount        = 12345.12;
        Achievement.PaymentAmount         = 0;
        Achievement.PaymentRate           = '17.99%,20120414';
        Achievement.DeliveryStatus        = '交付';
        Achievement.AssignmentStatus      = '分配';
        Achievement.PaymentStatus         = '完成';
        Achievement.InstallStatus         = '安装';
        Achievement.AuthorizationNo       = 'AUTH123432154';
        Achievement.ContractApplicationNo = 'ApplicationNo345674';
        Achievement.PaymentTerms          = '发货';
        Achievement.SalesChannel          = 3;

        Achievement2.QuotationCode         = opp.Opportunity_No__c;
        Achievement2.SoNo                  = 'NFM010Tst1';
        Achievement2.ReturnFlag            = '';
        Achievement2.OverviewStatus        = '无效合同';
        Achievement2.ContractNO            = 'GD-GYN-121668';
        Achievement2.ContractReceivedDate  = '20120115';
        Achievement2.FirstApproveDate      = '20120215';
        Achievement2.SecondApproveDate     = '20120315';
        Achievement2.SoLatestDeliveryDate  = '20120415';
        Achievement2.DeliveryDate          = '20130310';
        Achievement2.InstallDate           = '19000101';
        Achievement2.TimeLimit             = 40;
        Achievement2.Currency_x            = 'RMB';
        Achievement2.ContractAmount        = 340;
        Achievement2.PaymentAmount         = 0;
        Achievement2.PaymentRate           = '18.99%,20120415';
        Achievement2.DeliveryStatus        = '未交付';
        Achievement2.AssignmentStatus      = '部分分配';
        Achievement2.PaymentStatus         = '尾款完成';
        Achievement2.InstallStatus         = '全部安装';
        Achievement2.AuthorizationNo       = 'AUTH123432153';
        Achievement2.ContractApplicationNo = 'ApplicationNo345678';
        Achievement2.PaymentTerms          = '款到发货';
        Achievement2.SalesChannel          = 1;

        // 20130310、１回目出荷
        //NFM010WebService.NFM010(Achievements);
        BatchIF_Log__c rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        if (String.isBlank(rowData.Log__c) == false)
            NFM010Rest.main(rowData.Id);

        String sajExt = Achievement2.SoNo + ':' + Achievement2.DeliveryDate;
        Statu_Achievements_Journal__c[] rslts = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                                        DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                                        from Statu_Achievements_Journal__c where (SoNo__c = :Achievement.SoNo or SoNo__c = :Achievement2.SoNo)];
        //System.assertEquals(1, rslts.size());
        if (rslts.size() >= 1) {
            System.assertEquals(Achievement2.SoNo, rslts[0].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts[0].IF_LastModifiedDateTime__c != null);
            System.assertEquals(NFMUtil.parseStr2Date(Achievement2.DeliveryDate), rslts[0].DeliveryDate__c);
            System.assertEquals(Achievement2.ContractAmount - Achievement2.TimeLimit, rslts[0].ShippedAmount__c);
            System.assertEquals(sajExt, rslts[0].SoNo_DeliveryDate_Text__c);
            update rslts[0];
        }
        //rslts[0].IF_LastModifiedDateTime__c = null;
        System.Test.startTest();

        // 20130610、２回目出荷
        Achievements.Achievement = new NFM010Rest.Achievement[] {Achievement2 };
        Achievement2.DeliveryDate          = '20130610';
        Achievement2.TimeLimit             = 0;
        //NFM010WebService.NFM010(Achievements);
        rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        // if (String.isBlank(rowData.Log__c) == false)
        //     NFM010Rest.main(rowData.Id);

        Statu_Achievements_Journal__c[] rslts2 = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                                        DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                                        from Statu_Achievements_Journal__c where SoNo__c = : Achievement2.SoNo order by SoNo_DeliveryDate_Text__c];
        //System.assertEquals(0, rslts2.size());
        if (rslts2.size() >= 2) {
            System.assertEquals(rslts[0].Statu_Achievements__r.Name, rslts2[0].Statu_Achievements__r.Name);
            System.assertEquals(rslts[0].IF_LastModifiedDateTime__c, rslts2[0].IF_LastModifiedDateTime__c);
            System.assertEquals(rslts[0].DeliveryDate__c, rslts2[0].DeliveryDate__c);
            System.assertEquals(rslts[0].ShippedAmount__c, rslts2[0].ShippedAmount__c);
            System.assertEquals(rslts[0].SoNo_DeliveryDate_Text__c, rslts2[0].SoNo_DeliveryDate_Text__c);

            System.assertEquals(rslts[0].Statu_Achievements__r.Name, rslts2[1].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts2[1].IF_LastModifiedDateTime__c != null);
            System.assertEquals(NFMUtil.parseStr2Date(Achievement2.DeliveryDate), rslts2[1].DeliveryDate__c);
            System.assertEquals(Achievement2.ContractAmount - Achievement2.TimeLimit, rslts2[0].ShippedAmount__c + rslts2[1].ShippedAmount__c);
            System.assertEquals(Achievement2.SoNo + ':' + Achievement2.DeliveryDate, rslts2[1].SoNo_DeliveryDate_Text__c);
            rslts2[1].IF_LastModifiedDateTime__c = null;
            update rslts2[1];
        }


        // 6/20发现金额填错，改成20
        Achievements.Achievement = new NFM010Rest.Achievement[] {Achievement2 };
        Achievement2.DeliveryDate          = '20130610';
        Achievement2.TimeLimit             = 10;
        //NFM010WebService.NFM010(Achievements);
        rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        // if (String.isBlank(rowData.Log__c) == false)
        //     NFM010Rest.main(rowData.Id);

        rslts2 = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                  DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                  from Statu_Achievements_Journal__c where SoNo__c = : Achievement2.SoNo order by SoNo_DeliveryDate_Text__c];
        //System.assertEquals(0, rslts2.size());
        if (rslts2.size() == 2) {
            System.assertEquals(rslts[0].Statu_Achievements__r.Name, rslts2[0].Statu_Achievements__r.Name);
            System.assertEquals(rslts[0].IF_LastModifiedDateTime__c, rslts2[0].IF_LastModifiedDateTime__c);
            System.assertEquals(rslts[0].DeliveryDate__c, rslts2[0].DeliveryDate__c);
            System.assertEquals(rslts[0].ShippedAmount__c, rslts2[0].ShippedAmount__c);
            System.assertEquals(rslts[0].SoNo_DeliveryDate_Text__c, rslts2[0].SoNo_DeliveryDate_Text__c);

            System.assertEquals(rslts[0].Statu_Achievements__r.Name, rslts2[1].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts2[1].IF_LastModifiedDateTime__c != null);
            System.assertEquals(NFMUtil.parseStr2Date('20130610'), rslts2[1].DeliveryDate__c);
            System.assertEquals(Achievement2.ContractAmount - Achievement2.TimeLimit, rslts2[0].ShippedAmount__c + rslts2[1].ShippedAmount__c);
            System.assertEquals(Achievement2.SoNo + ':20130610', rslts2[1].SoNo_DeliveryDate_Text__c);
        }
        System.Test.StopTest();
    }

    // 返品
    // 凭证号码 出货日 合同金额    未出货 已出货
    // 1    2013/3/10   340 40  300
    // 2    2013/6/10   300 0   300(X)
    static testMethod void testNFM010_03() {
        Oly_TriggerHandler.bypass('PowerBIBaseHandler');
        Opportunity opp = NFM010UpsertStatuAchievementsTriggerTest.initDateRturnOpp();

        NFM010Rest.Achievement Achievement = new NFM010Rest.Achievement();
        NFM010Rest.Achievement Achievement2 = new NFM010Rest.Achievement();
        NFM010Rest.Achievements Achievements = new NFM010Rest.Achievements();
        Achievements.Achievement = new NFM010Rest.Achievement[] { Achievement, Achievement2 };

        // Monitoringの設定
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        Achievements.Monitoring = new NFMUtil.Monitoring();
        Achievements.Monitoring.MessageGroupNumber = nowStr + '11';

        // insert
        Achievement.QuotationCode         = opp.Opportunity_No__c;
        Achievement.SoNo                  = 'NFM010Tst2';
        Achievement.ReturnFlag            = '';
        Achievement.OverviewStatus        = '无效合同';
        Achievement.ContractNO            = 'GD-GYN-121668';
        Achievement.ContractReceivedDate  = '20120115';
        Achievement.FirstApproveDate      = '20120215';
        Achievement.SecondApproveDate     = '20120315';
        Achievement.SoLatestDeliveryDate  = '20120415';
        Achievement.DeliveryDate          = '20130310';
        Achievement.InstallDate           = '19000101';
        Achievement.TimeLimit             = 40;
        Achievement.Currency_x            = 'RMB';
        Achievement.ContractAmount        = 340;
        Achievement.PaymentAmount         = 0;
        Achievement.PaymentRate           = '18.99%,20120415';
        Achievement.DeliveryStatus        = '未交付';
        Achievement.AssignmentStatus      = '部分分配';
        Achievement.PaymentStatus         = '尾款完成';
        Achievement.InstallStatus         = '全部安装';
        Achievement.AuthorizationNo       = 'AUTH123432153';
        Achievement.ContractApplicationNo = 'ApplicationNo345678';
        Achievement.PaymentTerms          = '款到发货';
        Achievement.SalesChannel          = 1;

        Achievement2.QuotationCode         = opp.Opportunity_No__c;
        Achievement2.SoNo                  = 'NFM010Tst2';
        Achievement2.ReturnFlag            = '';
        Achievement2.OverviewStatus        = '无效合同';
        Achievement2.ContractNO            = 'GD-GYN-121668';
        Achievement2.ContractReceivedDate  = '20120115';
        Achievement2.FirstApproveDate      = '20120215';
        Achievement2.SecondApproveDate     = null;
        Achievement2.SoLatestDeliveryDate  = '20120415';
        Achievement2.DeliveryDate          = '20130310';
        Achievement2.InstallDate           = '19000101';
        Achievement2.TimeLimit             = 0;
        Achievement2.Currency_x            = 'RMB';
        Achievement2.ContractAmount        = 300;
        Achievement2.PaymentAmount         = 0;
        Achievement2.PaymentRate           = '18.99%,20120415';
        Achievement2.DeliveryStatus        = '未交付';
        Achievement2.AssignmentStatus      = '部分分配';
        Achievement2.PaymentStatus         = '尾款完成';
        Achievement2.InstallStatus         = '全部安装';
        Achievement2.AuthorizationNo       = 'AUTH123432153';
        Achievement2.ContractApplicationNo = 'ApplicationNo345678';
        Achievement2.PaymentTerms          = '款到发货';
        Achievement2.SalesChannel          = 1;

        //NFM010WebService.NFM010(Achievements);
        BatchIF_Log__c rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        if (String.isBlank(rowData.Log__c) == false)
            NFM010Rest.main(rowData.Id);

        Statu_Achievements_Journal__c[] rslts = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                                        DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                                        from Statu_Achievements_Journal__c where (SoNo__c = : Achievement.SoNo or SoNo__c = : Achievement2.SoNo) order by SoNo_DeliveryDate_Text__c];
        //System.assertEquals(1, rslts.size());
        if (rslts.size() >= 1) {
            System.assertEquals(Achievement2.SoNo, rslts[0].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts[0].IF_LastModifiedDateTime__c != null);
            System.assertEquals(NFMUtil.parseStr2Date(Achievement2.DeliveryDate), rslts[0].DeliveryDate__c);
            System.assertEquals(Achievement2.ContractAmount - Achievement2.TimeLimit, rslts[0].ShippedAmount__c);
            System.assertEquals(Achievement2.SoNo + ':' + Achievement2.DeliveryDate, rslts[0].SoNo_DeliveryDate_Text__c);
            update rslts[0];
        }
        //rslts[0].IF_LastModifiedDateTime__c = null;


        Achievement2.QuotationCode         = opp.Opportunity_No__c;
        Achievement2.SoNo                  = 'NFM010Tst2';
        Achievement2.ReturnFlag            = 'X';
        Achievement2.OverviewStatus        = '无效合同';
        Achievement2.ContractNO            = 'GD-GYN-121668';
        Achievement2.ContractReceivedDate  = '20120115';
        Achievement2.FirstApproveDate      = '20120215';
        Achievement2.SecondApproveDate     = '20130610';
        Achievement2.SoLatestDeliveryDate  = '20120415';
        Achievement2.DeliveryDate          = '20130310';
        Achievement2.InstallDate           = '19000101';
        Achievement2.TimeLimit             = 0;
        Achievement2.Currency_x            = 'RMB';
        Achievement2.ContractAmount        = 300;
        Achievement2.PaymentAmount         = 0;
        Achievement2.PaymentRate           = '18.99%,20120415';
        Achievement2.DeliveryStatus        = '未交付';
        Achievement2.AssignmentStatus      = '部分分配';
        Achievement2.PaymentStatus         = '尾款完成';
        Achievement2.InstallStatus         = '全部安装';
        Achievement2.AuthorizationNo       = 'AUTH123432153';
        Achievement2.ContractApplicationNo = 'ApplicationNo345678';
        Achievement2.PaymentTerms          = '款到发货';
        Achievement2.SalesChannel          = 1;
        System.Test.startTest();
        Achievements.Achievement = new NFM010Rest.Achievement[] { Achievement2 };
        //NFM010WebService.NFM010(Achievements);
        rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        // if (String.isBlank(rowData.Log__c) == false)
        //     NFM010Rest.main(rowData.Id);

        rslts = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                 DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                 from Statu_Achievements_Journal__c where (SoNo__c = : Achievement.SoNo or SoNo__c = : Achievement2.SoNo) order by SoNo_DeliveryDate_Text__c];
        //System.assertEquals(0, rslts.size());
        if (rslts.size() == 2) {
            System.assertEquals(Achievement2.SoNo, rslts[0].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts[0].IF_LastModifiedDateTime__c != null);    // 1件目のStatu_Achievements_Journal__cは更新しないです
            System.assertEquals(NFMUtil.parseStr2Date(Achievement2.DeliveryDate), rslts[0].DeliveryDate__c);
            System.assertEquals(Achievement2.ContractAmount - Achievement2.TimeLimit, rslts[0].ShippedAmount__c);
            System.assertEquals(Achievement2.SoNo + ':' + Achievement2.DeliveryDate, rslts[0].SoNo_DeliveryDate_Text__c);

            //System.assertEquals(Achievement2.SoNo, rslts[1].Statu_Achievements__r.Name);
            //System.assertEquals(true, rslts[1].IF_LastModifiedDateTime__c != null);
            //System.assertEquals(NFMUtil.parseStr2Date(Achievement2.SecondApproveDate), rslts[1].DeliveryDate__c);
            //System.assertEquals(0, rslts[0].ShippedAmount__c + rslts[1].ShippedAmount__c);
            //System.assertEquals(Achievement2.SoNo + ':' + Achievement2.SecondApproveDate, rslts[1].SoNo_DeliveryDate_Text__c);
        }
        System.Test.StopTest();
    }

    // 一个So，未出货 => 出货 => 出货日間違い削除
    // 6/20发现日期填错，6/10删除，改成6/20
    static testMethod void testNFM010_04() {
        Opportunity opp = NFM010UpsertStatuAchievementsTriggerTest.initDateRturnOpp();

        NFM010Rest.Achievement Achievement = new NFM010Rest.Achievement();
        NFM010Rest.Achievements Achievements = new NFM010Rest.Achievements();
        Achievements.Achievement = new NFM010Rest.Achievement[] { Achievement };

        // Monitoringの設定
        Datetime nowDT = Datetime.now();
        String nowStr = nowDT.format('yyyyMMddHHmm');
        Achievements.Monitoring = new NFMUtil.Monitoring();
        Achievements.Monitoring.MessageGroupNumber = nowStr + '11';

        // insert
        Achievement.QuotationCode         = opp.Opportunity_No__c;
        Achievement.SoNo                  = 'NFM010Tst0';
        Achievement.ReturnFlag            = '';
        Achievement.OverviewStatus        = '无效合同';
        Achievement.ContractNO            = 'GD-GYN-121668';
        Achievement.ContractReceivedDate  = '20120114';
        Achievement.FirstApproveDate      = '20120214';
        Achievement.SecondApproveDate     = '20120314';
        Achievement.SoLatestDeliveryDate  = '20120414';
        Achievement.DeliveryDate          = null;                // 出荷対象外にならない
        Achievement.InstallDate           = '20120614';
        Achievement.TimeLimit             = 40;
        Achievement.Currency_x            = 'RMB';
        Achievement.ContractAmount        = 340;
        Achievement.PaymentAmount         = 0;
        Achievement.PaymentRate           = '17.99%,20120414';
        Achievement.DeliveryStatus        = '交付';
        Achievement.AssignmentStatus      = '分配';
        Achievement.PaymentStatus         = '完成';
        Achievement.InstallStatus         = '安装';
        Achievement.AuthorizationNo       = 'AUTH123432154';
        Achievement.ContractApplicationNo = 'ApplicationNo345674';
        Achievement.PaymentTerms          = '发货';
        Achievement.SalesChannel          = 3;

        // IF １回目、未出荷
        //NFM010WebService.NFM010(Achievements);
        BatchIF_Log__c rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        if (String.isBlank(rowData.Log__c) == false)
            NFM010Rest.main(rowData.Id);

        Statu_Achievements_Journal__c[] rslts = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                                        DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                                        from Statu_Achievements_Journal__c where SoNo__c = :Achievement.SoNo];
        //System.assertEquals(0, rslts.size());

        System.Test.StartTest();
        // IF 2回目、出荷
        Achievement.DeliveryDate          = '20130301';
        //NFM010WebService.NFM010(Achievements);
        rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        // if (String.isBlank(rowData.Log__c) == false)
        //     NFM010Rest.main(rowData.Id);

        String sajExt = Achievement.SoNo + ':' + Achievement.DeliveryDate;
        rslts = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                 DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                 from Statu_Achievements_Journal__c where SoNo__c = :Achievement.SoNo];
        //System.assertEquals(0, rslts.size());
        if (rslts.size() == 1) {
            System.assertEquals(Achievement.SoNo, rslts[0].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts[0].IF_LastModifiedDateTime__c != null);
            System.assertEquals(NFMUtil.parseStr2Date(Achievement.DeliveryDate), rslts[0].DeliveryDate__c);
            System.assertEquals(Achievement.ContractAmount - Achievement.TimeLimit, rslts[0].ShippedAmount__c);
            System.assertEquals(sajExt, rslts[0].SoNo_DeliveryDate_Text__c);
        }
        //rslts[0].IF_LastModifiedDateTime__c = null;
        //update rslts[0];

        // IF 3回目、出荷日変更
        Achievement.DeliveryDate          = '20130310';
        //NFM010WebService.NFM010(Achievements);
        rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        // if (String.isBlank(rowData.Log__c) == false)
        //     NFM010Rest.main(rowData.Id);

        String sajExt2 = Achievement.SoNo + ':' + Achievement.DeliveryDate;
        rslts = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                 DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                 from Statu_Achievements_Journal__c where SoNo__c = :Achievement.SoNo order by SoNo_DeliveryDate_Text__c];
        //System.assertEquals(0, rslts.size());
        if (rslts.size() == 2) {
            System.assertEquals(Achievement.SoNo, rslts[0].Statu_Achievements__r.Name);
            System.assertEquals(false, rslts[0].IF_LastModifiedDateTime__c == null);
            System.assertEquals(NFMUtil.parseStr2Date('20130301'), rslts[0].DeliveryDate__c);
            System.assertEquals(300, rslts[0].ShippedAmount__c);
            System.assertEquals(sajExt, rslts[0].SoNo_DeliveryDate_Text__c);

            System.assertEquals(Achievement.SoNo, rslts[1].Statu_Achievements__r.Name);
            //System.assertEquals(rslts[0].IF_LastModifiedDateTime__c, rslts[1].IF_LastModifiedDateTime__c);
            System.assertEquals(NFMUtil.parseStr2Date(Achievement.DeliveryDate), rslts[1].DeliveryDate__c);
            System.assertEquals(0, rslts[1].ShippedAmount__c);
            System.assertEquals(sajExt2, rslts[1].SoNo_DeliveryDate_Text__c);
        }
        //rslts[0].IF_LastModifiedDateTime__c = null;
        //update rslts[0];

        // IF 4回目、出荷日削除、1件目のStatu_Achievements_Journal__cは更新しないです。2件目削除。
        Achievement.DeliveryDate          = null;
        //NFM010WebService.NFM010(Achievements);
        rowData = NFMUtil.saveRowData(Achievements.Monitoring, 'NFM010', Achievements.Achievement);
        // if (String.isBlank(rowData.Log__c) == false)
        //     NFM010Rest.main(rowData.Id);

        rslts = [select Id, IF_LastModifiedDateTime__c, Statu_Achievements__r.Name,
                 DeliveryDate__c, ShippedAmount__c, SoNo_DeliveryDate_Text__c
                 from Statu_Achievements_Journal__c where SoNo__c = :Achievement.SoNo];
        //System.assertEquals(0, rslts.size());
        if (rslts.size() == 1) {
            System.assertEquals(Achievement.SoNo, rslts[0].Statu_Achievements__r.Name);
            System.assertEquals(true, rslts[0].IF_LastModifiedDateTime__c != null);    // 1件目のStatu_Achievements_Journal__cは更新しないです
            System.assertEquals(NFMUtil.parseStr2Date('20130301'), rslts[0].DeliveryDate__c);
            System.assertEquals(300, rslts[0].ShippedAmount__c);
            System.assertEquals(sajExt, rslts[0].SoNo_DeliveryDate_Text__c);
        }
        System.Test.StopTest();
    }


    /*
     * 生成一个询价OCM管理省(预测用)为能量、对应医院FSE ENG主担当和副担当有值；
     * 生成对应注残，20.发货日不为空，并且预测精度对象(注残)为真
     *
     */
    static Opportunity setupTestData() {
        ControllerUtil.EscapeNFM001Trigger = true;
        ID rectCoID = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('HP').getRecordTypeId();


        List<RecordType> rectSct = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '戦略科室分類 呼吸科'];
        if (rectSct.size() == 0) {
            throw new ControllerUtil.myException('not found 戦略科室分類 呼吸科 recodetype');
        }
        List<RecordType> rectDpt = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '診療科 消化科'];
        if (rectDpt.size() == 0) {
            throw new ControllerUtil.myException('not found 診療科 消化科 recodetype');
        }
        Opportunity opp;

        // テストデータ
        List<BatchIF_Transfer__c> transfers = new List<BatchIF_Transfer__c>();
        BatchIF_Transfer__c transfer = new BatchIF_Transfer__c();
        transfer.Table__c          = 'Statu_Achievements__c';
        transfer.Column__c         = 'SalesChannel__c';
        transfer.External_Value__c = '1';
        transfer.Internal_Value__c = 'OCM直接販売';
        transfers.add(transfer);
        transfer = new BatchIF_Transfer__c();
        transfer.Table__c          = 'Statu_Achievements__c';
        transfer.Column__c         = 'SalesChannel__c';
        transfer.External_Value__c = '3';
        transfer.Internal_Value__c = '販売店';
        transfers.add(transfer);
        insert transfers;


        User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
        System.runAs ( thisUser ) {
            List<User> insertUser = new List<User>();
            user UserGI = New User(
                              Alias = 'GI_User',
                              Email = 'GI_User@testorg.com',
                              EmailEncodingKey = 'UTF-8',
                              LastName = 'testUserGI',
                              Firstname = 'GI',
                              LanguageLocaleKey = 'zh_CN',
                              LocaleSidKey = 'zh_CN',
                              Dept__c = '能量事业本部',
                              IsActive  = true,
                              ProfileId = System.Label.ProfileId_SystemAdmin,
                              TimeZoneSidKey = 'Asia/Shanghai',
                              UserName = 'testUserGI@testorg.com');
            insertUser.add(UserGI);
            user UserET = New User(
                              Alias = 'ET_User',
                              Email = 'ET_User@testorg.com',
                              EmailEncodingKey = 'UTF-8',
                              LastName = 'testUserET',
                              Firstname = 'ET',
                              IsActive  = true,
                              Dept__c = '能量事业本部',
                              LanguageLocaleKey = 'zh_CN',
                              LocaleSidKey = 'zh_CN',
                              ProfileId = System.Label.ProfileId_SystemAdmin,
                              TimeZoneSidKey = 'Asia/Shanghai',
                              UserName = 'testUserET@testorg.com');
            insertUser.add(UserET);
            insert insertUser;

            list<User> tempUser = [select id, Alias__c from user where
                                   IsActive = true and
                                              id = :UserGI.id];
            //System.assertEquals('a', ''+tempUser);
            Account company;
            Account section;
            Account depart;
            company = new Account();
            company.RecordTypeId = rectCoID;
            company.Name         = 'NFM010TestCompany';
            company.OCM_man_province_txt__c = 'test';
            company.FSE_ENG_Main_Leader__c = UserGI.id;
            company.FSE_GI_Main_Leader__c = UserGI.id;
            company.FSE_SP_Main_Leader__c = UserGI.id;
            company.FSE_ENG_Vice_Leader__c = tempUser[0].Alias__c;
            company.FSE_GI_Vice_Leader__c = tempUser[0].Alias__c;
            company.FSE_SP_Vice_Leader__c = tempUser[0].Alias__c;
            upsert company;
            section = new Account();
            section.RecordTypeId = rectSct[0].Id;
            section.Name         = '*';
            section.Department_Class_Label__c = '消化科';
            section.ParentId                  = company.Id;
            section.Hospital_Department_Class__c = company.Id;
            upsert section;
            depart = new Account();
            depart.RecordTypeId = rectDpt[0].Id;
            depart.Name         = '*';
            depart.Department_Name__c  = 'NFM010TestDepart';
            depart.ParentId            = section.Id;
            depart.Department_Class__c = section.Id;
            depart.Hospital__c         = company.Id;
            depart.OCM_man_province_txt__c  = 'test';
            upsert depart;
            System.Test.StartTest();


            opp = new Opportunity();
            opp.AccountId           = depart.Id;
            opp.Department_Class__c = section.Id;
            opp.Hospital__c         = company.Id;
            opp.Name                = 'GZ-SP-GD3187';
            opp.Trade__c            = '内貿';
            opp.StageName           = '引合';
            opp.CloseDate           = date.newinstance(2023, 11, 30);
            opp.Group_purchase_PCL__c  = true;
            insert opp;
            System.Test.StopTest();



        }
        List<Opportunity> oppList =
            [select Opportunity_No__c, Opp_Number__c, Name, Id
             from Opportunity
             where id = : opp.id];
        return oppList[0];



    }

    static testMethod void testUpsertStatuAchievements() {
        //setupTestData();
        Opportunity opp = NFM010UpsertStatuAchievementsTriggerTest.setupTestData();
        Statu_Achievements__c sta = new Statu_Achievements__c();
        StaticParameter.EscapeNFM010UpsertStatuAchievementsTrigger = true;
        sta.DeliveryDate__c = Date.today();
        sta.Opportunity__c = opp.id;
        sta.ET_SP_Consumption__c  = false;
        sta.ContractAmount__c = 1234;
        upsert sta;


        StaticParameter.EventOpportunityPileUpExeFlg = false;
        StaticParameter.NotUpdEventCFlg = false;
        StaticParameter.EscapeNFM001Trigger = false;
        StaticParameter.EscapeNFM001AgencyContractTrigger = false;
        StaticParameter.EscapeNFM001AgencyContractTrigger2 = false;
        StaticParameter.EscapeNFM007Trigger = false;
        StaticParameter.EscapeOpportunityBefUpdTrigger = false;
        StaticParameter.EscapeOpportunityHpDeptUpdTrigger = false;
        StaticParameter.EscapeSyncOpportunityTrigger = false;
        StaticParameter.EscapeMaintenanceContractAfterUpdateTrigger = false;
        StaticParameter.EscapeSyncProduct2Trigger = false;
        // trueのとき、リードのトリガーをスルーする
        StaticParameter.EscapeLeadTrigger = false;
        StaticParameter.EscapeAccountTrigger = false;

        StaticParameter.EscapeConsumableOrderDetail2Trigger = false;

        StaticParameter.EscapeNFM010UpsertStatuAchievementsTrigger = false;
    }

    static testMethod void testUpsertStatuAchievements_DN() {
        //setupTestData();
        Opportunity opp = NFM010UpsertStatuAchievementsTriggerTest.setupTestData();
        Statu_Achievements__c sta = new Statu_Achievements__c();
        StaticParameter.EscapeNFM010UpsertStatuAchievementsTrigger = true;
        sta.DeliveryDate__c = Date.today();
        sta.Opportunity__c = opp.id;
        sta.ET_SP_Consumption__c  = false;
        sta.ContractAmount__c = 1234;
        sta.UnshippedAmount__c = 2233;
        sta.orderType__c = 'ZM17';
        sta.LastApproveDate__c = date.today();
        upsert sta;
        upsert sta;

        StaticParameter.EventOpportunityPileUpExeFlg = false;
        StaticParameter.NotUpdEventCFlg = false;
        StaticParameter.EscapeNFM001Trigger = false;
        StaticParameter.EscapeNFM001AgencyContractTrigger = false;
        StaticParameter.EscapeNFM001AgencyContractTrigger2 = false;
        StaticParameter.EscapeNFM007Trigger = false;
        StaticParameter.EscapeOpportunityBefUpdTrigger = false;
        StaticParameter.EscapeOpportunityHpDeptUpdTrigger = false;
        StaticParameter.EscapeSyncOpportunityTrigger = false;
        StaticParameter.EscapeMaintenanceContractAfterUpdateTrigger = false;
        StaticParameter.EscapeSyncProduct2Trigger = false;
        // trueのとき、リードのトリガーをスルーする
        StaticParameter.EscapeLeadTrigger = false;
        StaticParameter.EscapeAccountTrigger = false;

        StaticParameter.EscapeConsumableOrderDetail2Trigger = false;

        StaticParameter.EscapeNFM010UpsertStatuAchievementsTrigger = false;
    }


}