:lipstick: Improve code.

:lipstick: Improve code.

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

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

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

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

declare function local:param-values(
    $name as string,
    $entities as object*) as string*
{
    switch(true)
     case $name eq "xbrl:Concept"
        return (request:param-values("concept"), request:param-values("xbrl:Concept"))

    (: sec profile :)
     case $name eq "sec:FiscalYear" and $profile-name eq "sec"
        return ($fiscalYear, request:param-values("sec:FiscalYear"))[$$ ne "LATEST"]
     case $name eq "sec:FiscalYear::type" and $profile-name eq "sec"
        return "integer"
     case $name eq "sec:FiscalPeriod" and $profile-name eq "sec"
        return ($fiscalPeriod, request:param-values("sec:FiscalPeriod"))
     case $name eq "sec:FiscalPeriod::type" and $profile-name eq "sec"
        return "string"
     case $name eq "sec:FiscalPeriodType" and $profile-name eq "sec"
        return ($fiscalPeriodType, request:param-values("sec:FiscalPeriodType"))
     case $name eq "sec:FiscalPeriodType::type" and $profile-name eq "sec"
        return "string"
     case $name eq "dei:LegalEntityAxis" and $profile-name eq "sec"
        return
         if(empty((request:param-values("sec:LegalEntityAxis"), request:param-values("sec:LegalEntityAxis::default"))))
         then "sec:DefaultLegalEntity"
         else request:param-values("sec:LegalEntityAxis")
     case $name eq "dei:LegalEntityAxis::default" return
         if(empty((request:param-values("sec:LegalEntityAxis"), request:param-values("sec:LegalEntityAxis::default"))))
         then "sec:DefaultLegalEntity"
         else request:param-values("sec:LegalEntityAxis::default")

     case $name eq "xbrl:Entity" and $profile-name = ("sec", "japan")
         return (
                if(empty(($cik,$tag,$ticker,$sic)) or exists($entities))
                then entities:eid($entities)
                else "dummy",
                request:param-values("xbrl:Entity")
            )
     case $name eq "xbrl28:Archive" and $profile-name = ("sec", "japan") return (
            let $prefix as string :=
                switch($profile-name)
                case "sec" return "sec"
                case "japan" return "fsa"
                default return (: not reachable :) ()
            let $fiscalYears :=
                let $years := request:param-values( $prefix || ":FiscalYear")
                return if ($years) then $years else $fiscalYear
            let $fiscalPeriods := local:param-values($prefix || ":FiscalPeriod", $entities)
            return
                if($fiscalYears = "LATEST")
                then archives:aid(multiplexer:latest-filings($profile-name, $entities, $fiscalPeriods))
                else (),
            $aid,
            request:param-values("xbrl28:Archive")
        )

     (: japan profile :)
     case $name eq "fsa:FiscalYear" and $profile-name eq "japan"
     return ($fiscalYear, request:param-values("fsa:FiscalYear"))[$$ ne "LATEST"]
     case $name eq "fsa:FiscalYear::type" and $profile-name eq "japan"
     return "integer"
     case $name eq "fsa:FiscalPeriod" and $profile-name eq "japan"
     return ($fiscalPeriod, request:param-values("fsa:FiscalPeriod"))
     case $name eq "fsa:FiscalPeriod::type" and $profile-name eq "japan"
     return "string"
     case $name eq "fsa:FiscalPeriodType" and $profile-name eq "japan"
     return ($fiscalPeriodType, request:param-values("fsa:FiscalPeriodType"))
     case $name eq "fsa:FiscalPeriodType::type" and $profile-name eq "japan"
     return "string"

     default return request:param-values($name)
};

declare function local:param-names() as string*
{
    let $names := request:param-names()
    return distinct-values((
        (: generic xbrl :)
        $names[contains($$, ":")],
        "xbrl:Entity"[$names = ("eid")],
        "xbrl28:Archive"[$profile-name = ("sec", "japan")],
        "xbrl:Concept"[$names = "concept"],

        (: sec profile :)
        "sec:Accepted"[$profile-name eq "sec"],
        "sec:FiscalPeriod"[$profile-name eq "sec"],
        "sec:FiscalPeriodType"[$profile-name eq "sec"],
        "sec:FiscalYear"[$profile-name eq "sec"],
        "xbrl:Entity"[$profile-name eq "sec" and
                      $names = ("cik", "tag", "ticker", "sic")],
        "dei:LegalEntityAxis"[$profile-name eq "sec"],
        "dei:LegalEntityAxis::default"[$profile-name eq "sec"],

        (: japan profile :)
        "fsa:Submitted"[$profile-name eq "japan"],
        "fsa:FiscalPeriod"[$profile-name eq "japan"],
        "fsa:FiscalPeriodType"[$profile-name eq "japan"],
        "fsa:FiscalYear"[$profile-name eq "japan"],
        "xbrl:Entity"[$profile-name eq "japan" and
                      $names = ("edinetcode", "tag", "ticker")]
    ))
};

declare function local:cast-sequence($values as atomic*, $type as string) as atomic*
{
  for $value in $values
  return
      switch ($type)
      case "integer" return $value cast as integer
      case "string" return $value cast as string
      default return error(xs:QName("local:unsupported-type"), $type || ": unsupported type")
};

declare function local:hypercube($entities as object*) as object
{
    let $hypercube-spec :=
    {|
        for $parameter in local:param-names()
        group by $dimension-name :=
            switch(true)
            case ends-with(lower-case($parameter), "::default")
                return substring-before($parameter, "::default")
            case ends-with(lower-case($parameter), ":default")
                return substring-before($parameter, ":default")
            case ends-with(lower-case($parameter), "::type")
                return substring-before($parameter, "::type")
            default
                return $parameter
        let $all as boolean :=
            (local:param-values($dimension-name, $entities) ! upper-case($$)) = "ALL"
        let $type as string? :=
            (local:param-values($dimension-name || "::type", $entities),
             local:param-values($dimension-name || ":type", $entities))[1]

        let $values := local:param-values($dimension-name, $entities)
        let $typed-values := if (exists($type)) then local:cast-sequence($values[$$ ne "ALL"], $type) else $values

        let $has-default := ($parameter = $dimension-name || "::default") or ($parameter = $dimension-name || ":default")
        let $default-value := (local:param-values($dimension-name || "::default", $entities),
                               local:param-values($dimension-name || ":default", $entities))[1]
        let $typed-default-value := if (exists($type)) then local:cast-sequence($default-value, $type) else $default-value

        return
        {
            $dimension-name : {|
                { "Type" : $type }[exists($type)],
                if(not($all))
                then { "Domain" : [ $typed-values ] }[exists($typed-values)]
                else (),
                { "Default" : $typed-default-value }[$has-default],
                { "Default" : null }[(not $has-default) and $all and exists($type)]
            |}
        }
    |}
    return hypercubes:user-defined-hypercube($hypercube-spec)
};

(: Query parameters :)
declare  %rest:case-insensitive                 variable $token             as string? external;
declare  %rest:case-insensitive                 variable $profile-name      as string  external := $config:profile-name;
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 := "LATEST";
declare  %rest:case-insensitive %rest:distinct  variable $fiscalPeriod      as string* external := "FY";
declare  %rest:case-insensitive %rest:distinct  variable $fiscalPeriodType  as string* external := ("instant", "YTD");
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 $map               as string? external;
declare  %rest:case-insensitive                 variable $rule              as string? external;
declare  %rest:case-insensitive                 variable $report            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 $additional-rules  as string? external;
declare  %rest:case-insensitive                 variable $debug             as boolean external := false;

session:audit-call($token);

(: Post-processing :)
let $format as string? := api:preprocess-format($format, $request-uri)
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,
  api:preprocess-tags($tag),
  $ticker,
  $sic,
  $aid)

let $report as object? := reports:reports($report)
let $map as item* :=
    if(exists($report))
    then reports:concept-map($report)
    else $map
let $rule as item* :=
    (
        if(exists($report))
        then reports:rules($report)
        else rules:rules($rule),
        if(exists($additional-rules))
        then rules:rules($additional-rules)
        else ()
    )

let $hypercube := local:hypercube($entities)

let $facts :=
    let $options := {|
      {
        Hypercube : $hypercube,
        Validate: $validate
      },
      { "ConceptMaps" : $map }[exists($map)],
      { "Rules" : [ $rule ] }[exists($rule)],
      { "Concepts" : $report.Concepts }[exists($report) and exists($report.Concepts)]
    |}
    return if($profile-name eq "sec")
    then sec:facts-for($options)
    else facts:facts-for($options)

let $facts :=
  if(not $labels)
  then $facts
  else
    let $archives as string* := distinct-values($facts.Aspects."xbrl28:Archive")
    let $concept-names as string* := distinct-values($facts.Aspects."xbrl:Concept")
    let $concepts as object* :=
      (
          concepts:concepts($concept-names, $archives, $concepts:ANY_COMPONENT_LINK_ROLE),
          (reports:concepts(($report,$map)))[$$.Name = $concept-names]
      )
    let $language as string := ( $report.$components:DEFAULT-LANGUAGE , $concepts:AMERICAN_ENGLISH )[1]
    let $roles as string* := ( $report.Role, $concepts:ANY_COMPONENT_LINK_ROLE )
    let $nonFetchedEntities as string* := request:param-values("xbrl:Entity")[not $$ = entities:eid($entities)]
    let $entities as object* := ($entities, entities:entities($nonFetchedEntities))
    for $fact as object in $facts
    let $entityName as string :=
        switch(true)
        case $profile-name eq "sec" return
            $entities[entities:eid($$) = $fact.Aspects."xbrl:Entity"].Profiles.SEC.CompanyName
        case $profile-name eq "japan" return
            $entities[entities:eid($$) = $fact.Aspects."xbrl:Entity"].Profiles.FSA.SubmitterName
        default return $fact.Aspects."xbrl:Entity"
    return
    {|
      $fact,
      let $concept-labels as object? := facts:labels($fact, $roles, $concepts:STANDARD_LABEL_ROLE, $language, $concepts, ())
      let $standard-labels as object := conversion:get-standard-labels($fact, $entityName)
      return { Labels : {| $concept-labels, $standard-labels |} }
    |}

let $facts :=
  if($profile-name eq "sec")
  then api:normalize-facts($facts)
  else $facts

let $result := {
    NetworkIdentifier : "http://bizql.io/facts",
    TableName : "xbrl:Facts",
    FactTable : [ $facts ]
}
let $comment :=
{
    NumFacts: count($facts),
    TotalNumFacts: session:num-facts(),
    TotalNumArchives: session:num-archives(),
    TotalNumEntities: session:num-entities()
}
let $comment :=
    if($debug)
    then {|
        $comment,
        { DebugInfo: { Hypercube: $hypercube } }
    |}
    else $comment
let $serializers := {
    to-xml : function($res as object) as node()* {
           <FactTable NetworkIdentifier="http://bizql.io/facts"
            TableName="xbrl:Facts">{
                conversion:facts-to-xml($res.FactTable[], { Caller: "Report"})
        }</FactTable>
    },
    to-csv : function($res as object) as string {
        (conversion:facts-to-csv($res.FactTable[], { Caller: "Report" }), "")[1]
    }
}

let $results := api:serialize($result, $comment, $serializers, $format, "facts")
return api:check-and-return-results($token, $results, $format)


use the filing's module summaries and conversion (xml and csv) functions

import module namespace companies = "http://xbrl.io/modules/bizql/profiles/sec/companies";
import module namespace filings = "http://xbrl.io/modules/bizql/profiles/sec/filings";
import module namespace archives = "http://xbrl.io/modules/bizql/archives";
import module namespace fiscal = "http://xbrl.io/modules/bizql/profiles/sec/fiscal/core";

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

let $format      := lower-case(request:param-values("format")[1])
let $ciks        := distinct-values(companies:eid(request:param-values("cik")))
let $tags        := distinct-values(request:param-values("tag") ! upper-case($$))
let $tickers     := distinct-values(request:param-values("ticker"))
let $sics        := distinct-values(request:param-values("sic"))
let $fiscalPeriods := distinct-values(let $fp := request:param-values("fiscalPeriod", "FY")
                      return
                        if (($fp ! lower-case($$)) = "all")
                        then $fiscal:ALL_FISCAL_PERIODS
                        else if (($fp ! lower-case($$)) = "fy")
                        then distinct-values(("FY", "Q4", $fp))
                        else $fp)
let $aids     := request:param-values("aid")
let $companies := companies:companies($ciks, $tags, $tickers, $sics)
let $fiscalYears := distinct-values(
                    for $y in request:param-values("fiscalYear", "LATEST")
                    return
                        if ($y eq "ALL")
                        then $fiscal:ALL_FISCAL_YEARS
                        else if ($y eq "LATEST")
                          then for $cik in $companies
                               for $fp in $fiscalPeriods
                               return
                                   if ($fiscal:ALL_FISCAL_PERIODS eq $fp)
                                   then
                                       (fiscal:latest-reported-fiscal-period($cik).year) ! ($$ cast as integer)
                                   else
                                       (fiscal:latest-reported-fiscal-period($cik, $fp).year) ! ($$ cast as integer)
                        else if ($y castable as integer)
                        then $y cast as integer
                        else ()
                )
let $archives := (archives:archives($aids),
                    for $fp in $fiscalPeriods, $fy in $fiscalYears
                    return
                      fiscal:filings-for-entities-and-fiscal-periods-and-years($companies, $fp, $fy))
return
    if (session:only-dow30($companies) or session:valid())
    then {
        let $summaries := filings:summaries($archives)
        return
            switch ($format)
            case "xml"  return {
                response:serialization-parameters({"omit-xml-declaration" : false, indent : true });
                ( session:comment("xml", {
                    NumArchives: count($summaries),
                    TotalNumArchives: session:num-archives(),
                    TotalNumEntities: session:num-entities()
                }),
                <Filings>{
                    filings:summaries-to-xml($summaries)
                }</Filings>)
            }
            case "csv" case "text" return {
                response:content-type("text/csv");
                response:header("Content-Disposition", "attachment; filename=filings.csv");
                string-join(filings:summaries-to-csv($summaries), "")
            }
            case "excel" return {
                response:content-type("application/vnd.ms-excel");
                response:header("Content-Disposition", "attachment; filename=filings.csv");
                string-join(filings:summaries-to-csv($summaries))
            }
            default return {
                response:content-type("application/json");
                response:serialization-parameters({"indent" : true});
                {|
                    { "Archives" : [ $summaries ] },
                    session:comment("json", {
                        NumArchives: count($summaries),
                        TotalNumArchives: session:num-archives(),
                        TotalNumEntities: session:num-entities()
                    })
                |}
            }
    } else {
        response:status-code(401);
        session:error("accessing filings of an entity that is not in the DOW30", $format)
    }

import module namespace facts = "http://xbrl.io/modules/bizql/facts";

import module namespace companies = "http://xbrl.io/modules/bizql/profiles/sec/companies";
import module namespace filings = "http://xbrl.io/modules/bizql/profiles/sec/filings";
import module namespace archives = "http://xbrl.io/modules/bizql/archives";
import module namespace fiscal = "http://xbrl.io/modules/bizql/profiles/sec/fiscal/core";

import module namespace request = "http://www.28msec.com/modules/http-request";
import module namespace response = "http://www.28msec.com/modules/http-response";
import module namespace csv = "http://zorba.io/modules/json-csv";
import module namespace session = "http://apps.28.io/session";

declare function local:to-xml($filings as object*) as node()*
{
    ( session:comment("xml", {
        NumArchives: count($filings),
        TotalNumArchives: session:num-archives(),
        TotalNumEntities: session:num-entities()
    }),
    <Filings>{
        for $f in $filings
        return
        <Filing>
            <CIK>{$f.CIK}</CIK>
            <EntityRegistrantName>{$f.EntityRegistrantName}</EntityRegistrantName>
            <FormType>{$f.FormType}</FormType>
            <FiscalYear>{$f.FiscalYear}</FiscalYear>
            <FiscalPeriod>{$f.FiscalPeriod}</FiscalPeriod>
            <Accepted>{$f.Accepted}</Accepted>
            <Generator>{$f.Generator}</Generator>
            <AccessionNumber>{$f.AccessionNumber}</AccessionNumber>
            <SECFilingPage>{$f.SECFilingPage}</SECFilingPage>
            <XBRLInstanceURL>{$f.XBRLInstanceURL}</XBRLInstanceURL>
            <Networks>{$f.Networks}</Networks>
            <ReportElements>{$f.ReportElements}</ReportElements>
            <Tables>{$f.Tables}</Tables>
            <Axis>{$f.Axis}</Axis>
            <Members>{$f.Members}</Members>
            <LineItems>{$f.LineItems}</LineItems>
            <Concepts>{$f.Concepts}</Concepts>
            <Abstracts>{$f.Abstracts}</Abstracts>
            <Footnotes>{$f.Footnotes}</Footnotes>
            <Facts>{$f.Facts}</Facts>
            <ExtensionFacts>{$f.ExtensionFacts}</ExtensionFacts>
            <ExtensionConcepts>{$f.ExtensionConcepts}</ExtensionConcepts>
            <ExtensionAbstracts>{$f.ExtensionAbstracts}</ExtensionAbstracts>
        </Filing>
    }</Filings>)
};

declare function local:to-csv($filings as object*) as string*
{
    csv:serialize($filings, { serialize-null-as : "" })
};

declare function local:summary($a as object) as object
{
    {
        CIK : $a.Entity,
        EntityRegistrantName :
            facts:facts-for-archives-and-concepts($a, "dei:EntityRegistrantName").Value,
        FormType : filings:document-types($a),
        FiscalYear : fiscal:fiscal-year($a),
        FiscalPeriod : fiscal:fiscal-period($a),
        Accepted : filings:acceptance-dateTimes($a),
        Generator : filings:generators($a),
        AccessionNumber: $a._id,
        SECFilingPage : $a.Profiles.SEC.SECFilingPage,
        XBRLInstanceURL : $a.InstanceURL,
        Networks : filings:num-networks($a),
        ReportElements : filings:num-report-elements($a),
        Tables : filings:num-tables($a),
        Axis : filings:num-axes($a),
        Members : filings:num-members($a),
        LineItems : $a.Statistics.Profiles.SEC.NumDistinctReportElementNamesEndingWithLineItems,
        Concepts : filings:num-concepts($a),
        Abstracts : filings:num-abstracts($a),
        Footnotes : filings:num-footnotes($a),
        Facts: filings:num-facts($a),
        ExtensionFacts:  filings:num-extension-facts($a),
        ExtensionConcepts : filings:num-extension-concepts($a),
        ExtensionAbstracts : filings:num-extension-abstracts($a)
    }
};

let $format      := lower-case(request:param-values("format")[1])
let $ciks        := distinct-values(companies:eid(request:param-values("cik")))
let $tags        := distinct-values(request:param-values("tag") ! upper-case($$))
let $tickers     := distinct-values(request:param-values("ticker"))
let $sics        := distinct-values(request:param-values("sic"))
let $fiscalPeriods := distinct-values(let $fp := request:param-values("fiscalPeriod", "FY")
                      return
                        if (($fp ! lower-case($$)) = "all")
                        then $fiscal:ALL_FISCAL_PERIODS
                        else if (($fp ! lower-case($$)) = "fy")
                        then distinct-values(("FY", "Q4", $fp))
                        else $fp)
let $aids     := request:param-values("aid")
let $ciks := ($ciks,
    companies:companies-for-tags($tags),
    companies:companies-for-tickers($tickers),
    companies:companies-for-SIC($sics))
let $fiscalYears := distinct-values(
                    for $y in request:param-values("fiscalYear", "LATEST")
                    return
                        if ($y eq "ALL")
                        then $fiscal:ALL_FISCAL_YEARS
                        else if ($y eq "LATEST")
                          then for $cik in $ciks
                               for $fp in $fiscalPeriods
                               return
                                   if ($fiscal:ALL_FISCAL_PERIODS eq $fp)
                                   then
                                       (fiscal:latest-reported-fiscal-period($cik).year) ! ($$ cast as integer)
                                   else
                                       (fiscal:latest-reported-fiscal-period($cik, $fp).year) ! ($$ cast as integer)
                        else if ($y castable as integer)
                        then $y cast as integer
                        else ()
                )
let $archives := (archives:archives($aids),
                    for $fp in $fiscalPeriods, $fy in $fiscalYears
                    return
                      fiscal:filings-for-entities-and-fiscal-periods-and-years($ciks, $fp, $fy))
let $entities := companies:companies($archives.Entities)
return
    if (session:only-dow30($entities) or session:valid())
    then {
        let $archives :=
                for $a in $archives
                group by $a._id (: duplicate elimination :)
                order by filings:acceptance-dateTimes($a[1]) descending
                return local:summary($a[1])
        return
            switch ($format)
            case "xml"  return {
                response:serialization-parameters({"omit-xml-declaration" : false, indent : true });
                local:to-xml($archives)
            }
            case "csv" case "text" return {
                response:content-type("text/csv");
                response:header("Content-Disposition", "attachment; filename=filings.csv");
                string-join(local:to-csv($archives), "")
            }
            case "excel" return {
                response:content-type("application/vnd.ms-excel");
                response:header("Content-Disposition", "attachment; filename=filings.csv");
                string-join(local:to-csv($archives))
            }
            default return {
                response:content-type("application/json");
                response:serialization-parameters({"indent" : true});
                {|
                    { "Archives" : [ $archives ] },
                    session:comment("json", {
                        NumArchives: count($archives),
                        TotalNumArchives: session:num-archives(),
                        TotalNumEntities: session:num-entities()
                    })
                |}
            }
    } else {
        response:status-code(401);
        session:error("accessing filings of an entity that is not in the DOW30", $format)
    }


Update FixRights.jq

Update FixRights.jq

append json "anybody" into collection("Rights")[$$._id eq "data_sec"].roles;

append json "anyone" into collection("Rights")[$$._id eq "data_sec"].roles;


reverted newlines change

reverted newlines change

jsoniq version "1.0";
import module namespace http = "http://zorba.io/modules/http-client";
import module namespace request = "http://www.28msec.com/modules/http-request";

declare variable $id := "BasicFinancialInformation";
declare variable $report := parse-json(http:get("http://" || request:server-name() || ":" || request:server-port() || "/v1/_queries/public/export/fac.jq?_method=POST").body.content);
declare variable $desc :=
  "Documentation about the fundamental accounting concepts defined in this report can be found at http://fundamentalaccountingconcepts.wikispaces.com/home";
declare variable $role := "http://xbrl.io/basic-financial-information";
declare variable $additionalRules :=
  (
    {
        "Id" : "gi_CommonStockSharesOutstanding",
        "Type" : "xbrl28:formula",
        "Label" : "CommonStockSharesOutstanding imputation",
        "Formula" : "(: workaround for bug: https://github.com/28msec/xbrl-infosetgenerator/issues/7 :)
                     let $aligned-filter := trim($aligned-filter, (\"Profiles.SEC.Fiscal\"))
                     for $facts in  facts:facts-for-internal((
                             \"fac:CommonStockSharesOutstanding\"), $hypercube, $aligned-filter, $concept-maps, $rules, $cache, $options)
                     group by $canonical-filter-string :=
                                 facts:canonically-serialize-object($facts, ($facts:CONCEPT, \"_id\", \"IsInDefaultHypercube\", \"Type\", \"Value\", \"Decimals\", \"AuditTrails\", \"xbrl28:Type\", \"Balance\"))
                     for $CommonStockSharesOutstandingByArchive in $facts[$$.$facts:ASPECTS.$facts:CONCEPT eq \"fac:CommonStockSharesOutstanding\"]
                     group by $CommonStockSharesOutstandingByArchive.Archive
                     return
                         let $source-fact :=
                             (
                                 for $CommonStockSharesOutstanding in $CommonStockSharesOutstandingByArchive
                                 order by $CommonStockSharesOutstanding.$facts:ASPECTS.$facts:PERIOD descending
                                 return $CommonStockSharesOutstanding
                             )[1]
                         let $value := rules:decimal-value($source-fact)
                         let $original-concept := $source-fact.AuditTrails[][$$.Type eq \"xbrl28:concept-maps\"].Data.OriginalConcept
                         let $audit-trail-message :=
                            rules:fact-trail({ \"Aspects\" : { \"xbrl:Unit\" : \"shares\", \"xbrl:Concept\" : $original-concept }, Value: $value }) || \" (as of latest practicable date: \" || $source-fact.$facts:ASPECTS.$facts:PERIOD
                            || \")\"
                         return
                             rules:create-computed-fact(
                                 $source-fact,
                                 \"fac:CommonStockSharesOutstanding\",
                                 $value,
                                 $rule,
                                 $audit-trail-message,
                                 $source-fact,
                                 $options)",
        "ComputableConcepts" : [ "fac:CommonStockSharesOutstanding" ]
      },
      {
          "Id" : "decimals_inf",
          "Type" : "xbrl28:formula",
          "Label" : "Align INF decimals",
          "Formula" : "for $fact in facts:facts-for-internal($concepts, $hypercube, $aligned-filter, $concept-maps, $rules, $cache, $options)
                             return
                               if(string($fact.Decimals) eq \"INF\")
                               then
                                 let $concept := $fact.Aspects.\"xbrl:Concept\"
                                 let $audit-trail :=
                                   {
                                     \"Type\" : \"xbrl28:decimals-inf-alignment\",
                                     \"Label\" : \"Aligning Decimals to 3 instead of INF\",
                                     \"Message\" : $concept || \" = 0\",
                                     \"Data\" : {
                                       \"OutputConcept\" : $concept
                                     }
                                   }
                                 return
                                 copy $f := $fact
                                 modify (
                                     replace value of json $f.Decimals with 3,
                                     if(exists($f.AuditTrails))
                                     then replace value of json $f.AuditTrails with [ $audit-trail ]
                                     else insert json { AuditTrails: [ $audit-trail ] } into $f
                                 )
                                 return $f
                               else $fact"
        }
  );

(: Presentation :)
let $presentation := $report.Networks[][$$.ShortName eq "Presentation"]
let $concepts :=
    {
      "fac:CommonStockSharesAuthorized": {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "Id" : "e7c449eb-4e1b-4d20-af35-b783cfdab03e"
      },
      "fac:CommonStockSharesIssued": {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "Id" : "a8a4ae32-0424-437e-a645-428398f95f9c"
      },
      "fac:CommonStockSharesOutstanding": {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "Id" : "f51e72c7-a3ce-4639-99b0-47ca36d54a7b"
      }
    }
let $genInfo := $presentation.Trees."fac:FundamentalAccountingConceptsLineItems".To."fac:FundamentalAccountingConceptsHierarchy".To."fac:GeneralInformationHierarchy"
return
  {
    replace value of json $presentation.LinkRole with $role;
    replace value of json $genInfo.To with {| ( $genInfo.To, $concepts ) |};
  }

(: Hypercube :)
let $conceptsDomain := $report.Hypercubes."xbrl:DefaultHypercube".Aspects."xbrl:Concept".Domains."xbrl:ConceptDomain"
let $concepts :=
    {
      "fac:CommonStockSharesAuthorized": {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "Id" : "e7c449eb-4e1b-4d20-af35-b783cfdab03e"
      },
      "fac:CommonStockSharesIssued": {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "Id" : "a8a4ae32-0424-437e-a645-428398f95f9c"
      },
      "fac:CommonStockSharesOutstanding": {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "Id" : "f51e72c7-a3ce-4639-99b0-47ca36d54a7b"
      }
    }
return
  replace value of json $conceptsDomain.Members with {| $conceptsDomain.Members, $concepts |};

(: ConceptMap :)
let $conceptMap := $report.Networks[][$$.ShortName eq "ConceptMap"]
let $mappings :=
    {
      "fac:CommonStockSharesAuthorized" : {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "To" : {
          "us-gaap:CommonStockSharesAuthorized": {
            "Name" : "us-gaap:CommonStockSharesAuthorized",
            "Id" : "8ed0a312-9891-4d3d-b459-67604dce2124"
          }
        },
        "Id" : "372f39c9-c8ed-4654-a424-6f033bb0ddd2"

      },
      "fac:CommonStockSharesIssued" : {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "To" : {
          "us-gaap:CommonStockSharesIssued": {
            "Name" : "us-gaap:CommonStockSharesIssued",
            "Id" : "1359b87e-5f75-49f3-849b-d410cc399b50"
          }
        },
        "Id" : "66226139-512f-4edd-8c18-6d7e307a1f66"
      },
      "fac:CommonStockSharesOutstanding" : {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "To" : {
          "dei:EntityCommonStockSharesOutstanding": {
            "Name" : "dei:EntityCommonStockSharesOutstanding",
            "Id" : "b8d27670-5caa-411f-8305-860c0613c31f"
          }
        },
        "Id" : "91b87448-a8dd-4739-9cdf-2cdaef6a4ff6"
      }
    }
return
  {
    replace value of json $conceptMap.LinkRole with $role;
    replace value of json $conceptMap.Trees with {| $conceptMap.Trees, $mappings |};
  }

(: DefinitionModel :)
replace value of json $report.DefinitionModels[1].Breakdowns.y[1].BreakdownTrees[1].LinkRole with $role;

(: adapt default_zero rule :)
let $defaultZeroRule := $report.Rules[][$$.Id eq "default_zero"]
let $formula := replace($defaultZeroRule.Formula,
                        "\"fac:LiabilitiesAndEquity\"\\)",
                        "\"fac:LiabilitiesAndEquity\", \"us-gaap:CommonStockSharesAuthorized\", \"us-gaap:CommonStockSharesIssued\", \"dei:EntityCommonStockSharesOutstanding\")"
                       )
return
  {
    replace value of json $defaultZeroRule.Formula with $formula;
  }

{ "_id": $id,
  Archive: null,
  Label: "Basic Financial Information",
  Description: $desc,
  Prefix: "fac",
  Role: $role,
  Owner: "charlie@prudena.com",
  LastModified: string(current-dateTime()),
  ACL: [],
  Networks: $report.Networks,
  Hypercubes: $report.Hypercubes,
  DefinitionModels: $report.DefinitionModels,
  Rules: [ for $rule in ($report.Rules[], $additionalRules)
           order by $rule.ComputableConcepts[][1], $rule.Id descending empty least
           return $rule ],
  Filters: {
    cik: [  ],
    tag: [ "DOW30" ],
    fiscalYear : [ 2013 ],
    fiscalPeriod : [ "FY" ],
    sic : [  ]
  }
}

jsoniq version "1.0";
import module namespace http = "http://zorba.io/modules/http-client";
import module namespace request = "http://www.28msec.com/modules/http-request";

declare variable $id := "BasicFinancialInformation";
declare variable $report := parse-json(http:get("http://" || request:server-name() || ":" || request:server-port() || "/v1/_queries/public/export/fac.jq?_method=POST").body.content);
declare variable $desc :=
  "Documentation about the fundamental accounting concepts defined in this report can be found at http://fundamentalaccountingconcepts.wikispaces.com/home";
declare variable $role := "http://xbrl.io/basic-financial-information";
declare variable $additionalRules :=
  (
    {
        "Id" : "gi_CommonStockSharesOutstanding",
        "Type" : "xbrl28:formula",
        "Label" : "CommonStockSharesOutstanding imputation",
        "Formula" : "\n(: workaround for bug: https://github.com/28msec/xbrl-infosetgenerator/issues/7 :)\nlet $aligned-filter := trim($aligned-filter, (\"Profiles.SEC.Fiscal\"))\nfor $facts in  facts:facts-for-internal((\n        \"fac:CommonStockSharesOutstanding\"), $hypercube, $aligned-filter, $concept-maps, $rules, $cache, $options)\ngroup by $canonical-filter-string := \n            facts:canonically-serialize-object($facts, ($facts:CONCEPT, \"_id\", \"IsInDefaultHypercube\", \"Type\", \"Value\", \"Decimals\", \"AuditTrails\", \"xbrl28:Type\", \"Balance\"))\nfor $CommonStockSharesOutstandingByArchive in $facts[$$.$facts:ASPECTS.$facts:CONCEPT eq \"fac:CommonStockSharesOutstanding\"]\ngroup by $CommonStockSharesOutstandingByArchive.Archive\nreturn\n    let $source-fact :=\n        (\n            for $CommonStockSharesOutstanding in $CommonStockSharesOutstandingByArchive\n            order by $CommonStockSharesOutstanding.$facts:ASPECTS.$facts:PERIOD descending\n            return $CommonStockSharesOutstanding\n        )[1]\n    let $value := rules:decimal-value($source-fact)\n    let $original-concept := $source-fact.AuditTrails[][$$.Type eq \"xbrl28:concept-maps\"].Data.OriginalConcept\n    let $audit-trail-message :=\n       rules:fact-trail({ \"Aspects\" : { \"xbrl:Unit\" : \"shares\", \"xbrl:Concept\" : $original-concept }, Value: $value }) || \" (as of latest practicable date: \" || $source-fact.$facts:ASPECTS.$facts:PERIOD\n       || \")\"\n    return\n        rules:create-computed-fact(\n            $source-fact,\n            \"fac:CommonStockSharesOutstanding\",\n            $value,\n            $rule,\n            $audit-trail-message,\n            $source-fact,\n            $options)",
        "ComputableConcepts" : [ "fac:CommonStockSharesOutstanding" ]
      },
      {
          "Id" : "decimals_inf",
          "Type" : "xbrl28:formula",
          "Label" : "Align INF decimals",
          "Formula" : "for $fact in facts:facts-for-internal($concepts, $hypercube, $aligned-filter, $concept-maps, $rules, $cache, $options)
                             return
                               if(string($fact.Decimals) eq \"INF\")
                               then
                                 let $concept := $fact.Aspects.\"xbrl:Concept\"
                                 let $audit-trail :=
                                   {
                                     \"Type\" : \"xbrl28:decimals-inf-alignment\",
                                     \"Label\" : \"Aligning Decimals to 3 instead of INF\",
                                     \"Message\" : $concept || \" = 0\",
                                     \"Data\" : {
                                       \"OutputConcept\" : $concept
                                     }
                                   }
                                 return
                                 copy $f := $fact
                                 modify (
                                     replace value of json $f.Decimals with 3,
                                     if(exists($f.AuditTrails))
                                     then replace value of json $f.AuditTrails with [ $audit-trail ]
                                     else insert json { AuditTrails: [ $audit-trail ] } into $f
                                 )
                                 return $f
                               else $fact"
        }
  );

(: Presentation :)
let $presentation := $report.Networks[][$$.ShortName eq "Presentation"]
let $concepts :=
    {
      "fac:CommonStockSharesAuthorized": {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "Id" : "e7c449eb-4e1b-4d20-af35-b783cfdab03e"
      },
      "fac:CommonStockSharesIssued": {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "Id" : "a8a4ae32-0424-437e-a645-428398f95f9c"
      },
      "fac:CommonStockSharesOutstanding": {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "Id" : "f51e72c7-a3ce-4639-99b0-47ca36d54a7b"
      }
    }
let $genInfo := $presentation.Trees."fac:FundamentalAccountingConceptsLineItems".To."fac:FundamentalAccountingConceptsHierarchy".To."fac:GeneralInformationHierarchy"
return
  {
    replace value of json $presentation.LinkRole with $role;
    replace value of json $genInfo.To with {| ( $genInfo.To, $concepts ) |};
  }

(: Hypercube :)
let $conceptsDomain := $report.Hypercubes."xbrl:DefaultHypercube".Aspects."xbrl:Concept".Domains."xbrl:ConceptDomain"
let $concepts :=
    {
      "fac:CommonStockSharesAuthorized": {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "Id" : "e7c449eb-4e1b-4d20-af35-b783cfdab03e"
      },
      "fac:CommonStockSharesIssued": {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "Id" : "a8a4ae32-0424-437e-a645-428398f95f9c"
      },
      "fac:CommonStockSharesOutstanding": {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "Id" : "f51e72c7-a3ce-4639-99b0-47ca36d54a7b"
      }
    }
return
  replace value of json $conceptsDomain.Members with {| $conceptsDomain.Members, $concepts |};

(: ConceptMap :)
let $conceptMap := $report.Networks[][$$.ShortName eq "ConceptMap"]
let $mappings :=
    {
      "fac:CommonStockSharesAuthorized" : {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "To" : {
          "us-gaap:CommonStockSharesAuthorized": {
            "Name" : "us-gaap:CommonStockSharesAuthorized",
            "Id" : "8ed0a312-9891-4d3d-b459-67604dce2124"
          }
        },
        "Id" : "372f39c9-c8ed-4654-a424-6f033bb0ddd2"

      },
      "fac:CommonStockSharesIssued" : {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "To" : {
          "us-gaap:CommonStockSharesIssued": {
            "Name" : "us-gaap:CommonStockSharesIssued",
            "Id" : "1359b87e-5f75-49f3-849b-d410cc399b50"
          }
        },
        "Id" : "66226139-512f-4edd-8c18-6d7e307a1f66"
      },
      "fac:CommonStockSharesOutstanding" : {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "To" : {
          "dei:EntityCommonStockSharesOutstanding": {
            "Name" : "dei:EntityCommonStockSharesOutstanding",
            "Id" : "b8d27670-5caa-411f-8305-860c0613c31f"
          }
        },
        "Id" : "91b87448-a8dd-4739-9cdf-2cdaef6a4ff6"
      }
    }
return
  {
    replace value of json $conceptMap.LinkRole with $role;
    replace value of json $conceptMap.Trees with {| $conceptMap.Trees, $mappings |};
  }

(: DefinitionModel :)
replace value of json $report.DefinitionModels[1].Breakdowns.y[1].BreakdownTrees[1].LinkRole with $role;

(: adapt default_zero rule :)
let $defaultZeroRule := $report.Rules[][$$.Id eq "default_zero"]
let $formula := replace($defaultZeroRule.Formula,
                        "\"fac:LiabilitiesAndEquity\"\\)",
                        "\"fac:LiabilitiesAndEquity\", \"us-gaap:CommonStockSharesAuthorized\", \"us-gaap:CommonStockSharesIssued\", \"dei:EntityCommonStockSharesOutstanding\")"
                       )
return
  {
    replace value of json $defaultZeroRule.Formula with $formula;
  }

{ "_id": $id,
  Archive: null,
  Label: "Basic Financial Information",
  Description: $desc,
  Prefix: "fac",
  Role: $role,
  Owner: "charlie@prudena.com",
  LastModified: string(current-dateTime()),
  ACL: [],
  Networks: $report.Networks,
  Hypercubes: $report.Hypercubes,
  DefinitionModels: $report.DefinitionModels,
  Rules: [ for $rule in ($report.Rules[], $additionalRules)
           order by $rule.ComputableConcepts[][1], $rule.Id descending empty least
           return $rule ],
  Filters: {
    cik: [  ],
    tag: [ "DOW30" ],
    fiscalYear : [ 2013 ],
    fiscalPeriod : [ "FY" ],
    sic : [  ]
  }
}


better documentation

better documentation

jsoniq version "1.0";
import module namespace http = "http://zorba.io/modules/http-client";
import module namespace request = "http://www.28msec.com/modules/http-request";

declare variable $id := "BasicFinancialInformation";
declare variable $report := parse-json(http:get("http://" || request:server-name() || ":" || request:server-port() || "/v1/_queries/public/export/fac.jq?_method=POST").body.content);
declare variable $desc :=
  "This report extends the fundamental accounting concepts report. Documentation about the fundamental accounting concepts defined in this report can be found at http://fundamentalaccountingconcepts.wikispaces.com/home";
declare variable $role := "http://xbrl.io/basic-financial-information";
declare variable $additionalRules :=
  (
    {
        "Id" : "gi_CommonStockSharesOutstanding",
        "Type" : "xbrl28:formula",
        "Label" : "CommonStockSharesOutstanding imputation",
        "Formula" : "(: workaround for bug: https://github.com/28msec/xbrl-infosetgenerator/issues/7 :)
                     let $aligned-filter := trim($aligned-filter, (\"Profiles.SEC.Fiscal\"))
                     for $facts in  facts:facts-for-internal((
                             \"fac:CommonStockSharesOutstanding\"), $hypercube, $aligned-filter, $concept-maps, $rules, $cache, $options)
                     group by $canonical-filter-string :=
                                 facts:canonically-serialize-object($facts, ($facts:CONCEPT, \"_id\", \"IsInDefaultHypercube\", \"Type\", \"Value\", \"Decimals\", \"AuditTrails\", \"xbrl28:Type\", \"Balance\"))
                     for $CommonStockSharesOutstandingByArchive in $facts[$$.$facts:ASPECTS.$facts:CONCEPT eq \"fac:CommonStockSharesOutstanding\"]
                     group by $CommonStockSharesOutstandingByArchive.Archive
                     return
                         let $source-fact :=
                             (
                                 for $CommonStockSharesOutstanding in $CommonStockSharesOutstandingByArchive
                                 order by $CommonStockSharesOutstanding.$facts:ASPECTS.$facts:PERIOD descending
                                 return $CommonStockSharesOutstanding
                             )[1]
                         let $value := rules:decimal-value($source-fact)
                         let $original-concept := $source-fact.AuditTrails[][$$.Type eq \"xbrl28:concept-maps\"].Data.OriginalConcept
                         let $audit-trail-message :=
                            rules:fact-trail({ \"Aspects\" : { \"xbrl:Unit\" : \"shares\", \"xbrl:Concept\" : $original-concept }, Value: $value }) || \" (as of latest practicable date: \" || $source-fact.$facts:ASPECTS.$facts:PERIOD
                            || \")\"
                         return
                             rules:create-computed-fact(
                                 $source-fact,
                                 \"fac:CommonStockSharesOutstanding\",
                                 $value,
                                 $rule,
                                 $audit-trail-message,
                                 $source-fact,
                                 $options)",
        "ComputableConcepts" : [ "fac:CommonStockSharesOutstanding" ]
      },
      {
          "Id" : "decimals_inf",
          "Type" : "xbrl28:formula",
          "Label" : "Align INF decimals",
          "Formula" : "for $fact in facts:facts-for-internal($concepts, $hypercube, $aligned-filter, $concept-maps, $rules, $cache, $options)
                             return
                               if(string($fact.Decimals) eq \"INF\")
                               then
                                 let $concept := $fact.Aspects.\"xbrl:Concept\"
                                 let $audit-trail :=
                                   {
                                     \"Type\" : \"xbrl28:decimals-inf-alignment\",
                                     \"Label\" : \"Aligning Decimals to 3 instead of INF\",
                                     \"Message\" : $concept || \" = 0\",
                                     \"Data\" : {
                                       \"OutputConcept\" : $concept
                                     }
                                   }
                                 return
                                 copy $f := $fact
                                 modify (
                                     replace value of json $f.Decimals with 3,
                                     if(exists($f.AuditTrails))
                                     then replace value of json $f.AuditTrails with [ $audit-trail ]
                                     else insert json { AuditTrails: [ $audit-trail ] } into $f
                                 )
                                 return $f
                               else $fact"
        }
  );

(: Presentation :)
let $presentation := $report.Networks[][$$.ShortName eq "Presentation"]
let $concepts :=
    {
      "fac:CommonStockSharesAuthorized": {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "Id" : "e7c449eb-4e1b-4d20-af35-b783cfdab03e"
      },
      "fac:CommonStockSharesIssued": {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "Id" : "a8a4ae32-0424-437e-a645-428398f95f9c"
      },
      "fac:CommonStockSharesOutstanding": {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "Id" : "f51e72c7-a3ce-4639-99b0-47ca36d54a7b"
      }
    }
let $genInfo := $presentation.Trees."fac:FundamentalAccountingConceptsLineItems".To."fac:FundamentalAccountingConceptsHierarchy".To."fac:GeneralInformationHierarchy"
return
  {
    replace value of json $presentation.LinkRole with $role;
    replace value of json $genInfo.To with {| ( $genInfo.To, $concepts ) |};
  }

(: Hypercube :)
let $conceptsDomain := $report.Hypercubes."xbrl:DefaultHypercube".Aspects."xbrl:Concept".Domains."xbrl:ConceptDomain"
let $concepts :=
    {
      "fac:CommonStockSharesAuthorized": {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "Id" : "e7c449eb-4e1b-4d20-af35-b783cfdab03e"
      },
      "fac:CommonStockSharesIssued": {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "Id" : "a8a4ae32-0424-437e-a645-428398f95f9c"
      },
      "fac:CommonStockSharesOutstanding": {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "Id" : "f51e72c7-a3ce-4639-99b0-47ca36d54a7b"
      }
    }
return
  replace value of json $conceptsDomain.Members with {| $conceptsDomain.Members, $concepts |};

(: ConceptMap :)
let $conceptMap := $report.Networks[][$$.ShortName eq "ConceptMap"]
let $mappings :=
    {
      "fac:CommonStockSharesAuthorized" : {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "To" : {
          "us-gaap:CommonStockSharesAuthorized": {
            "Name" : "us-gaap:CommonStockSharesAuthorized",
            "Id" : "8ed0a312-9891-4d3d-b459-67604dce2124"
          }
        },
        "Id" : "372f39c9-c8ed-4654-a424-6f033bb0ddd2"

      },
      "fac:CommonStockSharesIssued" : {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "To" : {
          "us-gaap:CommonStockSharesIssued": {
            "Name" : "us-gaap:CommonStockSharesIssued",
            "Id" : "1359b87e-5f75-49f3-849b-d410cc399b50"
          }
        },
        "Id" : "66226139-512f-4edd-8c18-6d7e307a1f66"
      },
      "fac:CommonStockSharesOutstanding" : {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "To" : {
          "dei:EntityCommonStockSharesOutstanding": {
            "Name" : "dei:EntityCommonStockSharesOutstanding",
            "Id" : "b8d27670-5caa-411f-8305-860c0613c31f"
          }
        },
        "Id" : "91b87448-a8dd-4739-9cdf-2cdaef6a4ff6"
      }
    }
return
  {
    replace value of json $conceptMap.LinkRole with $role;
    replace value of json $conceptMap.Trees with {| $conceptMap.Trees, $mappings |};
  }

(: DefinitionModel :)
replace value of json $report.DefinitionModels[1].Breakdowns.y[1].BreakdownTrees[1].LinkRole with $role;

(: adapt default_zero rule :)
let $defaultZeroRule := $report.Rules[][$$.Id eq "default_zero"]
let $formula := replace($defaultZeroRule.Formula,
                        "\"fac:LiabilitiesAndEquity\"\\)",
                        "\"fac:LiabilitiesAndEquity\", \"us-gaap:CommonStockSharesAuthorized\", \"us-gaap:CommonStockSharesIssued\", \"dei:EntityCommonStockSharesOutstanding\")"
                       )
return
  {
    replace value of json $defaultZeroRule.Formula with $formula;
  }

{ "_id": $id,
  Archive: null,
  Label: "Basic Financial Information",
  Description: $desc,
  Prefix: "fac",
  Role: $role,
  Owner: "charlie@prudena.com",
  LastModified: string(current-dateTime()),
  ACL: [],
  Networks: $report.Networks,
  Hypercubes: $report.Hypercubes,
  DefinitionModels: $report.DefinitionModels,
  Rules: [ for $rule in ($report.Rules[], $additionalRules)
           order by $rule.ComputableConcepts[][1], $rule.Id descending empty least
           return $rule ],
  Filters: {
    cik: [  ],
    tag: [ "DOW30" ],
    fiscalYear : [ 2013 ],
    fiscalPeriod : [ "FY" ],
    sic : [  ]
  }
}

jsoniq version "1.0";
import module namespace http = "http://zorba.io/modules/http-client";
import module namespace request = "http://www.28msec.com/modules/http-request";

declare variable $id := "BasicFinancialInformation";
declare variable $report := parse-json(http:get("http://" || request:server-name() || ":" || request:server-port() || "/v1/_queries/public/export/fac.jq?_method=POST").body.content);
declare variable $desc :=
  "Documentation about the fundamental accounting concepts defined in this report can be found at http://fundamentalaccountingconcepts.wikispaces.com/home";
declare variable $role := "http://xbrl.io/basic-financial-information";
declare variable $additionalRules :=
  (
    {
        "Id" : "gi_CommonStockSharesOutstanding",
        "Type" : "xbrl28:formula",
        "Label" : "CommonStockSharesOutstanding imputation",
        "Formula" : "(: workaround for bug: https://github.com/28msec/xbrl-infosetgenerator/issues/7 :)
                     let $aligned-filter := trim($aligned-filter, (\"Profiles.SEC.Fiscal\"))
                     for $facts in  facts:facts-for-internal((
                             \"fac:CommonStockSharesOutstanding\"), $hypercube, $aligned-filter, $concept-maps, $rules, $cache, $options)
                     group by $canonical-filter-string :=
                                 facts:canonically-serialize-object($facts, ($facts:CONCEPT, \"_id\", \"IsInDefaultHypercube\", \"Type\", \"Value\", \"Decimals\", \"AuditTrails\", \"xbrl28:Type\", \"Balance\"))
                     for $CommonStockSharesOutstandingByArchive in $facts[$$.$facts:ASPECTS.$facts:CONCEPT eq \"fac:CommonStockSharesOutstanding\"]
                     group by $CommonStockSharesOutstandingByArchive.Archive
                     return
                         let $source-fact :=
                             (
                                 for $CommonStockSharesOutstanding in $CommonStockSharesOutstandingByArchive
                                 order by $CommonStockSharesOutstanding.$facts:ASPECTS.$facts:PERIOD descending
                                 return $CommonStockSharesOutstanding
                             )[1]
                         let $value := rules:decimal-value($source-fact)
                         let $original-concept := $source-fact.AuditTrails[][$$.Type eq \"xbrl28:concept-maps\"].Data.OriginalConcept
                         let $audit-trail-message :=
                            rules:fact-trail({ \"Aspects\" : { \"xbrl:Unit\" : \"shares\", \"xbrl:Concept\" : $original-concept }, Value: $value }) || \" (as of latest practicable date: \" || $source-fact.$facts:ASPECTS.$facts:PERIOD
                            || \")\"
                         return
                             rules:create-computed-fact(
                                 $source-fact,
                                 \"fac:CommonStockSharesOutstanding\",
                                 $value,
                                 $rule,
                                 $audit-trail-message,
                                 $source-fact,
                                 $options)",
        "ComputableConcepts" : [ "fac:CommonStockSharesOutstanding" ]
      },
      {
          "Id" : "decimals_inf",
          "Type" : "xbrl28:formula",
          "Label" : "Align INF decimals",
          "Formula" : "for $fact in facts:facts-for-internal($concepts, $hypercube, $aligned-filter, $concept-maps, $rules, $cache, $options)
                             return
                               if(string($fact.Decimals) eq \"INF\")
                               then
                                 let $concept := $fact.Aspects.\"xbrl:Concept\"
                                 let $audit-trail :=
                                   {
                                     \"Type\" : \"xbrl28:decimals-inf-alignment\",
                                     \"Label\" : \"Aligning Decimals to 3 instead of INF\",
                                     \"Message\" : $concept || \" = 0\",
                                     \"Data\" : {
                                       \"OutputConcept\" : $concept
                                     }
                                   }
                                 return
                                 copy $f := $fact
                                 modify (
                                     replace value of json $f.Decimals with 3,
                                     if(exists($f.AuditTrails))
                                     then replace value of json $f.AuditTrails with [ $audit-trail ]
                                     else insert json { AuditTrails: [ $audit-trail ] } into $f
                                 )
                                 return $f
                               else $fact"
        }
  );

(: Presentation :)
let $presentation := $report.Networks[][$$.ShortName eq "Presentation"]
let $concepts :=
    {
      "fac:CommonStockSharesAuthorized": {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "Id" : "e7c449eb-4e1b-4d20-af35-b783cfdab03e"
      },
      "fac:CommonStockSharesIssued": {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "Id" : "a8a4ae32-0424-437e-a645-428398f95f9c"
      },
      "fac:CommonStockSharesOutstanding": {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "Id" : "f51e72c7-a3ce-4639-99b0-47ca36d54a7b"
      }
    }
let $genInfo := $presentation.Trees."fac:FundamentalAccountingConceptsLineItems".To."fac:FundamentalAccountingConceptsHierarchy".To."fac:GeneralInformationHierarchy"
return
  {
    replace value of json $presentation.LinkRole with $role;
    replace value of json $genInfo.To with {| ( $genInfo.To, $concepts ) |};
  }

(: Hypercube :)
let $conceptsDomain := $report.Hypercubes."xbrl:DefaultHypercube".Aspects."xbrl:Concept".Domains."xbrl:ConceptDomain"
let $concepts :=
    {
      "fac:CommonStockSharesAuthorized": {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "Id" : "e7c449eb-4e1b-4d20-af35-b783cfdab03e"
      },
      "fac:CommonStockSharesIssued": {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "Id" : "a8a4ae32-0424-437e-a645-428398f95f9c"
      },
      "fac:CommonStockSharesOutstanding": {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "Id" : "f51e72c7-a3ce-4639-99b0-47ca36d54a7b"
      }
    }
return
  replace value of json $conceptsDomain.Members with {| $conceptsDomain.Members, $concepts |};

(: ConceptMap :)
let $conceptMap := $report.Networks[][$$.ShortName eq "ConceptMap"]
let $mappings :=
    {
      "fac:CommonStockSharesAuthorized" : {
        "Name" : "fac:CommonStockSharesAuthorized",
        "Label" : "Common Stock Shares (authorized)",
        "To" : {
          "us-gaap:CommonStockSharesAuthorized": {
            "Name" : "us-gaap:CommonStockSharesAuthorized",
            "Id" : "8ed0a312-9891-4d3d-b459-67604dce2124"
          }
        },
        "Id" : "372f39c9-c8ed-4654-a424-6f033bb0ddd2"

      },
      "fac:CommonStockSharesIssued" : {
        "Name" : "fac:CommonStockSharesIssued",
        "Label" : "Common Stock Shares (issued)",
        "To" : {
          "us-gaap:CommonStockSharesIssued": {
            "Name" : "us-gaap:CommonStockSharesIssued",
            "Id" : "1359b87e-5f75-49f3-849b-d410cc399b50"
          }
        },
        "Id" : "66226139-512f-4edd-8c18-6d7e307a1f66"
      },
      "fac:CommonStockSharesOutstanding" : {
        "Name" : "fac:CommonStockSharesOutstanding",
        "Label" : "Common Stock Shares (outstanding)",
        "To" : {
          "dei:EntityCommonStockSharesOutstanding": {
            "Name" : "dei:EntityCommonStockSharesOutstanding",
            "Id" : "b8d27670-5caa-411f-8305-860c0613c31f"
          }
        },
        "Id" : "91b87448-a8dd-4739-9cdf-2cdaef6a4ff6"
      }
    }
return
  {
    replace value of json $conceptMap.LinkRole with $role;
    replace value of json $conceptMap.Trees with {| $conceptMap.Trees, $mappings |};
  }

(: DefinitionModel :)
replace value of json $report.DefinitionModels[1].Breakdowns.y[1].BreakdownTrees[1].LinkRole with $role;

(: adapt default_zero rule :)
let $defaultZeroRule := $report.Rules[][$$.Id eq "default_zero"]
let $formula := replace($defaultZeroRule.Formula,
                        "\"fac:LiabilitiesAndEquity\"\\)",
                        "\"fac:LiabilitiesAndEquity\", \"us-gaap:CommonStockSharesAuthorized\", \"us-gaap:CommonStockSharesIssued\", \"dei:EntityCommonStockSharesOutstanding\")"
                       )
return
  {
    replace value of json $defaultZeroRule.Formula with $formula;
  }

{ "_id": $id,
  Archive: null,
  Label: "Basic Financial Information",
  Description: $desc,
  Prefix: "fac",
  Role: $role,
  Owner: "charlie@prudena.com",
  LastModified: string(current-dateTime()),
  ACL: [],
  Networks: $report.Networks,
  Hypercubes: $report.Hypercubes,
  DefinitionModels: $report.DefinitionModels,
  Rules: [ for $rule in ($report.Rules[], $additionalRules)
           order by $rule.ComputableConcepts[][1], $rule.Id descending empty least
           return $rule ],
  Filters: {
    cik: [  ],
    tag: [ "DOW30" ],
    fiscalYear : [ 2013 ],
    fiscalPeriod : [ "FY" ],
    sic : [  ]
  }
}


Fix tests

Fix tests

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

declare %an:nondeterministic function local:test-taxonomy-label() as item
{
  let $expected :=
  [ {
    "Name" : "jpcrp-cor:AccountingPolicyForDeferredAssetsTextBlock",
    "Labels" : [ {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "繰延資産の処理方法 [テキストブロック]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Accounting policy for deferred assets [text block]"
    },{
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "繰延資産の処理方法"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Accounting policy for deferred assets"
    } ],
    "ComponentRole" : "http://www.xbrl.org/2003/role/link",
    "ComponentLabel" : "Default Component",
    "Archive" : "STANDARD-TAXONOMY-2014"
  }, {
    "Name" : "jpcrp-cor:AccountingPolicyForDeferredAssetsUnderArticle113OfInsuranceBusinessActINSTextBlock",
    "Labels" : [ {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "保険業法第113条繰延資産の処理方法"
    },{
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Accounting policy for deferred assets under article 113 of Insurance Business Act"
    },  {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "保険業法第113条繰延資産の処理方法、保険業 [テキストブロック]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Accounting policy for deferred assets under article 113 of Insurance Business Act-INS [text block]"
    } ],
    "ComponentRole" : "http://www.xbrl.org/2003/role/link",
    "ComponentLabel" : "Default Component",
    "Archive" : "STANDARD-TAXONOMY-2014"
  } ]
  let $endpoint := "report-elements"
  let $params := {aid:"STANDARD-TAXONOMY-2014", label:"\"Accounting policy for deferred assets\""}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].ReportElements
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-taxonomy-name() as item
{
  let $expected :=
  [ {
    "Name" : "jppfs-cor:CurrentAssets",
    "Labels" : [ {
      "Role" : "http://disclosure．edinet-fsa．go．jp/jppfs/ivt/role/totalLabel",
      "Language" : "en",
      "Value" : "Total current assets"
    }, {
      "Role" : "http://disclosure．edinet-fsa．go．jp/jppfs/ivt/role/totalLabel",
      "Language" : "ja",
      "Value" : "流動資産計"
    }, {
      "Role" : "http://disclosure．edinet-fsa．go．jp/jppfs/sec/role/totalLabel",
      "Language" : "ja",
      "Value" : "流動資産計"
    }, {
      "Role" : "http://disclosure．edinet-fsa．go．jp/jppfs/sec/role/totalLabel",
      "Language" : "en",
      "Value" : "Total current assets"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "流動資産"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Current assets"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "流動資産"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Current assets"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/totalLabel",
      "Language" : "ja",
      "Value" : "流動資産合計"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/totalLabel",
      "Language" : "en",
      "Value" : "Total current assets"
    } ],
    "ComponentRole" : "http://www.xbrl.org/2003/role/link",
    "ComponentLabel" : "Default Component",
    "Archive" : "STANDARD-TAXONOMY-2014"
  } ]
  let $endpoint := "report-elements"
  let $params := {aid:"STANDARD-TAXONOMY-2014", name:"jppfs-cor:CurrentAssets"}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].ReportElements
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-company-label() as item
{
  let $expected :=  [ {
      "Name" : "jpcrp030000-asr_e01225-000:LossOfInactiveFacilitiesEL",
      "Labels" : [ {
        "Role" : "http://www．xbrl．org/2003/role/documentation",
        "Language" : "ja",
        "Value" : "設備休止関連損失、特別損失"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/documentation",
        "Language" : "en",
        "Value" : "Loss of inactive facilities-EL"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/label",
        "Language" : "en",
        "Value" : "Loss of inactive facilities"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/label",
        "Language" : "ja",
        "Value" : "設備休止関連損失"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
        "Language" : "en",
        "Value" : "Loss of inactive facilities-EL"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
        "Language" : "ja",
        "Value" : "設備休止関連損失、特別損失"
      } ],
      "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jppfs/rol_ConsolidatedStatementOfIncome",
      "ComponentLabel" : "連結損益計算書",
      "Archive" : "S10028XL"
    }, {
      "Name" : "jpcrp030000-asr_e01225-000:NotesRegardingTheLossOfInactiveFacilitiesTextBlock",
      "Labels" : [ {
        "Role" : "http://www．xbrl．org/2003/role/label",
        "Language" : "en",
        "Value" : "Notes regarding the loss of inactive facilities"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/label",
        "Language" : "ja",
        "Value" : "設備休止関連損失に関する注記"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
        "Language" : "ja",
        "Value" : "設備休止関連損失に関する注記[テキストブロック]"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
        "Language" : "en",
        "Value" : "Notes regarding the loss of inactive facilities[text block]"
      } ],
      "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jpcrp/rol_NotesConsolidatedStatementOfIncome",
      "ComponentLabel" : "連結損益計算書関係",
      "Archive" : "S10028XL"
    }, {
      "Name" : "jpcrp030000-asr_e01225-000:LossOfInactiveFacilitiesEL",
      "Labels" : [ {
        "Role" : "http://www．xbrl．org/2003/role/documentation",
        "Language" : "ja",
        "Value" : "設備休止関連損失、特別損失"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/documentation",
        "Language" : "en",
        "Value" : "Loss of inactive facilities-EL"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/label",
        "Language" : "en",
        "Value" : "Loss of inactive facilities"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/label",
        "Language" : "ja",
        "Value" : "設備休止関連損失"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
        "Language" : "en",
        "Value" : "Loss of inactive facilities-EL"
      }, {
        "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
        "Language" : "ja",
        "Value" : "設備休止関連損失、特別損失"
      } ],
      "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jppfs/rol_StatementOfIncome",
      "ComponentLabel" : "損益計算書",
      "Archive" : "S10028XL"
    } ]
  let $endpoint := "report-elements"
  let $params := {cik:"E01225", label:"\"Loss of inactive facilities\""}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].ReportElements
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-company-name() as item
{
  let $expected :=
  [ {
        "Name" : "jpcrp-cor:NotesConsolidatedStatementOfCashFlowsHeading",
        "Labels" : [ {
          "Role" : "http://www．xbrl．org/2003/role/label",
          "Language" : "en",
          "Value" : "Notes - Consolidated statement of cash flows"
        }, {
          "Role" : "http://www．xbrl．org/2003/role/label",
          "Language" : "ja",
          "Value" : "連結キャッシュ・フロー計算書関係"
        }, {
          "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
          "Language" : "en",
          "Value" : "Notes - Consolidated statement of cash flows [heading]"
        }, {
          "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
          "Language" : "ja",
          "Value" : "連結キャッシュ・フロー計算書関係 [目次項目]"
        } ],
        "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jpcrp/rol_NotesConsolidatedStatementOfCashFlows",
        "ComponentLabel" : "連結キャッシュ・フロー計算書関係",
        "Archive" : "S10028XL"
      }, {
        "Name" : "jpcrp-cor:NotesConsolidatedStatementOfCashFlowsHeading",
        "Labels" : [ {
          "Role" : "http://www．xbrl．org/2003/role/label",
          "Language" : "en",
          "Value" : "Notes - Consolidated statement of cash flows"
        }, {
          "Role" : "http://www．xbrl．org/2003/role/label",
          "Language" : "ja",
          "Value" : "連結キャッシュ・フロー計算書関係"
        }, {
          "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
          "Language" : "en",
          "Value" : "Notes - Consolidated statement of cash flows [heading]"
        }, {
          "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
          "Language" : "ja",
          "Value" : "連結キャッシュ・フロー計算書関係 [目次項目]"
        } ],
        "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jpcrp/rol_CabinetOfficeOrdinanceOnDisclosureOfCorporateInformationEtcFormNo3AnnualSecuritiesReport",
        "ComponentLabel" : "企業内容等の開示に関する内閣府令 第三号様式 有価証券報告書",
        "Archive" : "S10028XL"
      } ]
  let $endpoint := "report-elements"
  let $params := {cik:"E01225", name:"jpcrp-cor:NotesConsolidatedStatementOfCashFlowsHeading"}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].ReportElements
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:sequential function local:check($o as object) as object
{
    if (not(every $k in (keys($o) ! $o.$$) satisfies ($k instance of boolean and $k)))
    then {
            response:status-code(500);
            $o
    } else
            $o
};

local:check({
    taxonomy-label: local:test-taxonomy-label(),
    taxonomy-name: local:test-taxonomy-name(),
    company-label: local:test-company-label(),
    company-name: local:test-company-name()
})

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

declare %an:nondeterministic function local:test-taxonomy-label() as item
{
  let $expected :=
  [ {
    "Name" : "jpcrp-cor:AccountingPolicyForDeferredAssetsTextBlock",
    "Labels" : [ {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "繰延資産の処理方法 [テキストブロック]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Accounting policy for deferred assets [text block]"
    },{
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "繰延資産の処理方法"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Accounting policy for deferred assets"
    } ],
    "ComponentRole" : "http://www.xbrl.org/2003/role/link",
    "ComponentLabel" : "Default Component",
    "Archive" : "STANDARD-TAXONOMY-2014"
  }, {
    "Name" : "jpcrp-cor:AccountingPolicyForDeferredAssetsUnderArticle113OfInsuranceBusinessActINSTextBlock",
    "Labels" : [ {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "保険業法第113条繰延資産の処理方法"
    },{
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Accounting policy for deferred assets under article 113 of Insurance Business Act"
    },  {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "保険業法第113条繰延資産の処理方法、保険業 [テキストブロック]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Accounting policy for deferred assets under article 113 of Insurance Business Act-INS [text block]"
    } ],
    "ComponentRole" : "http://www.xbrl.org/2003/role/link",
    "ComponentLabel" : "Default Component",
    "Archive" : "STANDARD-TAXONOMY-2014"
  } ]
  let $endpoint := "report-elements"
  let $params := {aid:"STANDARD-TAXONOMY-2014", label:"\"Accounting policy for deferred assets\""}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].ReportElements
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-taxonomy-name() as item
{
  let $expected :=
  [ {
    "Name" : "jppfs-cor:CurrentAssets",
    "Labels" : [ {
      "Role" : "http://disclosure．edinet-fsa．go．jp/jppfs/ivt/role/totalLabel",
      "Language" : "en",
      "Value" : "Total current assets"
    }, {
      "Role" : "http://disclosure．edinet-fsa．go．jp/jppfs/ivt/role/totalLabel",
      "Language" : "ja",
      "Value" : "流動資産計"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "流動資産"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Current assets"
    }, {
      "Role" : "http://disclosure．edinet-fsa．go．jp/jppfs/sec/role/totalLabel",
      "Language" : "ja",
      "Value" : "流動資産計"
    }, {
      "Role" : "http://disclosure．edinet-fsa．go．jp/jppfs/sec/role/totalLabel",
      "Language" : "en",
      "Value" : "Total current assets"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "流動資産"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Current assets"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/totalLabel",
      "Language" : "en",
      "Value" : "Total current assets"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/totalLabel",
      "Language" : "ja",
      "Value" : "流動資産合計"
    } ],
    "ComponentRole" : "http://www.xbrl.org/2003/role/link",
    "ComponentLabel" : "Default Component",
    "Archive" : "STANDARD-TAXONOMY-2014"
  } ]
  let $endpoint := "report-elements"
  let $params := {aid:"STANDARD-TAXONOMY-2014", name:"jppfs-cor:CurrentAssets"}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].ReportElements
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-company-label() as item
{
  let $expected :=
  [ {
    "Name" : "jpcrp030000-asr_e01225-000:LossOfInactiveFacilitiesEL",
    "Labels" : [ {
      "Role" : "http://www．xbrl．org/2003/role/documentation",
      "Language" : "en",
      "Value" : "Loss of inactive facilities-EL"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/documentation",
      "Language" : "ja",
      "Value" : "設備休止関連損失、特別損失"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Loss of inactive facilities-EL"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "設備休止関連損失、特別損失"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "設備休止関連損失"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Loss of inactive facilities"
    } ],
    "Label" : "設備休止関連損失",
    "IsNillable" : true,
    "IsAbstract" : false,
    "PeriodType" : "duration",
    "Balance" : "debit",
    "SubstitutionGroup" : "xbrli:item",
    "DataType" : "xbrli:monetaryItemType",
    "BaseType" : "xbrli:monetary",
    "ClosestSchemaBuiltinType" : "xs:decimal",
    "IsTextBlock" : false,
    "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jppfs/rol_ConsolidatedStatementOfIncome",
    "ComponentLabel" : "連結損益計算書",
    "Archive" : "S10028XL"
  }, {
    "Name" : "jpcrp030000-asr_e01225-000:NotesRegardingTheLossOfInactiveFacilitiesTextBlock",
    "Labels" : [ {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "設備休止関連損失に関する注記[テキストブロック]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Notes regarding the loss of inactive facilities[text block]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Notes regarding the loss of inactive facilities"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "設備休止関連損失に関する注記"
    } ],
    "Label" : "設備休止関連損失に関する注記",
    "PreferredLabelRole" : "http://www.xbrl.org/2003/role/label",
    "IsNillable" : true,
    "IsAbstract" : false,
    "PeriodType" : "duration",
    "SubstitutionGroup" : "xbrli:item",
    "DataType" : "nonnum:textBlockItemType",
    "BaseType" : "xs:string",
    "ClosestSchemaBuiltinType" : "xs:string",
    "IsTextBlock" : true,
    "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jpcrp/rol_NotesConsolidatedStatementOfIncome",
    "ComponentLabel" : "連結損益計算書関係",
    "Archive" : "S10028XL"
  }, {
    "Name" : "jpcrp030000-asr_e01225-000:LossOfInactiveFacilitiesEL",
    "Labels" : [ {
      "Role" : "http://www．xbrl．org/2003/role/documentation",
      "Language" : "en",
      "Value" : "Loss of inactive facilities-EL"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/documentation",
      "Language" : "ja",
      "Value" : "設備休止関連損失、特別損失"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Loss of inactive facilities-EL"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "設備休止関連損失、特別損失"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "設備休止関連損失"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Loss of inactive facilities"
    } ],
    "Label" : "設備休止関連損失",
    "IsNillable" : true,
    "IsAbstract" : false,
    "PeriodType" : "duration",
    "Balance" : "debit",
    "SubstitutionGroup" : "xbrli:item",
    "DataType" : "xbrli:monetaryItemType",
    "BaseType" : "xbrli:monetary",
    "ClosestSchemaBuiltinType" : "xs:decimal",
    "IsTextBlock" : false,
    "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jppfs/rol_StatementOfIncome",
    "ComponentLabel" : "損益計算書",
    "Archive" : "S10028XL"
  } ]
  let $endpoint := "report-elements"
  let $params := {cik:"E01225", label:"\"Loss of inactive facilities\""}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].ReportElements
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:nondeterministic function local:test-company-name() as item
{
  let $expected :=
  [ {
    "Name" : "jpcrp-cor:NotesConsolidatedStatementOfCashFlowsHeading",
    "Labels" : [ {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Notes - Consolidated statement of cash flows [heading]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "連結キャッシュ・フロー計算書関係 [目次項目]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Notes - Consolidated statement of cash flows"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "連結キャッシュ・フロー計算書関係"
    } ],
    "Label" : "連結キャッシュ・フロー計算書関係",
    "IsNillable" : true,
    "IsAbstract" : true,
    "PeriodType" : "duration",
    "SubstitutionGroup" : "iod:identifierItem",
    "DataType" : "xbrli:stringItemType",
    "BaseType" : "xs:string",
    "ClosestSchemaBuiltinType" : "xs:string",
    "IsTextBlock" : false,
    "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jpcrp/rol_NotesConsolidatedStatementOfCashFlows",
    "ComponentLabel" : "連結キャッシュ・フロー計算書関係",
    "Archive" : "S10028XL"
  }, {
    "Name" : "jpcrp-cor:NotesConsolidatedStatementOfCashFlowsHeading",
    "Labels" : [ {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "en",
      "Value" : "Notes - Consolidated statement of cash flows [heading]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/verboseLabel",
      "Language" : "ja",
      "Value" : "連結キャッシュ・フロー計算書関係 [目次項目]"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "en",
      "Value" : "Notes - Consolidated statement of cash flows"
    }, {
      "Role" : "http://www．xbrl．org/2003/role/label",
      "Language" : "ja",
      "Value" : "連結キャッシュ・フロー計算書関係"
    } ],
    "Label" : "連結キャッシュ・フロー計算書関係",
    "IsNillable" : true,
    "IsAbstract" : true,
    "PeriodType" : "duration",
    "SubstitutionGroup" : "iod:identifierItem",
    "DataType" : "xbrli:stringItemType",
    "BaseType" : "xs:string",
    "ClosestSchemaBuiltinType" : "xs:string",
    "IsTextBlock" : false,
    "ComponentRole" : "http://disclosure.edinet-fsa.go.jp/role/jpcrp/rol_CabinetOfficeOrdinanceOnDisclosureOfCorporateInformationEtcFormNo3AnnualSecuritiesReport",
    "ComponentLabel" : "企業内容等の開示に関する内閣府令 第三号様式 有価証券報告書",
    "Archive" : "S10028XL"
  } ]
  let $endpoint := "report-elements"
  let $params := {cik:"E01225", name:"jpcrp-cor:NotesConsolidatedStatementOfCashFlowsHeading"}
  let $request := test:invoke($endpoint, $params)
  let $status as integer := $request[1]
  let $actual as array? := $request[2].ReportElements
  return test:assert-deep-equal($expected, $actual, $status, test:url($endpoint, $params))
};

declare %an:sequential function local:check($o as object) as object
{
    if (not(every $k in (keys($o) ! $o.$$) satisfies ($k instance of boolean and $k)))
    then {
            response:status-code(500);
            $o
    } else
            $o
};

local:check({
    taxonomy-label: local:test-taxonomy-label(),
    taxonomy-name: local:test-taxonomy-name(),
    company-label: local:test-company-label(),
    company-name: local:test-company-name()
})


Some more fixes.

Some more fixes.

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

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

(: 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 $eid          as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $cik          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                 variable $profile-name as string  external := $config:profile-name;

session:audit-call($token);

(: HTTP parameter post-processing :)
let $format as string? := api:preprocess-format($format, $request-uri)
let $tag as string* := api:preprocess-tags($tag)
let $tag := if (exists(($cik, $tag, $ticker, $sic, $eid)))
             then $tag
             else "ALL"

(: Entity resolution :)
let $entities := multiplexer:entities($profile-name, $eid, $cik, $tag, $ticker, $sic)
let $entities :=
  for $entity in $entities
  return {|
    project($entity, "_id"),
    {
      Archives: backend:url(
        "filings",
        {|
          {
            eid: $entity._id,
            format: $format,
            profile-name: $profile-name
          },
          {
            fiscalYear: "ALL",
            fiscalPeriod: "ALL"
          }[$profile-name = ("sec", "japan")]
        |}, true)
    },
    trim($entity, "_id")
  |}

let $comment :=
{
    NumEntities: count($entities),
    TotalNumEntities: session:num-entities()
}

let $result := { "Entities" : [ $entities ] }
let $serializers := {
    to-xml : function($res as object) as node() {
        switch($profile-name)
        case "sec" return
        <Entities>{
            companies:to-xml($res.Entities[])
        }</Entities>
        default return <Entities>
            {
                for $id in $res.Entities[]._id
                return <EID>{$id}</EID>
            }
        </Entities>
    },
    to-csv : function($res as object) as string {
        switch($profile-name)
        case "sec" return string-join(companies:to-csv($res.Entities[]))
        default return api:json-to-csv($res.Entities[])
    }
}
return api:serialize($result, $comment, $serializers, $format, "entities")

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

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

(: 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 $eid          as string* external;
declare  %rest:case-insensitive %rest:distinct  variable $cik          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                 variable $profile-name as string  external := $config:profile-name;

session:audit-call($token);

(: HTTP parameter post-processing :)
let $format as string? := api:preprocess-format($format, $request-uri)
let $tag as string* := api:preprocess-tags($tag)
let $tag := if (exists(($cik, $tag, $ticker, $sic, $eid)))
             then $tag
             else "ALL"

(: Entity resolution :)
let $entities := multiplexer:entities($profile-name, $eid, $cik, $tag, $ticker, $sic)
let $entities :=
  if($profile-name ne "sec")
  then $entities ! api:flatten-json-object($$)
  else $entities
let $entities :=
  for $entity in $entities
  return {|
    project($entity, "_id"),
    {
      Archives: backend:url(
        "filings",
        {|
          {
            eid: $entity._id,
            format: $format,
            profile-name: $profile-name
          },
          {
            fiscalYear: "ALL",
            fiscalPeriod: "ALL"
          }[$profile-name = ("sec", "japan")]
        |}, true)
    },
    trim($entity, "_id")
  |}

let $comment :=
{
    NumEntities: count($entities),
    TotalNumEntities: session:num-entities()
}

let $result := { "Entities" : [ $entities ] }
let $serializers := {
    to-xml : function($res as object) as node() {
        switch($profile-name)
        case "sec" return
        <Entities>{
            companies:to-xml($res.Entities[])
        }</Entities>
        default return <Entities>
            {
                for $id in $res.Entities[].EID
                return <EID>{$id}</EID>
            }
        </Entities>
    },
    to-csv : function($res as object) as string {
        switch($profile-name)
        case "sec" return string-join(companies:to-csv($res.Entities[]))
        default return api:json-to-csv($res.Entities[])
    }
}
return api:serialize($result, $comment, $serializers, $format, "entities")