Fixed languages.

Fixed languages.

jsoniq version "1.0";

module namespace resolution = "http://28.io/modules/xbrl/resolution";

import module namespace components = "http://28.io/modules/xbrl/components";
import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace facts = "http://28.io/modules/xbrl/facts";
import module namespace hypercubes = "http://28.io/modules/xbrl/hypercubes";
import module namespace networks = "http://28.io/modules/xbrl/networks";

(: TODOs
- Options for relationship networks (formulaAxis, depth)
:)

(:~
 : Converts a definition breakdown to a structural breakdown
 :
 : @param $breakdown a breandowk
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the option object
 :
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND if a definition node kind
 : is unrecognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if a root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if a root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted, structural breakdown.
 :)
declare %private function resolution:convert-breakdown(
    $breakdown as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $parent-child-order as string? := ($breakdown.ParentChildOrder, $parent-child-order)[1]

    let $labels as array := $breakdown.BreakdownLabels

    let $unbalanced-trees as object* := resolution:convert-definition-nodes(
        $breakdown.BreakdownTrees[],
        $components,
        $parent-child-order,
        $concepts,
        $options
    )
    let $balanced-trees as object* := resolution:height-balance($unbalanced-trees)

    return {
        BreakdownLabels: $labels,
        BreakdownTrees: [ $balanced-trees ]
    }
};

(:~
 : Converts each definition node to one or more structural nodes
 :
 : @param $definition-nodes some definition nodes.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND if a definition node kind
 : is unrecognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if a root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if a root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:convert-definition-nodes(
    $definition-nodes as object*,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    for $definition-node as object in $definition-nodes
    let $parent-child-order as string? := ($definition-node.ParentChildOrder, $parent-child-order)[1]
    for $converted-node in
      switch($definition-node.Kind)
      case "Rule" return resolution:convert-rule-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "Aspect" return resolution:convert-aspect-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "ConceptRelationship" return resolution:convert-concept-relationship-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "DimensionRelationship" return resolution:convert-dimension-relationship-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts)
      default return error(
          QName("resolution:UNKNOWN-DEFINITION-NODE-KIND"),
          "Unknown definition node kind: $definition-node.Kind")
    return if(exists($definition-node.Id))
           then copy $c := $converted-node
                modify for $node in ($c, descendant-objects($c).Children[])
                       return insert json { Id: $definition-node.Id } into $node
                return $c
           else $converted-node
};

(:~
 : Retrieves the labels from the components' cache (default language)
 : or from the remove collection cache.
 :
 : @param $concept-names a sequence of concept names.
 : @param $components a sequence of components
 : @param $concepts the concept objects (for inferring the labels)
 : @param $label-role the desired label role
 : @param $options the options object
 :
 : @return the labels
 :)
declare %private function resolution:labels(
    $concept-names as string*,
    $components as object*,
    $concepts as object*,
    $label-role as string,
    $options as object?) as string*
{
    let $components-with-the-language-as-default :=
        for $component in $components
        let $default-language := ($component.DefaultLanguage, "en-US")[1]
        where not $default-language ne $options.Language
        return $component

    let $labels-from-local-metadata as string* :=
        let $default-hypercubes as object* :=
            hypercubes:hypercubes-for-components($components-with-the-language-as-default, "xbrl:DefaultHypercube")
        for $local-metadata as object in
            descendant-objects($default-hypercubes.Aspects)
        let $local-metadata-name := $local-metadata.Name
        let $local-metadata-preferred-label-role as string := ($local-metadata.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1]
        where $local-metadata-name = $concept-names and
              $local-metadata-preferred-label-role eq $label-role
        return
            $local-metadata.Label

    let $labels-from-concepts-collection as string* :=
        if(empty($labels-from-local-metadata))
        then
            concepts:labels-for-components(
                $concept-names,
                $components,
                $label-role,
                ($options.Language, "en-US")[1],
                $concepts,
                ())
        else ()

    return ($labels-from-local-metadata, $labels-from-concepts-collection)
 };

(:~
 : Converts a rule definition node to one or more structural nodes.
 : A rule node restricts a dimension to a value.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:convert-rule-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    let $main-members := values(values($definition-node.AspectRulesSet))

    let $labels := (
        $definition-node.Labels[],
        resolution:labels(
            $main-members,
            $components,
            $concepts,
            $concepts:STANDARD_LABEL_ROLE,
            $options)
    )

    let $children := resolution:convert-definition-nodes(
        $definition-node.Children[],
        $components,
        $parent-child-order,
        $concepts,
        $options)
    let $roll-up := {
        Labels: [ ],
        ConstraintSets : {
            "": { }

        },
        RollUp: true
    }
    let $constraint-sets := {|
        for $tag in keys($definition-node.AspectRulesSet)
        return {
            $tag: {|
                for $aspect in keys($definition-node.AspectRulesSet.$tag)
                return {
                    $aspect: $definition-node.AspectRulesSet.$tag.$aspect
                }
            |}
        }
    |}
    let $merged-children :=
        for $child in $children
        return copy $c := $child
        modify for $tag in keys($c.ConstraintSets)
               return replace value of json $c.ConstraintSets.$tag with facts:merge-objects(
                    $c.ConstraintSets.$tag,
                    $constraint-sets.$tag,
                    true)
        return $c
    return switch(true)
           case not $definition-node.Abstract and $definition-node.Merge
                return error(QName("resolution:NON-ABSTRACT-MERGE-NODE"), "A definition rule node cannot be non-abstract and merged.")
           case $definition-node.Merge return $merged-children
           case $definition-node.Abstract return {|
                {
                    Labels: [  $labels ],
                    ConstraintSets: $constraint-sets
                },
                if(exists($definition-node.TagSelectors))
                then {
                    TagSelectors: $definition-node.TagSelectors
                }
                else (),
                if(exists($children)) then {
                    Children: [ $children ]
                }
                else ()
           |}
            default return {|
                {
                    Labels: [  $labels ],
                    ConstraintSets: $constraint-sets
                },
                if(exists($definition-node.TagSelectors))
                then {
                    TagSelectors: $definition-node.TagSelectors
                }
                else (),
                if(exists($children))
                then {
                    Children: switch(true)
                              case $parent-child-order eq "parentFirst" return [$roll-up, $children]
                              default return [$children, $roll-up]
                }
                else (),
                if($definition-node.IsTotal)
                then { IsTotal: true }
                else ()
            |}
};

(:~
 : Convert an aspect definition node to one or more structural nodes.
 : An aspect nodes will expand to all values found in the fact pool during
 : the layouting stage.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-aspect-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $children :=  resolution:convert-definition-nodes(
        $definition-node.Children[],
        $components,
        $parent-child-order,
        $concepts,
        $options)
    let $constrained-aspect := $definition-node.Aspect
    return {|
        {
            Open: true,
            Aspect: $constrained-aspect
        },
        if ($children)
        then { Children: [ $children ] }
        else ()
    |}
};

(:~
 : Convert a concept relationship definition node to one or more structural nodes.
 : A concept relationship node will automatically expand a network to a hierarchy
 : of structural nodes.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root concept
 : cannot be resolved.
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-concept-relationship-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $link-role := $definition-node.LinkRole
    let $link-name := $definition-node.LinkName
    let $arc-role := $definition-node.ArcRole
    let $arc-name := $definition-node.ArcName
    let $root := $definition-node.RelationshipSource
    let $network as object? := networks:networks-for-components($components)[
        $$.LinkRole eq $link-role and
        $$.LinkName eq $link-name and
        $$.ArcRole eq $arc-role and
        $$.ArcName eq $arc-name
    ]
    let $subnetwork := descendant-objects($network.Trees)[$$.Name eq $root]
    return if(exists($subnetwork))
    then resolution:expand-concept-network($subnetwork, $components, $parent-child-order, $concepts, $options)
    else error(QName("resolution:UNRESOLVED-CONCEPT-RELATIONSHIP"), $root || ": The concept root could not be resolved.")
};

(:~
 : Helper, recursive function for resolution:convert-concept-relationship-node#3
 :
 : @param $network a network to expand.
 : @param $components a sequence of components.
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:expand-concept-network(
    $network as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    let $concept as string := $network.Name
    let $default-languages as string* := $components.$components:DEFAULT-LANGUAGE
    let $default-languages := if(exists($default-languages)) then $default-languages else "en-US"
    let $default-hypercube := hypercubes:hypercubes-for-components($components, "xbrl:DefaultHypercube")
    let $concept-metadata := $default-hypercube.Aspects."xbrl:Concept".Domains."xbrl:ConceptDomain".Members.$concept[1]
    let $label :=
        if(every $language in $default-languages satisfies $language eq $options.Language)
        then $network.Label
        else
        resolution:labels(
            $concept,
            $components,
            $concepts,
            ($network.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1],
            $options)
    return
    {|
        {
            Labels: [ $label ],
            ConstraintSets: {
                "" : { "xbrl:Concept" : $concept }
            }
        },

        switch($network.PreferredLabelRole)
        case "http://www.xbrl.org/2003/role/totalLabel"
        return {
            IsTotal: true
        }
        case "http://www.xbrl.org/2009/role/negatedLabel"
        return {
            IsNegated: true
        }
        case "http://www.xbrl.org/2009/role/negatedTerseLabel"
        return {
            IsNegated: true
        }
        case "http://www.xbrl.org/2003/role/periodStartLabel"
        return {
            TagSelectors: [ "table.periodStart" ]
        }
        case "http://www.xbrl.org/2003/role/periodEndLabel"
        return {
            TagSelectors: [ "table.periodEnd" ],
            IsTotal: true
        }
        default return (),

        let $sub-networks := (values($network.To), $network.To[])
        let $converted-subnetworks :=
            for $sub-network in $sub-networks
            let $order := $sub-network.Order
            order by $order
            return
                resolution:expand-concept-network(
                        $sub-network,
                        $components,
                        $parent-child-order,
                        $concepts,
                        $options
                    )
        let $roll-up :=
            if($concept-metadata.IsAbstract)
            then ()
            else {
                Labels: [],
                RollUp: true
            }
        where exists($converted-subnetworks)
        return {
            Children: [
                switch($parent-child-order)
                case "parentFirst" return ($roll-up, $converted-subnetworks)
                default return ($converted-subnetworks, $roll-up)
            ]
        }

    |}
};

(:~
 : Convert a dimension relationship definition node to one or more structural nodes.
 : A dimension relationship node will automatically expand a network to a hierarchy
 : of structural nodes.
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root member
 : cannot be resolved.
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-dimension-relationship-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*) as object
{
    let $link-role := $definition-node.LinkRole
    let $dimension := $definition-node.Dimension
    let $root := $definition-node.RelationshipSource
    let $hypercubes as object* := hypercubes:hypercubes-for-components($components[$$.Role eq $link-role])
    let $subnetwork as object := descendant-objects($hypercubes.Aspects.$dimension)[$$.Name eq $root][1]
    return if(exists($subnetwork))
    then resolution:expand-dimension-network($dimension, $subnetwork, $components, $parent-child-order, $concepts)
    else error(QName("resolution:UNRESOLVED-DIMENSION-RELATIONSHIP"), $root || ": The dimension member root could not be resolved.")
};

(:
    Helper, recursive function for resolution:convert-dimension-relationship-node#3
:)
declare function resolution:expand-dimension-network(
    $dimension as string,
    $network as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*) as object
{
    let $value := $network.Name
    let $label :=
          if(not $options.Language != $components.$components:DEFAULT-LANGUAGE)
          then $network.Label
          else
          resolution:labels(
            $value,
            $components,
            $concepts,
            ($network.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1],
            $options)
    return
    {|
        {
            Labels: [ $label],
            ConstraintSets: {
                "" : { $dimension : $value }
            }
        },
        let $sub-networks := values($network.Members)
        let $converted-subnetworks :=
            for $sub-network in $sub-networks
            return resolution:expand-dimension-network(
                        $dimension,
                        $sub-network,
                        $components,
                        $parent-child-order,
                        $concepts
                )
        let $roll-up :={
            Labels: [],
            RollUp: true
        }
        where exists($converted-subnetworks)
        return { Children: [ $converted-subnetworks, $roll-up ] }
    |}
};

(:
    Helper function that returns the depth of breakdown trees set.
:)
declare function resolution:depth($axis-breakdown-trees as object*) as integer
{
    switch(true)
    case empty($axis-breakdown-trees) return 0
    case empty($axis-breakdown-trees.Children[]) return 1
    default return max($axis-breakdown-trees.Children[] ! (1 + resolution:depth($$)))
};

(:~
 : Helper function that height-balances a breakdown trees set,
 : by adding roll-up nodes to get a uniform depth.
 :
 : @param $axis-breakdown-trees the breakdown trees for an axis
 :
 : @return the balanced breakdown trees.
 :)
declare function resolution:height-balance($axis-breakdown-trees as object*) as object*
{
    let $depth := resolution:depth($axis-breakdown-trees)
    return resolution:height-balance($axis-breakdown-trees, $depth)
};

(:~
 : Helper, recursive function for resolution:height-balance#1.
 :
 : @param $axis-breakdown-trees the breakdown trees for an axis
 : @parem the depth at which these trees should get balanced.
 :
 : @return the balanced breakdown trees.
 :)
declare function resolution:height-balance($axis-breakdown-trees as object*, $desired-depth as integer) as object*
{
  let $roll-up-cell := {
    CellLabels: [],
    ConstraintSets: {"" : {}},
    RollUp: true
  }
  return
    for $tree in $axis-breakdown-trees
    return switch(true)
           case $desired-depth gt 1 and empty($tree.Children)
           return copy $t := $tree
                  modify insert json {
                    Children: [
                      resolution:height-balance($roll-up-cell, $desired-depth - 1)
                    ]
                  } into $t
                  return $t
                case $desired-depth gt 1 and exists($tree.Children)
                  return copy $t := $tree
                         modify replace value of json $t.Children with [
                           $t.Children[] ! resolution:height-balance($$, $desired-depth - 1)
                         ]
                         return $t
                case $desired-depth eq 1 and empty($tree.Children)
                  return $tree
                default
                  return error(QName("resolution:UNFORESEEN-ERROR"), "An error occurred while height-balancing")
};

(:~
 : Retrieves the metadata for some members from a component.
 :
 : @param $components a sequence of components.
 : @param $member-names the names of the members for which to retrieve the metadata.
 :
 : @return the metadata for the supplied members.
 :)
declare %private function resolution:metadata(
    $components as object*,
    $member-names as string*) as object*
{
    let $default-hypercube := hypercubes:hypercubes-for-components($components, "xbrl:DefaultHypercube")
    return descendant-objects($default-hypercube.Aspects)[$$.Name = $member-names][1]
};

(:~
  Resolves a definition model to a structural model, given a component.

  @param $definition-model A definition mode, in 28msec's proprietary JSON format.
  @param $component A component, in 28msec's proprietary JSON format.

  @error resolution:UNFORESEEN-ERROR Something went wrong, contact us.
  @error resolution:UNKNOWN-DEFINITION-NODE-KIND A definition node was not recognized.

  @return a structural model
:)
declare function resolution:resolve(
    $definition-model as object,
    $components as object*) as object
{
    resolution:resolve($definition-model, $components, ())
};

(:~
 : Resolves a definition model to a structural model, given a component.
 :
 : @param $definition-model A definition mode, in 28msec's proprietary JSON format.
 : @param $component A component, in 28msec's proprietary JSON format.
 : @param $options Optional parameters among which
 : <ul>
 :   <li>Hypercube: override the components' hypercubes with the provided hypercube
 :      (this will only affect the default values used later in the layout pipeline).</li>
 :    <li>Language: override the components' default language in the rendering.</li>
 : </ul>
 :
 : @error resolution:UNFORESEEN-ERROR Something went wrong, contact us.
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND A definition node was not recognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if the root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return a structural model
 :)
declare function resolution:resolve(
    $definition-model as object,
    $components as object*,
    $options as object?) as object
{
    let $concepts as object* := concepts:concepts-for-components(
        $concepts:ALL_CONCEPT_NAMES,
        $components)
    let $hypercubes as object* :=
        if(exists($options.Hypercube))
        then $options.Hypercube
        else values($components.Hypercubes)
    return {
        ModelKind: "StructuralModel",
        TableSetLabels: $definition-model.Labels,
        Component: {
            Role: $components.Role[1],
            Label: $components.Label[1]
        },
        TableSet : [
            {
                Breakdowns: {|
                    for $axis in keys($definition-model.Breakdowns)
                    return {
                        $axis: [
                            for $breakdown in $definition-model.Breakdowns.$axis[]
                            return resolution:convert-breakdown($breakdown,
                                                                $components,
                                                                $definition-model.ParentChildOrder,
                                                                $concepts,
                                                                $options)
                        ]
                    }
                |}
            }
        ],
        GlobalConstraintSet: $definition-model.TableFilters,
        GlobalConstraintLabels: {|
            for $dimension in keys($definition-model.TableFilters)
            let $dimension-label as string* := resolution:metadata($components, $dimension).Label[1]
            let $value := $definition-model.TableFilters.$dimension
            let $value-label as string* := if($value instance of string) then resolution:metadata($components, $value).Label else ()
            return ({ $dimension: $dimension-label[1] }[exists($dimension-label)],
                    { $value: $value-label[1] }[exists($value-label)]
                    )
        |},
        DimensionDefaults: {|
            for $dimension as string in keys($hypercubes.Aspects)
            let $hypercube-default as atomic? := $hypercubes.Aspects.$dimension.Default[1]
            where exists($hypercube-default)
            return {
                $dimension: $hypercube-default
            }
        |}
    }
};

jsoniq version "1.0";

module namespace resolution = "http://28.io/modules/xbrl/resolution";

import module namespace components = "http://28.io/modules/xbrl/components";
import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace facts = "http://28.io/modules/xbrl/facts";
import module namespace hypercubes = "http://28.io/modules/xbrl/hypercubes";
import module namespace networks = "http://28.io/modules/xbrl/networks";

(: TODOs
- Options for relationship networks (formulaAxis, depth)
:)

(:~
 : Converts a definition breakdown to a structural breakdown
 :
 : @param $breakdown a breandowk
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the option object
 :
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND if a definition node kind
 : is unrecognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if a root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if a root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted, structural breakdown.
 :)
declare %private function resolution:convert-breakdown(
    $breakdown as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $parent-child-order as string? := ($breakdown.ParentChildOrder, $parent-child-order)[1]

    let $labels as array := $breakdown.BreakdownLabels

    let $unbalanced-trees as object* := resolution:convert-definition-nodes(
        $breakdown.BreakdownTrees[],
        $components,
        $parent-child-order,
        $concepts,
        $options
    )
    let $balanced-trees as object* := resolution:height-balance($unbalanced-trees)

    return {
        BreakdownLabels: $labels,
        BreakdownTrees: [ $balanced-trees ]
    }
};

(:~
 : Converts each definition node to one or more structural nodes
 :
 : @param $definition-nodes some definition nodes.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND if a definition node kind
 : is unrecognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if a root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if a root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:convert-definition-nodes(
    $definition-nodes as object*,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    for $definition-node as object in $definition-nodes
    let $parent-child-order as string? := ($definition-node.ParentChildOrder, $parent-child-order)[1]
    for $converted-node in
      switch($definition-node.Kind)
      case "Rule" return resolution:convert-rule-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "Aspect" return resolution:convert-aspect-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "ConceptRelationship" return resolution:convert-concept-relationship-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts,
          $options)
      case "DimensionRelationship" return resolution:convert-dimension-relationship-node(
          $definition-node,
          $components,
          $parent-child-order,
          $concepts)
      default return error(
          QName("resolution:UNKNOWN-DEFINITION-NODE-KIND"),
          "Unknown definition node kind: $definition-node.Kind")
    return if(exists($definition-node.Id))
           then copy $c := $converted-node
                modify for $node in ($c, descendant-objects($c).Children[])
                       return insert json { Id: $definition-node.Id } into $node
                return $c
           else $converted-node
};

(:~
 : Retrieves the labels from the components' cache (default language)
 : or from the remove collection cache.
 :
 : @param $concept-names a sequence of concept names.
 : @param $components a sequence of components
 : @param $concepts the concept objects (for inferring the labels)
 : @param $label-role the desired label role
 : @param $options the options object
 :
 : @return the labels
 :)
declare %private function resolution:labels(
    $concept-names as string*,
    $components as object*,
    $concepts as object*,
    $label-role as string,
    $options as object?) as string*
{
    let $components-with-the-language-as-default :=
        $components[not $$.$components:DEFAULT-LANGUAGE ne $options.Language]

    let $labels-from-local-metadata as string* :=
        let $default-hypercubes as object* :=
            hypercubes:hypercubes-for-components($components-with-the-language-as-default, "xbrl:DefaultHypercube")
        for $local-metadata as object in
            descendant-objects($default-hypercubes.Aspects)
        let $local-metadata-name := $local-metadata.Name
        let $local-metadata-preferred-label-role as string := ($local-metadata.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1]
        where $local-metadata-name = $concept-names and
              $local-metadata-preferred-label-role eq $label-role
        return
            $local-metadata.Label

    let $labels-from-concepts-collection as string* :=
        if(empty($labels-from-local-metadata))
        then
            concepts:labels-for-components(
                $concept-names,
                $components,
                $label-role,
                ($options.Language, "en-US")[1],
                $concepts,
                ())
        else ()

    return ($labels-from-local-metadata, $labels-from-concepts-collection)
 };

(:~
 : Converts a rule definition node to one or more structural nodes.
 : A rule node restricts a dimension to a value.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:convert-rule-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    let $main-members := values(values($definition-node.AspectRulesSet))

    let $labels := (
        $definition-node.Labels[],
        resolution:labels(
            $main-members,
            $components,
            $concepts,
            $concepts:STANDARD_LABEL_ROLE,
            $options)
    )

    let $children := resolution:convert-definition-nodes(
        $definition-node.Children[],
        $components,
        $parent-child-order,
        $concepts,
        $options)
    let $roll-up := {
        Labels: [ ],
        ConstraintSets : {
            "": { }

        },
        RollUp: true
    }
    let $constraint-sets := {|
        for $tag in keys($definition-node.AspectRulesSet)
        return {
            $tag: {|
                for $aspect in keys($definition-node.AspectRulesSet.$tag)
                return {
                    $aspect: $definition-node.AspectRulesSet.$tag.$aspect
                }
            |}
        }
    |}
    let $merged-children :=
        for $child in $children
        return copy $c := $child
        modify for $tag in keys($c.ConstraintSets)
               return replace value of json $c.ConstraintSets.$tag with facts:merge-objects(
                    $c.ConstraintSets.$tag,
                    $constraint-sets.$tag,
                    true)
        return $c
    return switch(true)
           case not $definition-node.Abstract and $definition-node.Merge
                return error(QName("resolution:NON-ABSTRACT-MERGE-NODE"), "A definition rule node cannot be non-abstract and merged.")
           case $definition-node.Merge return $merged-children
           case $definition-node.Abstract return {|
                {
                    Labels: [  $labels ],
                    ConstraintSets: $constraint-sets
                },
                if(exists($definition-node.TagSelectors))
                then {
                    TagSelectors: $definition-node.TagSelectors
                }
                else (),
                if(exists($children)) then {
                    Children: [ $children ]
                }
                else ()
           |}
            default return {|
                {
                    Labels: [  $labels ],
                    ConstraintSets: $constraint-sets
                },
                if(exists($definition-node.TagSelectors))
                then {
                    TagSelectors: $definition-node.TagSelectors
                }
                else (),
                if(exists($children))
                then {
                    Children: switch(true)
                              case $parent-child-order eq "parentFirst" return [$roll-up, $children]
                              default return [$children, $roll-up]
                }
                else (),
                if($definition-node.IsTotal)
                then { IsTotal: true }
                else ()
            |}
};

(:~
 : Convert an aspect definition node to one or more structural nodes.
 : An aspect nodes will expand to all values found in the fact pool during
 : the layouting stage.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 : @param $options the options object
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-aspect-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $children :=  resolution:convert-definition-nodes(
        $definition-node.Children[],
        $components,
        $parent-child-order,
        $concepts,
        $options)
    let $constrained-aspect := $definition-node.Aspect
    return {|
        {
            Open: true,
            Aspect: $constrained-aspect
        },
        if ($children)
        then { Children: [ $children ] }
        else ()
    |}
};

(:~
 : Convert a concept relationship definition node to one or more structural nodes.
 : A concept relationship node will automatically expand a network to a hierarchy
 : of structural nodes.
 :
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root concept
 : cannot be resolved.
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-concept-relationship-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object
{
    let $link-role := $definition-node.LinkRole
    let $link-name := $definition-node.LinkName
    let $arc-role := $definition-node.ArcRole
    let $arc-name := $definition-node.ArcName
    let $root := $definition-node.RelationshipSource
    let $network as object? := networks:networks-for-components($components)[
        $$.LinkRole eq $link-role and
        $$.LinkName eq $link-name and
        $$.ArcRole eq $arc-role and
        $$.ArcName eq $arc-name
    ]
    let $subnetwork := descendant-objects($network.Trees)[$$.Name eq $root]
    return if(exists($subnetwork))
    then resolution:expand-concept-network($subnetwork, $components, $parent-child-order, $concepts, $options)
    else error(QName("resolution:UNRESOLVED-CONCEPT-RELATIONSHIP"), $root || ": The concept root could not be resolved.")
};

(:~
 : Helper, recursive function for resolution:convert-concept-relationship-node#3
 :
 : @param $network a network to expand.
 : @param $components a sequence of components.
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @return the converted structural nodes.
 :)
declare %private function resolution:expand-concept-network(
    $network as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*,
    $options as object?) as object*
{
    let $concept := $network.Name
    let $default-hypercube := hypercubes:hypercubes-for-components($components, "xbrl:DefaultHypercube")
    let $concept-metadata := $default-hypercube.Aspects."xbrl:Concept".Domains."xbrl:ConceptDomain".Members.$concept[1]
    let $label :=
        if(not $options.Language != $components.$components:DEFAULT-LANGUAGE)
        then $network.Label
        else
        resolution:labels(
            $concept,
            $components,
            $concepts,
            ($network.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1],
            $options)
    return
    {|
        {
            Labels: [ $label ],
            ConstraintSets: {
                "" : { "xbrl:Concept" : $concept }
            }
        },

        switch($network.PreferredLabelRole)
        case "http://www.xbrl.org/2003/role/totalLabel"
        return {
            IsTotal: true
        }
        case "http://www.xbrl.org/2009/role/negatedLabel"
        return {
            IsNegated: true
        }
        case "http://www.xbrl.org/2009/role/negatedTerseLabel"
        return {
            IsNegated: true
        }
        case "http://www.xbrl.org/2003/role/periodStartLabel"
        return {
            TagSelectors: [ "table.periodStart" ]
        }
        case "http://www.xbrl.org/2003/role/periodEndLabel"
        return {
            TagSelectors: [ "table.periodEnd" ],
            IsTotal: true
        }
        default return (),

        let $sub-networks := (values($network.To), $network.To[])
        let $converted-subnetworks :=
            for $sub-network in $sub-networks
            let $order := $sub-network.Order
            order by $order
            return
                resolution:expand-concept-network(
                        $sub-network,
                        $components,
                        $parent-child-order,
                        $concepts,
                        $options
                    )
        let $roll-up :=
            if($concept-metadata.IsAbstract)
            then ()
            else {
                Labels: [],
                RollUp: true
            }
        where exists($converted-subnetworks)
        return {
            Children: [
                switch($parent-child-order)
                case "parentFirst" return ($roll-up, $converted-subnetworks)
                default return ($converted-subnetworks, $roll-up)
            ]
        }

    |}
};

(:~
 : Convert a dimension relationship definition node to one or more structural nodes.
 : A dimension relationship node will automatically expand a network to a hierarchy
 : of structural nodes.
 : @param $definition-node a definition node.
 : @param $components a sequence of components
 : @param $parent-child-order "parentFirst" or "childrenFirst"
 : @param $concepts the concept objects (for inferring the labels)
 :
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root member
 : cannot be resolved.
 :
 : @return the converted structural node.
 :)
declare %private function resolution:convert-dimension-relationship-node(
    $definition-node as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*) as object
{
    let $link-role := $definition-node.LinkRole
    let $dimension := $definition-node.Dimension
    let $root := $definition-node.RelationshipSource
    let $hypercubes as object* := hypercubes:hypercubes-for-components($components[$$.Role eq $link-role])
    let $subnetwork as object := descendant-objects($hypercubes.Aspects.$dimension)[$$.Name eq $root][1]
    return if(exists($subnetwork))
    then resolution:expand-dimension-network($dimension, $subnetwork, $components, $parent-child-order, $concepts)
    else error(QName("resolution:UNRESOLVED-DIMENSION-RELATIONSHIP"), $root || ": The dimension member root could not be resolved.")
};

(:
    Helper, recursive function for resolution:convert-dimension-relationship-node#3
:)
declare function resolution:expand-dimension-network(
    $dimension as string,
    $network as object,
    $components as object*,
    $parent-child-order as string?,
    $concepts as object*) as object
{
    let $value := $network.Name
    let $label :=
          if(not $options.Language != $components.$components:DEFAULT-LANGUAGE)
          then $network.Label
          else
          resolution:labels(
            $value,
            $components,
            $concepts,
            ($network.PreferredLabelRole, $concepts:STANDARD_LABEL_ROLE)[1],
            $options)
    return
    {|
        {
            Labels: [ $label],
            ConstraintSets: {
                "" : { $dimension : $value }
            }
        },
        let $sub-networks := values($network.Members)
        let $converted-subnetworks :=
            for $sub-network in $sub-networks
            return resolution:expand-dimension-network(
                        $dimension,
                        $sub-network,
                        $components,
                        $parent-child-order,
                        $concepts
                )
        let $roll-up :={
            Labels: [],
            RollUp: true
        }
        where exists($converted-subnetworks)
        return { Children: [ $converted-subnetworks, $roll-up ] }
    |}
};

(:
    Helper function that returns the depth of breakdown trees set.
:)
declare function resolution:depth($axis-breakdown-trees as object*) as integer
{
    switch(true)
    case empty($axis-breakdown-trees) return 0
    case empty($axis-breakdown-trees.Children[]) return 1
    default return max($axis-breakdown-trees.Children[] ! (1 + resolution:depth($$)))
};

(:~
 : Helper function that height-balances a breakdown trees set,
 : by adding roll-up nodes to get a uniform depth.
 :
 : @param $axis-breakdown-trees the breakdown trees for an axis
 :
 : @return the balanced breakdown trees.
 :)
declare function resolution:height-balance($axis-breakdown-trees as object*) as object*
{
    let $depth := resolution:depth($axis-breakdown-trees)
    return resolution:height-balance($axis-breakdown-trees, $depth)
};

(:~
 : Helper, recursive function for resolution:height-balance#1.
 :
 : @param $axis-breakdown-trees the breakdown trees for an axis
 : @parem the depth at which these trees should get balanced.
 :
 : @return the balanced breakdown trees.
 :)
declare function resolution:height-balance($axis-breakdown-trees as object*, $desired-depth as integer) as object*
{
  let $roll-up-cell := {
    CellLabels: [],
    ConstraintSets: {"" : {}},
    RollUp: true
  }
  return
    for $tree in $axis-breakdown-trees
    return switch(true)
           case $desired-depth gt 1 and empty($tree.Children)
           return copy $t := $tree
                  modify insert json {
                    Children: [
                      resolution:height-balance($roll-up-cell, $desired-depth - 1)
                    ]
                  } into $t
                  return $t
                case $desired-depth gt 1 and exists($tree.Children)
                  return copy $t := $tree
                         modify replace value of json $t.Children with [
                           $t.Children[] ! resolution:height-balance($$, $desired-depth - 1)
                         ]
                         return $t
                case $desired-depth eq 1 and empty($tree.Children)
                  return $tree
                default
                  return error(QName("resolution:UNFORESEEN-ERROR"), "An error occurred while height-balancing")
};

(:~
 : Retrieves the metadata for some members from a component.
 :
 : @param $components a sequence of components.
 : @param $member-names the names of the members for which to retrieve the metadata.
 :
 : @return the metadata for the supplied members.
 :)
declare %private function resolution:metadata(
    $components as object*,
    $member-names as string*) as object*
{
    let $default-hypercube := hypercubes:hypercubes-for-components($components, "xbrl:DefaultHypercube")
    return descendant-objects($default-hypercube.Aspects)[$$.Name = $member-names][1]
};

(:~
  Resolves a definition model to a structural model, given a component.

  @param $definition-model A definition mode, in 28msec's proprietary JSON format.
  @param $component A component, in 28msec's proprietary JSON format.

  @error resolution:UNFORESEEN-ERROR Something went wrong, contact us.
  @error resolution:UNKNOWN-DEFINITION-NODE-KIND A definition node was not recognized.

  @return a structural model
:)
declare function resolution:resolve(
    $definition-model as object,
    $components as object*) as object
{
    resolution:resolve($definition-model, $components, ())
};

(:~
 : Resolves a definition model to a structural model, given a component.
 :
 : @param $definition-model A definition mode, in 28msec's proprietary JSON format.
 : @param $component A component, in 28msec's proprietary JSON format.
 : @param $options Optional parameters among which
 : <ul>
 :   <li>Hypercube: override the components' hypercubes with the provided hypercube
 :      (this will only affect the default values used later in the layout pipeline).</li>
 :    <li>Language: override the components' default language in the rendering.</li>
 : </ul>
 :
 : @error resolution:UNFORESEEN-ERROR Something went wrong, contact us.
 : @error resolution:UNKNOWN-DEFINITION-NODE-KIND A definition node was not recognized.
 : @error resolution:UNRESOLVED-CONCEPT-RELATIONSHIP if the root concept
 : cannot be resolved.
 : @error resolution:UNRESOLVED-DIMENSION-RELATIONSHIP if the root member
 : cannot be resolved.
 : @error resolution:NON-ABSTRACT-MERGE-NODE if a rule node is merge,
 : but non-abstract.
 :
 : @return a structural model
 :)
declare function resolution:resolve(
    $definition-model as object,
    $components as object*,
    $options as object?) as object
{
    let $concepts as object* := concepts:concepts-for-components(
        $concepts:ALL_CONCEPT_NAMES,
        $components)
    let $hypercubes as object* :=
        if(exists($options.Hypercube))
        then $options.Hypercube
        else values($components.Hypercubes)
    return {
        ModelKind: "StructuralModel",
        TableSetLabels: $definition-model.Labels,
        Component: {
            Role: $components.Role[1],
            Label: $components.Label[1]
        },
        TableSet : [
            {
                Breakdowns: {|
                    for $axis in keys($definition-model.Breakdowns)
                    return {
                        $axis: [
                            for $breakdown in $definition-model.Breakdowns.$axis[]
                            return resolution:convert-breakdown($breakdown,
                                                                $components,
                                                                $definition-model.ParentChildOrder,
                                                                $concepts,
                                                                $options)
                        ]
                    }
                |}
            }
        ],
        GlobalConstraintSet: $definition-model.TableFilters,
        GlobalConstraintLabels: {|
            for $dimension in keys($definition-model.TableFilters)
            let $dimension-label as string* := resolution:metadata($components, $dimension).Label[1]
            let $value := $definition-model.TableFilters.$dimension
            let $value-label as string* := if($value instance of string) then resolution:metadata($components, $value).Label else ()
            return ({ $dimension: $dimension-label[1] }[exists($dimension-label)],
                    { $value: $value-label[1] }[exists($value-label)]
                    )
        |},
        DimensionDefaults: {|
            for $dimension as string in keys($hypercubes.Aspects)
            let $hypercube-default as atomic? := $hypercubes.Aspects.$dimension.Default[1]
            where exists($hypercube-default)
            return {
                $dimension: $hypercube-default
            }
        |}
    }
};


replaced reportschemas collection with reports collection

jsoniq version "1.0";
(:
 : Copyright 2013 28msec Inc.
 :)

(:~
 :
This module provides functions for storing, retrieving, and modifying
 : report schemas. Report schemas can be used in BizQL queries. They can be
 : instantiated generating a business report.

 :
 :
Report schemas are nothing else than a user-defined component. However,
 : one of their hypercubes (the default hypercube), as well as two of their
 : networks (presentation, concept-map) are special. A report schema is identified
 : with an RID (Report schema ID).

 :
 :
With this module, you can retrieve facts from an archive according to a report
 : schema. You can retrieve them as a (2D) fact table, or populate the presentation
 : network of the report schema with them. The concept map network will be used
 : by default to map the report schema concepts to reported concepts.

 :
 :
Report schemas are stored in the collection reportschemas in
 : the project's MongoDB database.

 :
 :
A report schema needs to be a syntactically valid JSound document.

 :
 : @author Charles Hoffman
 : @author Matthias Brantner
 : @author Dennis Knochenwefel
 : @author Ghislain Fourny
 :
 :)
module namespace report-schemas = "http://28.io/modules/xbrl/report-schemas";

import module namespace hypercubes = "http://28.io/modules/xbrl/hypercubes";
import module namespace networks = "http://28.io/modules/xbrl/networks";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:~
 : Name of the collection the report schemas are stored in.
 :)
declare variable $report-schemas:col as string := "reports";

(:~
 : Joker for all archives.
 :)
declare variable $report-schemas:ALL_ARCHIVES as boolean := true;

(:~
 :
Retrieves all report schemas.

 :
 : @return all report schemas.
 :)
declare function report-schemas:report-schemas() as object*
{
  collection($report-schemas:col)
};

(:~
 :
Return the report schemas with the given names (RIDs).

 :
 : @param $report-schemas-or-ids the ids of the report schemas (RIDs) or the
 : report schemas themselves.
 :
 : @return the report schemas with the given RIDs or the
 :   empty sequence if no report schema was found or the input
 : is an empty sequence.
 :)
declare function report-schemas:report-schemas($report-schemas-or-ids as item*) as object*
{
  let $ids as string* :=
    for $s in $report-schemas-or-ids
    where $s instance of string
    return $s
  let $schemas as object* :=
    for $s in $report-schemas-or-ids
    where $s instance of object
    return $s
  return
    (
      $schemas,
      if (exists($ids))
      then find($report-schemas:col,
                { "_id" : { "$in" : [ $ids ! report-schemas:rid($$) ] } } )
      else ()
    )
};

(:~
 :
Adds the given report schema to the database.

 :
 : @param $report-schema the report schema to add.
 :
 : @return the empty sequence.
 :
 : @error report-schemas:INVALID-SCHEMA if the given report schema object does not
 :   contain a name field
 : @error report-schemas:EXISTS if a report schema with the given name already exists
 :)
declare %an:sequential function report-schemas:add($report-schema as object) as ()
{
  if (empty($report-schema._id))
  then error(QName("report-schemas:INVALID-SCHEMA"),
    "schema object does not contain an _id field");
  else if (exists(report-schemas:report-schemas($report-schema._id)))
       then fn:error(QName("report-schemas:EXISTS"),
                     $report-schema._id || ": report schema already exists");
       else insert($report-schemas:col, $report-schema);
};

(:~
 :
Updates a report schema.

 :
 :
Replaces a report schema in the database with the given schema.
 : The schema to be replaced is identified by the value of the _id
 : field of the given schema (RID).

 :
 : @param $report-schema the new report schema
 :
 : @return the empty sequence
 :
 : @error report-schemas:DOES-NOT-EXIST if a report schema with the given name does not exist.
 :)
declare %an:sequential function report-schemas:update($report-schema as object)
as ()
{
  let $existing := report-schemas:report-schemas($report-schema._id)
  return if (empty($existing))
         then error(QName("report-schemas:DOES-NOT-EXIST"),
             $report-schema._id || ": report-schema with given id does not exist");
         else edit($existing, $report-schema);
};

(:~
 :
Deletes a report schema from the database.

 :
 : @param $report-schema-or-id the report schema to delete or its RID.
 :
 : @return the empty sequence.
 :
 : @error report-schemas:DOES-NOT-EXIST if no report schema with the given RID
 :   exists.
 :)
declare %an:sequential function report-schemas:delete($report-schema-or-id as item)
as ()
{
  let $report-schema := report-schemas:report-schemas($report-schema-or-id)
  let $id := report-schemas:rid($report-schema-or-id)
  return if (empty($report-schema))
  then error(QName("report-schemas:DOES-NOT-EXIST"),
    $id || ": report schema with given _id does not exist");
  else delete($report-schema);
};

(:~
 :
 :
Converts the input to a normalized report schema identifier (RID). The input
 : can be either a pure RID, or a report schema object which contains an RID.

 :
 : @param $report-schema-or-id a report schema identifier (RID)) or a report schema object.
 :
 : @error report-schemas:INVALID_PARAMETER if the RID or report schema is not valid
 :
 : @return the normalized RID.
 :)
declare function report-schemas:rid($report-schema-or-id as item) as atomic
{
  typeswitch ($report-schema-or-id)
  case object return
    let $rid := $report-schema-or-id._id
    return if(exists($rid))
           then $rid
           else error(QName("report-schemas:INVALID_PARAMETER"),
                      "Invalid report schema provided (no _id field)")
  case $rid as atomic return $rid
  default return error(
      QName("report-schemas:INVALID_PARAMETER"),
      "Invalid report schema or RID (must be an object or an atomic): "
      || serialize($report-schema-or-id))
};

(:~
 :
 :
Retrieves all facts from the supplied archives, that are relevant to the
 : supplied schema, and populates them with the default dimension values
 : when missing.

 :
 :
 : @param $schema a report schema or its RID,
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:facts(
    $schema as item,
    $archives as item*
)
as object*
{
  report-schemas:facts($schema, $archives, {})
};

(:~
 :
 :
Retrieves all facts from the supplied archives, that are relevant to the
 : supplied schema, and populates them with the default dimension values
 : when missing.

 :
 :
 : @param $schema a report schema or its RID,
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 : @param $options standard fact retrieving options as well as
 :

 :
HypercubeName: the name of a hypercube to be taken from the schema (only used if
 :          the Hypercube option is absent.

 :

 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:facts(
    $schema as item,
    $archives as item*,
    $options as object?
)
as object*
{
  let $schema := report-schemas:report-schemas($schema)
  let $concept-map := networks:networks-for-components-and-short-names(
      $schema,
      "ConceptMap")
  let $rules := $schema.Rules
  let $hypercube :=
    if(exists($options.Hypercube))
    then $options.Hypercube
    else hypercubes:hypercubes-for-components(
             $schema,
             if (exists($options.HypercubeName))
             then $options.HypercubeName
             else "xbrl:DefaultHypercube"
    )
  return hypercubes:facts-for-hypercube(
      $hypercube,
      $archives,
      {|
        $options,
        { "ConceptMaps": $concept-map }[exists($concept-map)],
        { "Rules": $rules }[exists($rules)]
      |}
  )
};

(:~
 :
 :
Retrieves all facts from the supplied archives, that are relevant to the
 : supplied schema, and populates them with the default dimension values
 : when missing.

 :
 :
 : @param $schema a schema or its RID,
 : @param $archives a sequence of archives or their AIDs.
 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:fact-table(
  $schema as item,
  $archives as item*
)
as array
{
  report-schemas:fact-table($schema, $archives, {})
};

(:~
 :
 :
Retrieves all facts from the supplied archives, that are relevant to the
 : supplied schema, and populates them with the default dimension values
 : when missing.

 :
 :
 : @param $schema a schema or its RID,
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 : @param $options standard fact retrieving options as well as
 :

 :
HypercubeName: the name of a hypercube to be taken from the schema (only used if
 :          the Hypercube option is absent.

 :

 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:fact-table(
  $schema as item,
  $archives as item*,
  $options as object?) as array
{
  let $schema := report-schemas:report-schemas($schema)
  let $hypercube :=
    if(exists($options.Hypercube))
    then $options.Hypercube
    else hypercubes:hypercubes-for-components(
             $schema,
             if (exists($options.HypercubeName))
             then $options.HypercubeName
             else "xbrl:DefaultHypercube"
    )
  let $facts := report-schemas:facts($schema, $archives, $options)
  return hypercubes:fact-table-for-hypercube-and-facts($hypercube, $facts)
};

(:~
 :
 :
Populates a concept-tree network with all facts from the supplied archives,
 : that are relevant to the
 : supplied schema. Default dimension values are added to the facts
 : when missing.

 :
 : @param $schema.
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:populate-with-facts(
  $schema as item,
  $archives as item*
)
as object*
{
  report-schemas:populate-with-facts($schema, $archives, {})
};

(:~
 :
 :
Populates a concept-tree network with all facts from the supplied archives,
 : that are relevant to the
 : supplied schema. Default dimension values are added to the facts
 : when missing.

 :
 : @param $schema.
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 : @param $options standard fact retrieving options as well as
 :

 :
HypercubeName: the name of a hypercube to be taken from the schema (only used if
 :          the Hypercube option is absent.

 :

 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:populate-with-facts(
  $schema as item,
  $archives as item*,
  $options as object?) as object*
{
  hypercubes:populate-networks-with-retrieved-facts(
    networks:networks-for-components-and-short-names(report-schemas:report-schemas($schema), "Presentation"),
    report-schemas:facts($schema, $archives, $options)
  )
};

jsoniq version "1.0";
(:
 : Copyright 2013 28msec Inc.
 :)

(:~
 :
This module provides functions for storing, retrieving, and modifying
 : report schemas. Report schemas can be used in BizQL queries. They can be
 : instantiated generating a business report.

 :
 :
Report schemas are nothing else than a user-defined component. However,
 : one of their hypercubes (the default hypercube), as well as two of their
 : networks (presentation, concept-map) are special. A report schema is identified
 : with an RID (Report schema ID).

 :
 :
With this module, you can retrieve facts from an archive according to a report
 : schema. You can retrieve them as a (2D) fact table, or populate the presentation
 : network of the report schema with them. The concept map network will be used
 : by default to map the report schema concepts to reported concepts.

 :
 :
Report schemas are stored in the collection reportschemas in
 : the project's MongoDB database.

 :
 :
A report schema needs to be a syntactically valid JSound document.

 :
 : @author Charles Hoffman
 : @author Matthias Brantner
 : @author Dennis Knochenwefel
 : @author Ghislain Fourny
 :
 :)
module namespace report-schemas = "http://28.io/modules/xbrl/report-schemas";

import module namespace hypercubes = "http://28.io/modules/xbrl/hypercubes";
import module namespace networks = "http://28.io/modules/xbrl/networks";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:~
 : Name of the collection the report schemas are stored in.
 :)
declare variable $report-schemas:col as string := "reportschemas";

(:~
 : Joker for all archives.
 :)
declare variable $report-schemas:ALL_ARCHIVES as boolean := true;

(:~
 :
Retrieves all report schemas.

 :
 : @return all report schemas.
 :)
declare function report-schemas:report-schemas() as object*
{
  collection($report-schemas:col)
};

(:~
 :
Return the report schemas with the given names (RIDs).

 :
 : @param $report-schemas-or-ids the ids of the report schemas (RIDs) or the
 : report schemas themselves.
 :
 : @return the report schemas with the given RIDs or the
 :   empty sequence if no report schema was found or the input
 : is an empty sequence.
 :)
declare function report-schemas:report-schemas($report-schemas-or-ids as item*) as object*
{
  let $ids as string* :=
    for $s in $report-schemas-or-ids
    where $s instance of string
    return $s
  let $schemas as object* :=
    for $s in $report-schemas-or-ids
    where $s instance of object
    return $s
  return
    (
      $schemas,
      if (exists($ids))
      then find($report-schemas:col,
                { "_id" : { "$in" : [ $ids ! report-schemas:rid($$) ] } } )
      else ()
    )
};

(:~
 :
Adds the given report schema to the database.

 :
 : @param $report-schema the report schema to add.
 :
 : @return the empty sequence.
 :
 : @error report-schemas:INVALID-SCHEMA if the given report schema object does not
 :   contain a name field
 : @error report-schemas:EXISTS if a report schema with the given name already exists
 :)
declare %an:sequential function report-schemas:add($report-schema as object) as ()
{
  if (empty($report-schema._id))
  then error(QName("report-schemas:INVALID-SCHEMA"),
    "schema object does not contain an _id field");
  else if (exists(report-schemas:report-schemas($report-schema._id)))
       then fn:error(QName("report-schemas:EXISTS"),
                     $report-schema._id || ": report schema already exists");
       else insert($report-schemas:col, $report-schema);
};

(:~
 :
Updates a report schema.

 :
 :
Replaces a report schema in the database with the given schema.
 : The schema to be replaced is identified by the value of the _id
 : field of the given schema (RID).

 :
 : @param $report-schema the new report schema
 :
 : @return the empty sequence
 :
 : @error report-schemas:DOES-NOT-EXIST if a report schema with the given name does not exist.
 :)
declare %an:sequential function report-schemas:update($report-schema as object)
as ()
{
  let $existing := report-schemas:report-schemas($report-schema._id)
  return if (empty($existing))
         then error(QName("report-schemas:DOES-NOT-EXIST"),
             $report-schema._id || ": report-schema with given id does not exist");
         else edit($existing, $report-schema);
};

(:~
 :
Deletes a report schema from the database.

 :
 : @param $report-schema-or-id the report schema to delete or its RID.
 :
 : @return the empty sequence.
 :
 : @error report-schemas:DOES-NOT-EXIST if no report schema with the given RID
 :   exists.
 :)
declare %an:sequential function report-schemas:delete($report-schema-or-id as item)
as ()
{
  let $report-schema := report-schemas:report-schemas($report-schema-or-id)
  let $id := report-schemas:rid($report-schema-or-id)
  return if (empty($report-schema))
  then error(QName("report-schemas:DOES-NOT-EXIST"),
    $id || ": report schema with given _id does not exist");
  else delete($report-schema);
};

(:~
 :
 :
Converts the input to a normalized report schema identifier (RID). The input
 : can be either a pure RID, or a report schema object which contains an RID.

 :
 : @param $report-schema-or-id a report schema identifier (RID)) or a report schema object.
 :
 : @error report-schemas:INVALID_PARAMETER if the RID or report schema is not valid
 :
 : @return the normalized RID.
 :)
declare function report-schemas:rid($report-schema-or-id as item) as atomic
{
  typeswitch ($report-schema-or-id)
  case object return
    let $rid := $report-schema-or-id._id
    return if(exists($rid))
           then $rid
           else error(QName("report-schemas:INVALID_PARAMETER"),
                      "Invalid report schema provided (no _id field)")
  case $rid as atomic return $rid
  default return error(
      QName("report-schemas:INVALID_PARAMETER"),
      "Invalid report schema or RID (must be an object or an atomic): "
      || serialize($report-schema-or-id))
};

(:~
 :
 :
Retrieves all facts from the supplied archives, that are relevant to the
 : supplied schema, and populates them with the default dimension values
 : when missing.

 :
 :
 : @param $schema a report schema or its RID,
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:facts(
    $schema as item,
    $archives as item*
)
as object*
{
  report-schemas:facts($schema, $archives, {})
};

(:~
 :
 :
Retrieves all facts from the supplied archives, that are relevant to the
 : supplied schema, and populates them with the default dimension values
 : when missing.

 :
 :
 : @param $schema a report schema or its RID,
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 : @param $options standard fact retrieving options as well as
 :

 :
HypercubeName: the name of a hypercube to be taken from the schema (only used if
 :          the Hypercube option is absent.

 :

 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:facts(
    $schema as item,
    $archives as item*,
    $options as object?
)
as object*
{
  let $schema := report-schemas:report-schemas($schema)
  let $concept-map := networks:networks-for-components-and-short-names(
      $schema,
      "ConceptMap")
  let $rules := $schema.Rules
  let $hypercube :=
    if(exists($options.Hypercube))
    then $options.Hypercube
    else hypercubes:hypercubes-for-components(
             $schema,
             if (exists($options.HypercubeName))
             then $options.HypercubeName
             else "xbrl:DefaultHypercube"
    )
  return hypercubes:facts-for-hypercube(
      $hypercube,
      $archives,
      {|
        $options,
        { "ConceptMaps": $concept-map }[exists($concept-map)],
        { "Rules": $rules }[exists($rules)]
      |}
  )
};

(:~
 :
 :
Retrieves all facts from the supplied archives, that are relevant to the
 : supplied schema, and populates them with the default dimension values
 : when missing.

 :
 :
 : @param $schema a schema or its RID,
 : @param $archives a sequence of archives or their AIDs.
 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:fact-table(
  $schema as item,
  $archives as item*
)
as array
{
  report-schemas:fact-table($schema, $archives, {})
};

(:~
 :
 :
Retrieves all facts from the supplied archives, that are relevant to the
 : supplied schema, and populates them with the default dimension values
 : when missing.

 :
 :
 : @param $schema a schema or its RID,
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 : @param $options standard fact retrieving options as well as
 :

 :
HypercubeName: the name of a hypercube to be taken from the schema (only used if
 :          the Hypercube option is absent.

 :

 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:fact-table(
  $schema as item,
  $archives as item*,
  $options as object?) as array
{
  let $schema := report-schemas:report-schemas($schema)
  let $hypercube :=
    if(exists($options.Hypercube))
    then $options.Hypercube
    else hypercubes:hypercubes-for-components(
             $schema,
             if (exists($options.HypercubeName))
             then $options.HypercubeName
             else "xbrl:DefaultHypercube"
    )
  let $facts := report-schemas:facts($schema, $archives, $options)
  return hypercubes:fact-table-for-hypercube-and-facts($hypercube, $facts)
};

(:~
 :
 :
Populates a concept-tree network with all facts from the supplied archives,
 : that are relevant to the
 : supplied schema. Default dimension values are added to the facts
 : when missing.

 :
 : @param $schema.
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:populate-with-facts(
  $schema as item,
  $archives as item*
)
as object*
{
  report-schemas:populate-with-facts($schema, $archives, {})
};

(:~
 :
 :
Populates a concept-tree network with all facts from the supplied archives,
 : that are relevant to the
 : supplied schema. Default dimension values are added to the facts
 : when missing.

 :
 : @param $schema.
 : @param $archives a sequence of archives or their AIDs or $report-schemas:ALL_ARCHIVES for no filtering.
 : @param $options standard fact retrieving options as well as
 :

 :
HypercubeName: the name of a hypercube to be taken from the schema (only used if
 :          the Hypercube option is absent.

 :

 :
 : @return a sequence of facts with populated dimension values.
 :)
declare function report-schemas:populate-with-facts(
  $schema as item,
  $archives as item*,
  $options as object?) as object*
{
  hypercubes:populate-networks-with-retrieved-facts(
    networks:networks-for-components-and-short-names(report-schemas:report-schemas($schema), "Presentation"),
    report-schemas:facts($schema, $archives, $options)
  )
};


:books: Add doc.

:books: Add doc.

jsoniq version "1.0";
module namespace data-source-wrapper = "http://28.io/modules/xbrl/data-source-wrapper";

import module namespace config = "http://apps.28.io/config";
import module namespace mongo-wrapper = "http://28.io/modules/xbrl/mongo-wrapper";

(:~
 :
Count how many objects a collection contains.

 :
 : @param $collection the name of a collection.
 :
 : @return the number of objects in this collection.
 :)
declare function data-source-wrapper:count(
    $collection as string
) as integer {
    switch($config:query-db.category)
    case "MongoDB" return mongo-wrapper:count($collection)
    default return ()
};

(:~
 :
Filters the objects in a collection.

 :
The filter format is as follows.

 :
A filter query consists of a hierarchy of nested objects, the keys of
 : which MUST NOT contain the dollar symbol.

 :
The leaves of this object hierarchy MUST be one of the tree:

 :

 :
An atomic ("exact match").
 :
An array of atomics ("one-of-these-values match").
 :
The exact object { "$exists" : true } ("must-exist match").
 :

 :
The semantics of a filter query is that it performs a
 : conjunction on the filters done on all possible paths.

 :
For example, with only atomics as leafs to keep it simple:

 :

 : {
 :   "Aspects" : {
 :     "xbrl:Concept" : "us-gaap:Assets",
 :     "xbrl:Entity" : "4962"
 :   },
 :   "Value" : 3
 : }
 :

 :
 :
filters for facts $f that satisfy all of the following:

 :

 :
$f.Aspects."xbrl:Concept" eq "us-gaap:Assets"
 :
$f.Aspects."xbrl:Entity" eq "4962"
 :
$f.Value eq 3
 :

 :
If an atomic $a is used as a leaf, with path A.B.C, the filter of this
 : path is: $f.A.B.C eq $a

 :
If an array $a is used as a leaf, with path A.B.C, the filter of this path
 : is: $f.A.B.C = $a[]

 :
If { "$exists" : true } is used as a leaf, with path A.B.C, the filter of
 : this path is: exists($f.A.B.C)

 :
 :
Finally, it also allowed to wrap several filtering queries as specified
 : above in a disjunctive close, in an array associated with the key "$or":

 :

 : {
 :   "$or" : [ <query1>, <query2>, ... ]
 : }
 :

 :
 : @param $collection the name of a collection.
 : @param $query a filter query.
 :
 : @return the number of objects in this collection.
 :)
declare function data-source-wrapper:find(
    $collection as string,
    $query as object
) as object()*
{
  switch($config:query-db.category)
  case "MongoDB" return mongo-wrapper:find($collection, $query)
  default return ()
};

declare function data-source-wrapper:find(
    $collection as string,
    $query as object,
    $projection as object
) as object()*
{
  switch($config:query-db.category)
  case "MongoDB" return mongo-wrapper:find($collection, $query, $projection)
  default return ()
};

declare function data-source-wrapper:text-search(
    $collection as string,
    $query as object) as object*
{
  switch($config:query-db.category)
  case "MongoDB" return mongo-wrapper:run-cmd-deterministic(
    {|
      { "text" : $collection },
      $query
    |}).results[].obj
  default return ()
};

declare function data-source-wrapper:connection() as anyURI?
{
  switch($config:query-db.category)
  case "MongoDB" return mongo-wrapper:connection()
  default return ()
};

jsoniq version "1.0";
module namespace data-source-wrapper = "http://28.io/modules/xbrl/data-source-wrapper";

import module namespace config = "http://apps.28.io/config";
import module namespace mongo-wrapper = "http://28.io/modules/xbrl/mongo-wrapper";

declare function data-source-wrapper:count(
    $collection as string
) as integer {
    switch($config:query-db.category)
    case "MongoDB" return mongo-wrapper:count($collection)
    default return ()
};

declare function data-source-wrapper:find(
    $collection as string,
    $query as object
) as object()*
{
  switch($config:query-db.category)
  case "MongoDB" return mongo-wrapper:find($collection, $query)
  default return ()
};

declare function data-source-wrapper:find(
    $collection as string,
    $query as object,
    $projection as object
) as object()*
{
  switch($config:query-db.category)
  case "MongoDB" return mongo-wrapper:find($collection, $query, $projection)
  default return ()
};

declare function data-source-wrapper:text-search(
    $collection as string,
    $query as object) as object*
{
  switch($config:query-db.category)
  case "MongoDB" return mongo-wrapper:run-cmd-deterministic(
    {|
      { "text" : $collection },
      $query
    |}).results[].obj
  default return ()
};

declare function data-source-wrapper:connection() as anyURI?
{
  switch($config:query-db.category)
  case "MongoDB" return mongo-wrapper:connection()
  default return ()
};


Update multiplexer.jq

Update multiplexer.jq

jsoniq version "1.0";

(:
 : Copyright 2012-2014 28msec Inc.
 :)
(:~
 :
This module provides functionality for automatically fetching entities, etc, from the
 : appropriate profile.

 :
 : @author Ghislain Fourny
 :
 :)
module namespace multiplexer = "http://28.io/modules/xbrl/profiles/multiplexer";

import module namespace archives = "http://28.io/modules/xbrl/archives";

import module namespace companies = "http://28.io/modules/xbrl/profiles/sec/companies";
import module namespace fiscal-core = "http://28.io/modules/xbrl/profiles/sec/fiscal/core";

import module namespace japan = "http://28.io/modules/xbrl/profiles/japan/core";

declare function multiplexer:entities(
  $profile-name as string,
  $eid as string*,
  $cik as string*,
  $tag as string*,
  $ticker as string*,
  $sic as string*) as object*
{
  switch($profile-name)
  case "sec" return
    for $entity in companies:companies(
      $cik,
      $tag,
      $ticker,
      $sic,
      $eid)
    order by $entity.Profiles.SEC.CompanyName
    return $entity
  default return
    for $entity in japan:entities($cik, $eid, $tag)
    order by $entity._id
    return $entity
};

declare function multiplexer:filings(
  $profile-name as string,
  $entities as item*,
  $fiscalPeriod as string*,
  $fiscalYear as integer*,
  $aid as string*) as object*
{
  switch($profile-name)
  case "sec" return fiscal-core:filings(
      $entities,
      $fiscalPeriod,
      $fiscalYear,
      $aid)
  case "japan" return japan:filings(
      $entities,
      $fiscalYear,
      $fiscalPeriod,
      $aid)
  default return archives:archives-for-entities($entities)
};

jsoniq version "1.0";

(:
 : Copyright 2012-2014 28msec Inc.
 :)
(:~
 :
This module provides functionality for automatically fetching entities, etc, from the
 : appropriate profile.

 :
 : @author Ghislain Fourny
 :
 :)
module namespace multiplexer = "http://28.io/modules/xbrl/profiles/multiplexer";

import module namespace archives = "http://28.io/modules/xbrl/archives";
import module namespace entities = "http://28.io/modules/xbrl/entities";

import module namespace companies = "http://28.io/modules/xbrl/profiles/sec/companies";
import module namespace fiscal-core = "http://28.io/modules/xbrl/profiles/sec/fiscal/core";

import module namespace japan = "http://28.io/modules/xbrl/profiles/japan/core";

declare function multiplexer:entities(
  $profile-name as string,
  $eid as string*,
  $cik as string*,
  $tag as string*,
  $ticker as string*,
  $sic as string*) as object*
{
  switch($profile-name)
  case "sec" return
    for $entity in companies:companies(
      $cik,
      $tag,
      $ticker,
      $sic,
      $eid)
    order by $entity.Profiles.SEC.CompanyName
    return $entity
  default return
    for $entity in japan:entities($cik, $eid, $tag)
    order by $entity._id
    return $entity
};

declare function multiplexer:filings(
  $profile-name as string,
  $entities as item*,
  $fiscalPeriod as string*,
  $fiscalYear as integer*,
  $aid as string*) as object*
{
  switch($profile-name)
  case "sec" return fiscal-core:filings(
      $entities,
      $fiscalPeriod,
      $fiscalYear,
      $aid)
  case "japan" return japan:filings(
      $entities,
      $fiscalYear,
      $fiscalPeriod,
      $aid)
  default return archives:archives-for-entities($entities)
};


:green_heart: Fix build.

:green_heart: Fix build.

import module namespace archives = "http://28.io/modules/xbrl/archives";
import module namespace entities = "http://28.io/modules/xbrl/entities";
import module namespace hypercubes = "http://28.io/modules/xbrl/hypercubes";
import module namespace conversion = "http://28.io/modules/xbrl/conversion";
import module namespace reports = "http://28.io/modules/xbrl/reports";
import module namespace components = "http://28.io/modules/xbrl/components";
import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace facts = "http://28.io/modules/xbrl/facts";
import module namespace labels = "http://28.io/modules/xbrl/labels";

import module namespace multiplexer = "http://28.io/modules/xbrl/profiles/multiplexer";
import module namespace fiscal-core = "http://28.io/modules/xbrl/profiles/sec/fiscal/core";

import module namespace response = "http://www.28msec.com/modules/http-response";

import module namespace config = "http://apps.28.io/config";
import module namespace session = "http://apps.28.io/session";
import module namespace api = "http://apps.28.io/api";

(: Query parameters :)
declare  %rest:case-insensitive                 variable $token         as string? external;
declare  %rest:env                              variable $request-uri   as string  external;
declare  %rest:case-insensitive                 variable $format        as string? external;
declare  %rest:case-insensitive %rest:distinct  variable $cik           as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $edinetcode    as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $tag           as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $ticker        as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $sic           as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $fiscalYear    as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $fiscalPeriod  as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $fiscalPeriodType  as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $eid           as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $aid           as string* external;
declare  %rest:case-insensitive                 variable $validate      as boolean external := false;
declare  %rest:case-insensitive                 variable $labels        as boolean external := false;
declare  %rest:case-insensitive                 variable $report        as string? external;
declare  %rest:case-insensitive                 variable $profile-name  as string  external := $config:profile-name;

session:audit-call($token);

(: Post-processing :)
let $format as string? := api:preprocess-format($format, $request-uri)
let $fiscalYear as integer* := api:preprocess-fiscal-years($fiscalYear)
let $fiscalPeriod as string* := api:preprocess-fiscal-periods($fiscalPeriod)
let $fiscalPeriodType as string* := api:preprocess-fiscal-period-types($fiscalPeriodType)
let $tag as string* := api:preprocess-tags($tag)

let $cik as string* :=
    switch($profile-name)
    case "sec" return $cik
    case "japan" return $edinetcode
    default return ()

(: Entity resolution :)
let $entities := multiplexer:entities(
  $profile-name,
  $eid,
  $cik,
  $tag,
  $ticker,
  $sic, ())

let $report-id as string? := $report
let $report as object? := reports:reports($report-id)

return
if(empty($report))
then
{
      response:status-code(404);
      session:error("report with id '" || $report-id || "' does not exist.", $format)
} else

    (: Fact resolution :)
    let $filter-override as object? :=
        if($profile-name eq "sec")
        then fiscal-core:filter-override(
            $entities,
            $fiscalYear,
            $fiscalPeriod,
            $fiscalPeriodType,
            $aid)
        else components:filter-override($entities, $aid)
    let $facts as object* :=
        let $hypercube := hypercubes:hypercubes-for-components($report)[1]
        let $filtered-aspects := values($hypercube.Aspects)[exists(($$.Members, $$.DomainRestriction))]
        return if(count($filtered-aspects) lt $config:filtered-aspects and not exists(($filter-override)))
        then {
              response:status-code(403);
              session:error("The report filters are too weak, which leads to too big an output.", $format)
        } else
            components:facts(
                    $report,
                    {|
                        { FilterOverride: $filter-override }[exists($filter-override)],
                        { Validate: $validate }
                    |}
                )

    let $concepts as object* := $report.Concepts[]
    let $language as string := ( $report.$components:DEFAULT-LANGUAGE , $labels:AMERICAN_ENGLISH )[1]
    let $role as string := ( $report.Role, $concepts:ANY_COMPONENT_LINK_ROLE )[1]
    let $facts :=
      if($profile-name eq "sec")
      then
        for $fact in $facts
        group by $archive := $fact.Aspects."xbrl28:Archive"
        let $archive := archives:archives($archive)
        let $entity := entities:entities($archive.Entity)
        for $fact in $fact
        return
        {|
            trim($fact, ("Labels", "EntityRegistrantName")),
            { "EntityRegistrantName" : $entity.Profiles.SEC.CompanyName },
            if($labels)
            then
                let $labels as object? := labels:labels-for-facts(
                  $fact,
                  $labels:STANDARD_LABEL_ROLE,
                  $language,
                  $concepts,
                  $entities,
                  ()
                )
                return
                    { Labels : $labels }
            else ()
        |}
      else
        for $fact in $facts
        let $labels := labels:labels-for-facts(
          $fact,
          $labels:STANDARD_LABEL_ROLE,
          $language,
          $concepts,
          $entities,
          ()
        )
        return
        {|
            trim($fact, "Labels"),
            { Labels : $labels-object }[exists($labels)]
        |}

    let $facts := api:normalize-facts($facts)

    let $results :=
        switch ($format)
        case "xml" return {
            response:serialization-parameters({"omit-xml-declaration" : false, indent : true });
            session:comment("xml",
            {
                NumFacts : count($facts),
                TotalNumFacts: session:num-facts(),
                TotalNumArchives: session:num-archives(),
                TotalNumEntities: session:num-entities()
            }),
            <FactTable NetworkIdentifier="http://bizql.io/facttable-for-report"
                    TableName="xbrl:FactTableForReport">{
                conversion:facts-to-xml($facts, { Caller: "Report" })
            }</FactTable>
        }
        case "text" case "csv" return {
            response:content-type("text/csv");
            response:header("Content-Disposition", "attachment; filename=facts.csv");
            conversion:facts-to-csv($facts, { Caller: "Report"})
        }
        case "excel" return {
            response:content-type("application/vnd.ms-excel");
            response:header("Content-Disposition", "attachment; filename=fact.csv");
            conversion:facts-to-csv($facts, { Caller: "Report"})
        }
        default return {
            response:content-type("application/json");
            response:serialization-parameters({"indent" : true});
            {|
                { NetworkIdentifier : "http://secxbrl.info/facts" },
                { TableName : "xbrl:Facts" },
                { FactTable : [ $facts ] },
                session:comment("json", {
                        NumFacts : count($facts),
                        TotalNumFacts: session:num-facts(),
                        TotalNumArchives: session:num-archives(),
                        TotalNumEntities: session:num-entities()
                    })
            |}
        }
    return api:check-and-return-results($token, $results, $format)

import module namespace archives = "http://28.io/modules/xbrl/archives";
import module namespace entities = "http://28.io/modules/xbrl/entities";
import module namespace hypercubes = "http://28.io/modules/xbrl/hypercubes";
import module namespace conversion = "http://28.io/modules/xbrl/conversion";
import module namespace reports = "http://28.io/modules/xbrl/reports";
import module namespace components = "http://28.io/modules/xbrl/components";
import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace facts = "http://28.io/modules/xbrl/facts";
import module namespace labels = "http://28.io/modules/xbrl/labels";

import module namespace multiplexer = "http://28.io/modules/xbrl/profiles/multiplexer";
import module namespace fiscal-core = "http://28.io/modules/xbrl/profiles/sec/fiscal/core";

import module namespace response = "http://www.28msec.com/modules/http-response";

import module namespace config = "http://apps.28.io/config";
import module namespace session = "http://apps.28.io/session";
import module namespace api = "http://apps.28.io/api";

(: Query parameters :)
declare  %rest:case-insensitive                 variable $token         as string? external;
declare  %rest:env                              variable $request-uri   as string  external;
declare  %rest:case-insensitive                 variable $format        as string? external;
declare  %rest:case-insensitive %rest:distinct  variable $cik           as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $edinetcode    as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $tag           as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $ticker        as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $sic           as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $fiscalYear    as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $fiscalPeriod  as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $fiscalPeriodType  as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $eid           as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $aid           as string* external;
declare  %rest:case-insensitive                 variable $validate      as boolean external := false;
declare  %rest:case-insensitive                 variable $labels        as boolean external := false;
declare  %rest:case-insensitive                 variable $report        as string? external;
declare  %rest:case-insensitive                 variable $profile-name  as string  external := $config:profile-name;

session:audit-call($token);

(: Post-processing :)
let $format as string? := api:preprocess-format($format, $request-uri)
let $fiscalYear as integer* := api:preprocess-fiscal-years($fiscalYear)
let $fiscalPeriod as string* := api:preprocess-fiscal-periods($fiscalPeriod)
let $fiscalPeriodType as string* := api:preprocess-fiscal-period-types($fiscalPeriodType)
let $tag as string* := api:preprocess-tags($tag)

let $cik as string* :=
    switch($profile-name)
    case "sec" return $cik
    case "japan" return $edinetcode
    default return ()

(: Entity resolution :)
let $entities := multiplexer:entities(
  $profile-name,
  $eid,
  $cik,
  $tag,
  $ticker,
  $sic, ())

let $report-id as string? := $report
let $report as object? := reports:reports($report-id)

return
if(empty($report))
then
{
      response:status-code(404);
      session:error("report with id '" || $report-id || "' does not exist.", $format)
} else

    (: Fact resolution :)
    let $filter-override as object? :=
        if($profile-name eq "sec")
        then fiscal-core:filter-override(
            $entities,
            $fiscalYear,
            $fiscalPeriod,
            $fiscalPeriodType,
            $aid)
        else components:filter-override($entities, $aid)
    let $facts as object* :=
        let $hypercube := hypercubes:hypercubes-for-components($report)[1]
        let $filtered-aspects := values($hypercube.Aspects)[exists(($$.Members, $$.DomainRestriction))]
        return if(count($filtered-aspects) lt $config:filtered-aspects and not exists(($filter-override)))
        then {
              response:status-code(403);
              session:error("The report filters are too weak, which leads to too big an output.", $format)
        } else
            components:facts(
                    $report,
                    {|
                        { FilterOverride: $filter-override }[exists($filter-override)],
                        { Validate: $validate }
                    |}
                )

    let $concepts as object* := $report.Concepts[]
    let $language as string := ( $report.$components:DEFAULT-LANGUAGE , $labels:AMERICAN_ENGLISH )[1]
    let $role as string := ( $report.Role, $concepts:ANY_COMPONENT_LINK_ROLE )[1]
    let $facts :=
      if($profile-name eq "sec")
      then
        for $fact in $facts
        group by $archive := $fact.Aspects."xbrl28:Archive"
        let $archive := archives:archives($archive)
        let $entity := entities:entities($archive.Entity)
        for $fact in $fact
        return
        {|
            trim($fact, ("Labels", "EntityRegistrantName")),
            { "EntityRegistrantName" : $entity.Profiles.SEC.CompanyName },
            if($labels)
            then
                let $labels as object? := facts:labels($fact, $labels:STANDARD_LABEL_ROLE, $language, $concepts, ())
                return
                    { Labels : $labels }
            else ()
        |}
      else
        for $fact in $facts
        let $labels := labels:labels-for-facts(
          $fact,
          $labels:STANDARD_LABEL_ROLE,
          $language,
          $concepts,
          $entities,
          ()
        )
        return
        {|
            trim($fact, "Labels"),
            { Labels : $labels-object }[exists($labels)]
        |}

    let $facts := api:normalize-facts($facts)

    let $results :=
        switch ($format)
        case "xml" return {
            response:serialization-parameters({"omit-xml-declaration" : false, indent : true });
            session:comment("xml",
            {
                NumFacts : count($facts),
                TotalNumFacts: session:num-facts(),
                TotalNumArchives: session:num-archives(),
                TotalNumEntities: session:num-entities()
            }),
            <FactTable NetworkIdentifier="http://bizql.io/facttable-for-report"
                    TableName="xbrl:FactTableForReport">{
                conversion:facts-to-xml($facts, { Caller: "Report" })
            }</FactTable>
        }
        case "text" case "csv" return {
            response:content-type("text/csv");
            response:header("Content-Disposition", "attachment; filename=facts.csv");
            conversion:facts-to-csv($facts, { Caller: "Report"})
        }
        case "excel" return {
            response:content-type("application/vnd.ms-excel");
            response:header("Content-Disposition", "attachment; filename=fact.csv");
            conversion:facts-to-csv($facts, { Caller: "Report"})
        }
        default return {
            response:content-type("application/json");
            response:serialization-parameters({"indent" : true});
            {|
                { NetworkIdentifier : "http://secxbrl.info/facts" },
                { TableName : "xbrl:Facts" },
                { FactTable : [ $facts ] },
                session:comment("json", {
                        NumFacts : count($facts),
                        TotalNumFacts: session:num-facts(),
                        TotalNumArchives: session:num-archives(),
                        TotalNumEntities: session:num-entities()
                    })
            |}
        }
    return api:check-and-return-results($token, $results, $format)