Clean up your copied environments

One of the most important things every developer should handle is to clean up the environment when the environment (or a company) is copied. Especially if the environment is managed directly by a client and they can create new copies anytime. Similarly, for copied companies.

How to do this? It’s really easy. Microsoft is already changing a few setup & system tables on environment copy (see Copy an environment – Business Central | Microsoft Learn). And we can use the same publishers.

To manipulate data when the environment is copied, use these two publishers from the codeunit 1886 “Environment Cleanup”. To clean company-specific data, use the ChangeCompany procedure together with the company name that is available as a parameter (see the example below).

codeunit 1886 "Environment Cleanup"
{
    [IntegrationEvent(false, false)]
    internal procedure OnClearCompanyConfig(CompanyName: Text; SourceEnv: Enum "Environment Type"; DestinationEnv: Enum "Environment Type")
    begin end;

    [IntegrationEvent(false, false)]
    internal procedure OnClearDatabaseConfig(SourceEnv: Enum "Environment Type"; DestinationEnv: Enum "Environment Type")
    begin end;
}

I personally using the same cleaning code for a company-copy process.

report 357 "Copy Company"
{
    [IntegrationEvent(false, false)]
    local procedure OnAfterCreatedNewCompanyByCopyCompany(NewCompanyName: Text[30]; Company: Record Company)
    begin end;
}

An example:

codeunit 50000 "TKA Copy Cleanup"
{
    [EventSubscriber(ObjectType::Codeunit, Codeunit::"Environment Cleanup", 'OnClearCompanyConfig', '', false, false)]
    local procedure OnClearCompanyConfigEnvironmentCleanup(CompanyName: Text)
    begin
        CleanOnEnvironmentOrCompanyCopy(CompanyName);
    end;

    [EventSubscriber(ObjectType::Report, Report::"Copy Company", 'OnAfterCreatedNewCompanyByCopyCompany', '', false, false)]
    local procedure OnAfterCreatedNewCompanyByCopyCompanyCopyCompany(NewCompanyName: Text[30])
    begin
        CleanOnEnvironmentOrCompanyCopy(NewCompanyName);
    end;

    local procedure CleanOnEnvironmentOrCompanyCopy(CompanyName: Text)
    var
        SalesReceivablesSetup: Record "Sales & Receivables Setup";
    begin
        SalesReceivablesSetup.ChangeCompany(CompanyName);
        if not SalesReceivablesSetup.Get() then
            exit;
        if SalesReceivablesSetup."TKA My Integration URL" = '' then
            exit;
        SalesReceivablesSetup."TKA My Integration URL" := 'https://api.DEVserver.xxxxxx.com.au';
        SalesReceivablesSetup.Modify(false);
    end;
}