|
| 1 | +from pathlib import Path |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | +from redcap.methods.reports import Reports |
| 5 | + |
| 6 | +from datalad.distribution.dataset import ( |
| 7 | + require_dataset, |
| 8 | + resolve_path, |
| 9 | +) |
| 10 | +from datalad.interface.common_opts import ( |
| 11 | + nosave_opt, |
| 12 | + save_message_opt, |
| 13 | +) |
| 14 | + |
| 15 | +from datalad_next.commands import ( |
| 16 | + EnsureCommandParameterization, |
| 17 | + ValidatedInterface, |
| 18 | + Parameter, |
| 19 | + build_doc, |
| 20 | + datasetmethod, |
| 21 | + eval_results, |
| 22 | + get_status_dict, |
| 23 | +) |
| 24 | +from datalad_next.constraints import ( |
| 25 | + EnsureBool, |
| 26 | + EnsurePath, |
| 27 | + EnsureStr, |
| 28 | + EnsureURL, |
| 29 | +) |
| 30 | +from datalad_next.constraints.dataset import ( |
| 31 | + DatasetParameter, |
| 32 | + EnsureDataset, |
| 33 | +) |
| 34 | +from datalad_next.utils import CredentialManager |
| 35 | + |
| 36 | +from .utils import ( |
| 37 | + update_credentials, |
| 38 | + check_ok_to_edit, |
| 39 | +) |
| 40 | + |
| 41 | + |
| 42 | +@build_doc |
| 43 | +class ExportReport(ValidatedInterface): |
| 44 | + """Export a report of the Project |
| 45 | +
|
| 46 | + This is an equivalent to exporting a custom report via the "My |
| 47 | + Reports & Exports" page in REDCap's interface. A report must be |
| 48 | + defined through the REDCap's interface, and the user needs to look |
| 49 | + up its auto-generated report ID. |
| 50 | +
|
| 51 | + """ |
| 52 | + |
| 53 | + _params_ = dict( |
| 54 | + url=Parameter( |
| 55 | + args=("url",), |
| 56 | + doc="API URL to a REDCap server", |
| 57 | + ), |
| 58 | + report=Parameter( |
| 59 | + args=("report",), |
| 60 | + doc="""the report ID number, provided next to the report name |
| 61 | + on the report list page in REDCap UI""", |
| 62 | + metavar="report_id", |
| 63 | + ), |
| 64 | + outfile=Parameter( |
| 65 | + args=("outfile",), |
| 66 | + doc="file to write. Existing files will be overwritten.", |
| 67 | + ), |
| 68 | + dataset=Parameter( |
| 69 | + args=("-d", "--dataset"), |
| 70 | + metavar="PATH", |
| 71 | + doc="""the dataset in which the output file will be saved. |
| 72 | + The `outfile` argument will be interpreted as being relative to |
| 73 | + this dataset. If no dataset is given, it will be identified |
| 74 | + based on the working directory.""", |
| 75 | + ), |
| 76 | + credential=Parameter( |
| 77 | + args=("--credential",), |
| 78 | + metavar="name", |
| 79 | + doc="""name of the credential providing a token to be used for |
| 80 | + authorization. If a match for the name is found, it will |
| 81 | + be used; otherwise the user will be prompted and the |
| 82 | + credential will be saved. If the name is not provided, the |
| 83 | + last-used credential matching the API url will be used if |
| 84 | + present; otherwise the user will be prompted and the |
| 85 | + credential will be saved under a default name.""", |
| 86 | + ), |
| 87 | + message=save_message_opt, |
| 88 | + save=nosave_opt, |
| 89 | + ) |
| 90 | + |
| 91 | + _validator_ = EnsureCommandParameterization( |
| 92 | + dict( |
| 93 | + url=EnsureURL(required=["scheme", "netloc", "path"]), |
| 94 | + report=EnsureStr(), |
| 95 | + outfile=EnsurePath(), |
| 96 | + dataset=EnsureDataset(installed=True, purpose="export redcap report"), |
| 97 | + credential=EnsureStr(), |
| 98 | + message=EnsureStr(), |
| 99 | + save=EnsureBool(), |
| 100 | + ) |
| 101 | + ) |
| 102 | + |
| 103 | + @staticmethod |
| 104 | + @datasetmethod(name="export_redcap_report") |
| 105 | + @eval_results |
| 106 | + def __call__( |
| 107 | + url: str, |
| 108 | + report: str, |
| 109 | + outfile: Path, |
| 110 | + dataset: Optional[DatasetParameter] = None, |
| 111 | + credential: Optional[str] = None, |
| 112 | + message: Optional[str] = None, |
| 113 | + save: bool = True, |
| 114 | + ): |
| 115 | + |
| 116 | + # work with a dataset object |
| 117 | + if dataset is None: |
| 118 | + # https://github.com/datalad/datalad-next/issues/225 |
| 119 | + ds = require_dataset(None) |
| 120 | + else: |
| 121 | + ds = dataset.ds |
| 122 | + |
| 123 | + # sort out the path in context of the dataset |
| 124 | + res_outfile = resolve_path(outfile, ds=ds) |
| 125 | + |
| 126 | + # refuse to operate if target file is outside the dataset or not clean |
| 127 | + ok_to_edit, unlock = check_ok_to_edit(res_outfile, ds) |
| 128 | + if not ok_to_edit: |
| 129 | + yield get_status_dict( |
| 130 | + action="export_redcap_report", |
| 131 | + path=res_outfile, |
| 132 | + status="error", |
| 133 | + message=( |
| 134 | + "Output file status is not clean or the file does not " |
| 135 | + "belong directly to the reference dataset." |
| 136 | + ), |
| 137 | + ) |
| 138 | + return |
| 139 | + |
| 140 | + # determine a token |
| 141 | + credman = CredentialManager(ds.config) |
| 142 | + credname, credprops = credman.obtain( |
| 143 | + name=credential, |
| 144 | + prompt="A token is required to access the REDCap project API", |
| 145 | + type_hint="token", |
| 146 | + query_props={"realm": url}, |
| 147 | + expected_props=("secret",), |
| 148 | + ) |
| 149 | + |
| 150 | + # create an api object |
| 151 | + api = Reports( |
| 152 | + url=url, |
| 153 | + token=credprops["secret"], |
| 154 | + ) |
| 155 | + |
| 156 | + # perform the api query |
| 157 | + response = api.export_report( |
| 158 | + report_id=report, |
| 159 | + format_type="csv", |
| 160 | + ) |
| 161 | + |
| 162 | + # query went well, store or update credentials |
| 163 | + update_credentials(credman, credname, credprops) |
| 164 | + |
| 165 | + # unlock the file if needed, and write contents |
| 166 | + if unlock: |
| 167 | + ds.unlock(res_outfile) |
| 168 | + with open(res_outfile, "wt") as f: |
| 169 | + f.write(response) |
| 170 | + |
| 171 | + # save changes in the dataset |
| 172 | + if save: |
| 173 | + ds.save( |
| 174 | + message=message if message is not None else "Export REDCap report", |
| 175 | + path=res_outfile, |
| 176 | + ) |
| 177 | + |
| 178 | + # yield successful result if we made it to here |
| 179 | + yield get_status_dict( |
| 180 | + action="export_redcap_report", |
| 181 | + path=res_outfile, |
| 182 | + status="ok", |
| 183 | + ) |
0 commit comments