|
| 1 | +import logging |
| 2 | +import re |
| 3 | + |
| 4 | +from mip_api import s3, upstream, util |
| 5 | + |
| 6 | +LOG = logging.getLogger(__name__) |
| 7 | +LOG.setLevel(logging.DEBUG) |
| 8 | + |
| 9 | + |
| 10 | +def get_chart(org_name, secrets, bucket, path): |
| 11 | + """ |
| 12 | + Access the Chart of Accounts from MIP Cloud, and implement a write-through |
| 13 | + cache of successful responses to tolerate long-term faults in the upstream |
| 14 | + API. |
| 15 | +
|
| 16 | + A successful API response will be stored in S3 indefinitely, to be retrieved |
| 17 | + and used in the case of an API failure. |
| 18 | +
|
| 19 | + The S3 bucket has versioning enabled for disaster recovery, but this means |
| 20 | + that every PUT request will create a new S3 object. In order to minimize |
| 21 | + the number of objects in the bucket, read the cache value on every run and |
| 22 | + only update the S3 object if it changes. |
| 23 | + """ |
| 24 | + |
| 25 | + # get the upstream API response |
| 26 | + LOG.info("Read chart of accounts from upstream API") |
| 27 | + upstream_dict = upstream.program_chart(org_name, secrets) |
| 28 | + LOG.debug(f"Upstream API response: {upstream_dict}") |
| 29 | + |
| 30 | + # always read cached value |
| 31 | + LOG.info("Read cached chart of accounts from S3") |
| 32 | + cache_dict = None |
| 33 | + try: |
| 34 | + cache_dict = s3.cache_read(bucket, path) |
| 35 | + LOG.debug(f"Cached API response: {cache_dict}") |
| 36 | + except Exception as exc: |
| 37 | + LOG.exception("S3 read failure") |
| 38 | + |
| 39 | + if upstream_dict: |
| 40 | + # if we received a non-empty response from the upstream API, compare it |
| 41 | + # to our cached response and update the S3 write-through cache if needed |
| 42 | + if upstream_dict == cache_dict: |
| 43 | + LOG.debug("No change in chart of accounts") |
| 44 | + else: |
| 45 | + # store write-through cache |
| 46 | + LOG.info("Write updated chart of accounts to S3") |
| 47 | + try: |
| 48 | + s3.cache_write(upstream_dict, bucket, path) |
| 49 | + except Exception as exc: |
| 50 | + LOG.exception("S3 write failure") |
| 51 | + coa_dict = upstream_dict |
| 52 | + else: |
| 53 | + # no response (or an empty response) from the upstream API, |
| 54 | + # rely on our response cached in S3. |
| 55 | + coa_dict = cache_dict |
| 56 | + |
| 57 | + if not coa_dict: |
| 58 | + # make sure we don't return an empty value |
| 59 | + raise ValueError("No valid chart of accounts found") |
| 60 | + |
| 61 | + return coa_dict |
| 62 | + |
| 63 | + |
| 64 | +def process_chart(params, chart_dict, omit_list, other, no_program): |
| 65 | + """ |
| 66 | + Process chart of accounts to remove unneeded programs, |
| 67 | + and inject some extra (meta) programs. |
| 68 | +
|
| 69 | + 5-digit codes are inactive and should be ignored in most cases. |
| 70 | + 8-digit codes are active, but only the first 6 digits are significant, |
| 71 | + i.e. 12345601 and 12345602 should be deduplicated as 123456. |
| 72 | + """ |
| 73 | + |
| 74 | + # deduplicate on shortened numeric codes |
| 75 | + # pre-populate with codes to omit to short-circuit their processing |
| 76 | + found_codes = [] |
| 77 | + found_codes.extend(omit_list) |
| 78 | + |
| 79 | + # output object |
| 80 | + out_chart = {} |
| 81 | + |
| 82 | + # whether to filter out inactive codes |
| 83 | + code_len = 5 |
| 84 | + if util.param_inactive_bool(params): |
| 85 | + code_len = 6 |
| 86 | + |
| 87 | + # optionally move this list of codes to the top of the output |
| 88 | + priority_codes = util.param_priority_list(params) |
| 89 | + |
| 90 | + # add short codes |
| 91 | + for code, _name in chart_dict.items(): |
| 92 | + if len(code) >= code_len: |
| 93 | + # truncate active codes to the first 6 significant digits |
| 94 | + short = code[:6] |
| 95 | + # enforce AWS tags limitations |
| 96 | + # https://docs.aws.amazon.com/tag-editor/latest/userguide/best-practices-and-strats.html |
| 97 | + # enforce removing special characters globally for consistency, |
| 98 | + # only enforce string limit when listing tag values because the string size will change. |
| 99 | + regex = r"[^\d\w\s.:/=+\-@]+" |
| 100 | + name = re.sub(regex, "", _name) |
| 101 | + |
| 102 | + if short in found_codes: |
| 103 | + LOG.info(f"Code {short} has already been processed") |
| 104 | + continue |
| 105 | + |
| 106 | + if priority_codes is not None: |
| 107 | + if short in priority_codes: |
| 108 | + # Since Python 3.7, python dictionaries preserve insertion |
| 109 | + # order, so to prepend an item to the top of the dictionary, |
| 110 | + # we create a new dictionary inserting the target code first, |
| 111 | + # then add the previous output, and finally save the new |
| 112 | + # dictionary as our output dictionary. |
| 113 | + new_chart = {short: name} |
| 114 | + new_chart.update(out_chart) |
| 115 | + out_chart = new_chart |
| 116 | + found_codes.append(short) |
| 117 | + else: |
| 118 | + out_chart[short] = name |
| 119 | + found_codes.append(short) |
| 120 | + else: |
| 121 | + out_chart[short] = name |
| 122 | + found_codes.append(short) |
| 123 | + |
| 124 | + # inject "other" code |
| 125 | + if util.param_other_bool(params): |
| 126 | + new_chart = {other: "Other"} |
| 127 | + new_chart.update(out_chart) |
| 128 | + out_chart = new_chart |
| 129 | + |
| 130 | + # inject "no program" code |
| 131 | + if util.param_no_program_bool(params): |
| 132 | + new_chart = {no_program: "No Program"} |
| 133 | + new_chart.update(out_chart) |
| 134 | + out_chart = new_chart |
| 135 | + |
| 136 | + return out_chart |
| 137 | + |
| 138 | + |
| 139 | +def limit_chart(params, chart_dict): |
| 140 | + """ |
| 141 | + Optionally limit the size of the chart based on a query-string parameter. |
| 142 | + """ |
| 143 | + |
| 144 | + # if a 'limit' query-string parameter is defined, "slice" the dictionary |
| 145 | + limit = util.param_limit_int(params) |
| 146 | + if limit > 0: |
| 147 | + # https://stackoverflow.com/a/66535220/1742875 |
| 148 | + short_dict = dict(list(chart_dict.items())[:limit]) |
| 149 | + return short_dict |
| 150 | + |
| 151 | + return chart_dict |
| 152 | + |
| 153 | + |
| 154 | +def list_tags(params, chart_dict): |
| 155 | + """ |
| 156 | + Generate a list of valid AWS tags. Only active codes are listed. |
| 157 | +
|
| 158 | + The string format is `{Program Name} / {Program Code}`. |
| 159 | +
|
| 160 | + Returns |
| 161 | + A list of strings. |
| 162 | + """ |
| 163 | + |
| 164 | + tags = [] |
| 165 | + |
| 166 | + # build tags from chart of accounts |
| 167 | + for code, name in chart_dict.items(): |
| 168 | + # enforce AWS tags limitations |
| 169 | + # https://docs.aws.amazon.com/tag-editor/latest/userguide/best-practices-and-strats.html |
| 170 | + # max tag value length is 256, truncate |
| 171 | + # only enforce when listing tag values |
| 172 | + tag = f"{name[:245]} / {code[:6]}" |
| 173 | + tags.append(tag) |
| 174 | + |
| 175 | + limit = util.param_limit_int(params) |
| 176 | + if limit > 0: |
| 177 | + LOG.info(f"limiting output to {limit} values") |
| 178 | + return tags[0:limit] |
| 179 | + else: |
| 180 | + return tags |
0 commit comments