id: fda-recall-monitor
namespace: company.team
inputs:
- id: firms
type: ARRAY
itemType: STRING
displayName: Recalling firms
description: Company names as FDA writes them in recalls; a name matches any
firm containing it, for example `Baxter` matches Baxter Healthcare
Corporation.
defaults:
- Baxter
- Medtronic
- Abbott
- Pfizer
- Johnson & Johnson
- id: product_types
type: MULTISELECT
displayName: Product types
values:
- drug
- device
- food
defaults:
- drug
- device
- food
- id: lookback_days
type: INT
displayName: Lookback (days)
description: Recalls FDA reported in this many days are read. Recalls already
alerted on are skipped.
defaults: 30
variables:
seen_key: fda_recalls_alerted
tasks:
- id: seen
type: io.kestra.plugin.core.kv.Get
description: Recall numbers already alerted on by earlier runs.
key: "{{ vars.seen_key }}"
errorOnMissing: false
- id: each_type
type: io.kestra.plugin.core.flow.Loop
values: "{{ inputs.product_types }}"
outputs:
- id: recalls
type: STRING
# openFDA answers 404 when nothing matches.
value: "{{ outputs.enforcement.code == 200 ? outputs.enforcement.body :
'{\"results\": []}' }}"
tasks:
- id: enforcement
type: io.kestra.plugin.core.http.Request
description: The openFDA enforcement reports of the watched firms for one
product type.
uri: "https://api.fda.gov/{{ item.value }}/enforcement.json"
params:
search: >-
({% for firm in inputs.firms %}recalling_firm:"{{ firm }}"{{
loop.last ? '' : ' ' }}{% endfor %}) AND report_date:[{{ now() |
dateAdd(-inputs.lookback_days, 'DAYS') | date('yyyyMMdd') }} TO {{
now() | date('yyyyMMdd') }}]
limit: "1000"
options:
allowFailed: true
- id: recalls
type: io.kestra.plugin.jdbc.duckdb.Query
description: One row per recall event, with the recall numbers an earlier run
hasn't alerted on yet.
inputFiles: |
{
{%- for t in outputs.each_type.outputs %}
"{{ t.item.value }}.json": {{ t.outputs.recalls | toJson }}{{ loop.last ? '' : ',' }}
{%- endfor %}
}
fetchType: FETCH
sql: |
WITH raw AS (
SELECT regexp_extract(filename, '([^/]+)\.json$', 1) AS product_type, unnest(results, max_depth := 2)
FROM read_json('{{ workingDir }}/*.json', filename = true, format = 'auto',
columns = {results: 'STRUCT(recall_number VARCHAR, classification VARCHAR, status VARCHAR, recalling_firm VARCHAR,
product_description VARCHAR, reason_for_recall VARCHAR, report_date VARCHAR,
recall_initiation_date VARCHAR, distribution_pattern VARCHAR, product_quantity VARCHAR,
voluntary_mandated VARCHAR, event_id VARCHAR)[]'})
),
recalls AS (
-- A recall number is one product of a recall event; keep one row per number.
SELECT * FROM raw WHERE recall_number IS NOT NULL
QUALIFY row_number() OVER (PARTITION BY recall_number ORDER BY report_date DESC) = 1
),
seen(recall_number) AS (
SELECT unnest(from_json('{{ outputs.seen.value ?? [] | toJson }}', '["VARCHAR"]'))
),
events AS (
-- One recall event often covers several products, each with its own recall number: report the event once.
SELECT r.event_id, r.product_type, r.classification, any_value(r.recalling_firm) AS recalling_firm,
any_value(r.status) AS status, min(strptime(r.report_date, '%Y%m%d')::DATE) AS report_date,
list(r.recall_number ORDER BY r.recall_number) AS recall_numbers,
list(r.recall_number ORDER BY r.recall_number) FILTER (WHERE r.recall_number NOT IN (SELECT recall_number FROM seen)) AS new_recall_numbers,
arg_min(regexp_replace(r.product_description, '\s+', ' ', 'g'), r.recall_number) AS product,
any_value(rtrim(regexp_replace(r.reason_for_recall, '\s+', ' ', 'g'), '. ')) AS reason
FROM recalls r
GROUP BY r.event_id, r.product_type, r.classification
)
SELECT product_type, event_id, classification, status, recalling_firm, report_date, recall_numbers,
coalesce(new_recall_numbers, []) AS new_recall_numbers,
new_recall_numbers IS NULL AS already_alerted,
format('{} ({} recall event {}, {}{}): {} Reason: {} Reported {}.', recalling_firm, product_type, event_id, status,
CASE WHEN len(recall_numbers) = 1 THEN ', ' || recall_numbers[1]
ELSE format(', {} products: {}', len(recall_numbers), array_to_string(recall_numbers, ', ')) END,
CASE WHEN length(product) > 160 THEN rtrim(left(product, 160)) || '…' ELSE rtrim(product, '. ') || '.' END,
CASE WHEN length(reason) > 220 THEN rtrim(left(reason, 220)) || '…' ELSE reason || '.' END,
report_date) AS message
FROM events
ORDER BY classification, report_date DESC, event_id
- id: report
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.recalls.rows | jq('[.[] | select(.already_alerted | not)]
| length') | first > 0 }}"
then:
- id: log_class_1
type: io.kestra.plugin.core.log.Log
runIf: "{{ outputs.recalls.rows | jq('[.[] | select((.already_alerted | not) and
.classification == \"Class I\")] | length') | first > 0 }}"
level: WARN
message: |
New Class I recall(s), the most serious (reasonable probability of serious harm or death):
{% for r in outputs.recalls.rows %}{% if not r.already_alerted and r.classification == 'Class I' %}- {{ r.message }}
{% endif %}{% endfor %}
- id: log_digest
type: io.kestra.plugin.core.log.Log
runIf: "{{ outputs.recalls.rows | jq('[.[] | select((.already_alerted | not) and
.classification != \"Class I\")] | length') | first > 0 }}"
message: |
New Class II/III recall(s):
{% for r in outputs.recalls.rows %}{% if not r.already_alerted and r.classification != 'Class I' %}- {{ r.classification }}: {{ r.message }}
{% endif %}{% endfor %}
- id: slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Optional. Without the SLACK_WEBHOOK_URL secret this step fails as a
warning; the recalls above are already logged.
allowFailure: true
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
# A full JSON payload: `messageText` starting with a number is cut to that number (kestra-io/plugin-slack#103).
payload: >-
{{ outputs.recalls.rows | jq('[.[] | select(.already_alerted | not)]
as $new
| ($new | map(select(.classification == "Class I"))) as $c1
| ($new | map(select(.classification != "Class I"))) as $rest
| def lines($l): ($l[:25] | map("• " + .classification + ": " + .message) | join("\n"))
+ (if ($l | length) > 25 then "\n…and " + (($l | length) - 25 | tostring) + " more in the execution logs" else "" end);
{text: ((if ($c1 | length) > 0 then ":rotating_light: " + ($c1 | length | tostring) + " new Class I recall(s):\n" + lines($c1) + "\n" else "" end)
+ (if ($rest | length) > 0 then ($rest | length | tostring) + " new Class II/III recall(s):\n" + lines($rest) else "" end))}')
| first | toJson }}
- id: remember
type: io.kestra.plugin.core.kv.Set
description: Adds the recalls just reported to the alerted list, keeping the
2,000 most recent numbers.
key: "{{ vars.seen_key }}"
kvType: JSON
value: >-
{{ {'seen': outputs.seen.value ?? [], 'rows': outputs.recalls.rows}
| jq('[.rows[].new_recall_numbers[]] as $new | (.seen - $new) + $new | .[-2000:]') | first | toJson }}
else:
- id: nothing_new
type: io.kestra.plugin.core.log.Log
message: No new recall from the watched firms.
outputs:
- id: new_recalls
type: INT
value: "{{ outputs.recalls.rows | jq('[.[] | select(.already_alerted | not)] |
length') | first }}"
triggers:
- id: weekly
type: io.kestra.plugin.core.trigger.Schedule
description: FDA publishes its Enforcement Report weekly, on Wednesdays.
cron: "0 12 * * 4"