Untitled

mail@pastecode.io avatar
unknown
python
a year ago
2.8 kB
4
Indexable
Never
def _get_global_group_struct(global_group_structures: Path, country_code: str) -> Dict:
    """Deserialize the global_group_structure and split it up by division.

    Global group structure (GGS) looks like:
    {
        "companies": {
            "NL00000001": "UK12345678",
            "DE90000099": "UK12345678",
            "SE11111111": "UK12345678",
            ...
        },
        "groups": {
            "UK12345678": {
                "NL00000001": {
                    "DE90000099": {}
                },
                "SE11111111": {}
            },
            ...
        }
    }
    The companies section maps every company in the GGS to its ultimate holding company
    so to get the corporate hierarchy for a company you go
    company_id => ultimate_parent_company_id => groups => corporate hierarchy

    Similar to _get_safenumbers_from_global_index we break up the GGS into smaller
    chunks that are relevant to a division. We first restrict the companies section to
    just companies from the relevant country, then we groupby those companies. The
    response may look something like:
    {
        "NL000": {
            "companies" {
                "NL00000001": "UK12345678",
                ...
            }
            "groups" {
                "UK12345678": {
                    "NL00000001": {
                        "DE90000099": {}
                    },
                    "SE11111111": {}
                },
                ...
            }
        },
        "NL001": {
            "companies" {
                "NL00100001": "US11111111",
                ...
            }
            "groups" {
                "US11111111": {
                    "NL00100001": {}
                },
                ...
            }
        }
    }

    :param global_group_structure_path: A Path to the global group structure JSON file.
        File must exist.
    :param country_code: Two letter country code. Used for filtering the output.

    :return: A dictionary where keys are division strings and values are portions of
        the global group structure.
    """
    with open(global_group_structures, "rb") as f:
        global_structure_obj = orjson.loads(f.read())

    ggs = {}
    ggs_companies = {
        k: v for k, v in global_structure_obj["companies"].items()
        if k.startswith(country_code)
    }
    sorted_companies = sorted(ggs_companies.items(), key=lambda x: x[0][:-DIV_FACTOR])

    for key, group in groupby(sorted_companies, lambda x: x[0][:-DIV_FACTOR]):
        div_companies = {k: v for k, v in group}
        div_groups = {
            v: global_structure_obj["groups"][v]
            for v in div_companies.values()
        }

        ggs[key] = {"companies": div_companies, "groups": div_groups}

    return ggs