Metadata-Version: 2.5
Name: invenio-pidbox
Version: 0.8.2
Summary: InvenioRDM PIDBox integration for people, organizations, and works.
Project-URL: Homepage, https://codeberg.org/front-matter/invenio-pidbox
Project-URL: Repository, https://codeberg.org/front-matter/invenio-pidbox
Project-URL: Bug Tracker, https://codeberg.org/front-matter/invenio-pidbox/issues
License: MIT
License-File: LICENSE
Keywords: author,citation,invenio,organization,pidbox
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.14
Requires-Dist: commonmeta-py[backend]>=0.318
Requires-Dist: commonmeta-rs>=0.12.21
Requires-Dist: invenio-app-rdm>=14.0.0
Requires-Dist: requests>=2.31
Provides-Extra: tests
Requires-Dist: invenio-app>=1.4.0; extra == 'tests'
Requires-Dist: invenio-rdm-records>=14.0.0; extra == 'tests'
Requires-Dist: invenio-search[opensearch2]>=3.0.0; extra == 'tests'
Requires-Dist: pytest-black>=0.3.0; extra == 'tests'
Requires-Dist: pytest-isort>=3.1.0; extra == 'tests'
Requires-Dist: pytest<9,>=7.4.0; extra == 'tests'
Description-Content-Type: text/markdown

# invenio-pidbox

InvenioRDM integration that serves people, organizations and citations from a
commonmeta SQLite store, read through commonmeta-py and commonmeta-rs.

The store is the one a commonmeta import already maintains — ORCID persons, ROR
organizations, works and the relations between them. This package reads it, and
adds no tables of its own: no application-specific people or organizations
tables, no citation store, no schema. Everything it exposes is a view onto that
one file.

## Features

**Profiles** — people, organization and container (journal, blog) profile
pages for InvenioRDM, with list and search pages, template context injected on the profile routes, and a
stylesheet and search-result components shipped as webpack bundles.

**Deposit autocomplete** — creator, affiliation and funder suggestions served
from commonmeta-rs Tantivy search, with the deposit form's overridable
components registered to route lookups to pidbox when configured.

**Awards** — the store's grants (Crossref grants and DataCite Awards) offered
in the funding field of the deposit form and of a community's settings, in
place of the awards vocabulary.

**Record relations** — affiliations, funders and awards resolved from the
store as well as the vocabularies, on records and on communities, so either
may name any organization or grant the store knows. Opt-in, because it changes
which records an instance accepts.

**Facet labels** — search facets fall back to the store for ids the vocabulary
cannot label, so an organization accepted by the relations above does not appear
in the sidebar as a bare ROR id.

**Citations** — citation counts and citing works, read from the store's
`pid_relations` table and served as commonmeta works, plus a
`pidbox:citations` custom field for the works a record itself cites.

**Bounded store access** — every read runs with a deadline behind a circuit
breaker, so a store that has gone slow degrades the feature that reads it
instead of holding request threads.

## Requirements

- Python 3.14+
- A commonmeta SQLite database readable through commonmeta-rs

Internally, commonmeta-rs reads `pid_annotations` records with source_id 4 for
people (ORCID) and source_id 3 for organizations (ROR), works from
`pid_records`, and citations from `pid_relations`.

## Installation

```bash
uv add invenio-pidbox
```

This package depends on commonmeta-py, commonmeta-rs, and invenio-app-rdm at
runtime, so installing invenio-pidbox pulls in the profile backend
automatically.

## Configuration

### Required

- `PIDBOX_SQLITE_PATH` — path to the commonmeta SQLite store, used by every
  feature below. Defaults to `/var/lib/commonmeta/commonmeta.sqlite3`.

### Front page metrics

```python
PIDBOX_FRONTPAGE_METRICS = True
```

The front page shows the metrics of the profile pages for all records, in the
header band, in place of the site's title and subtitle
(`THEME_FRONTPAGE_TITLE`, `THEME_FRONTPAGE_SUBTITLE`): all works, works published this year and
cited works, then the shares of works with ORCID iDs, references and funding,
in two rows of three. Each card links to the search it counts, and they stay
hidden while there are no records. The package's
`invenio_app_rdm/header_frontpage.html` includes them; an instance with a
`header_frontpage.html` of its own keeps it, and can include
`invenio_app_rdm/frontpage_metrics.html` where it likes.

The metrics sit on the band's background, which the theme sets
(`.frontpage-header` in the instance's less). For a band too dark for them:

```python
PIDBOX_FRONTPAGE_METRICS_BACKGROUND = "#cbd5e1"
```

A column to the left of the cards holds, by default, a ring with the share of
works with an open license (a Creative Commons license or CC0, in the open
access orange and with its logo). It can hold cards instead, one per row:

```python
PIDBOX_FRONTPAGE_METRICS_COLUMN = ["license"]  # the default
PIDBOX_FRONTPAGE_METRICS_COLUMN = [
    {"card": "communities", "type": "blog", "label": "Participating Blogs"},
    "ror",
]
```

- `license` — the open license ring.
- `communities` — the number of communities, of one `type` if given, linked to
  the communities search.
- `first` — the year of the first work, linked to the works oldest first.
- `ror` — the share of works with a ROR ID among their creators' affiliations.

Their labels follow `PIDBOX_METRICS_NOUN`, except the communities card's. A
card given as a dict can replace its `label`, its `icon` (a URL) and its
`accent` colour. Labels are looked up in the message catalogs, so an instance
translates its own in its translations.

The labels of the metrics, here and on the profile pages, name what the
instance holds: works, or blog posts ("All Posts", "Cited Posts", "First Post"
and so on). Both are in the message catalogs.

```python
PIDBOX_METRICS_NOUN = "work"  # the default; "post" for a blog archive
```

The cards count with the `orcid`-scheme, `references:`, `citations:` and
`funder:` searches, so the instance's `RDM_SEARCH` query parser needs those
fields.

The icons of the metrics and the profile pages ship with the package, in
`invenio_pidbox/static/images/pidbox/`. `invenio collect` copies them into the
instance's static folder, and they are served from `/static/images/pidbox/`.

### Community metrics

```python
PIDBOX_COMMUNITY_METRICS = True
PIDBOX_COMMUNITY_METRICS_COLUMN = ["license"]  # e.g. ["first", "ror"]
```

Every community page shows the same metrics for the community's records, in
the community header above its menu, counted with
`/api/communities/<slug>/records` and linked to the community's own search.
The first column takes the same items as the front page's. The package's
`invenio_communities/details/header.html` includes them; it is
invenio-communities' own (28.3) with that one include added, in a
`subheader_metrics` block. An instance with a `details/header.html` of its
own includes `invenio_communities/details/community_metrics.html` itself, on
the pages that set `community_menu_active`: a record's page and the deposit
form include the header too, for a community with a theme.

### Translations

The strings of the templates and the Python code are translated through
gettext catalogs in `invenio_pidbox/translations`, which invenio-i18n loads
through the `invenio_i18n.translations` entry point. English is the source
language; German, French and Spanish are complete. Where InvenioRDM translates
the same string, each catalog uses its wording, because the last catalog loaded
wins: pidbox's would otherwise replace InvenioRDM's across the site.

```bash
# after changing a string
uv run pybabel extract -F babel.ini -k lazy_gettext -k _ --no-wrap \
  -o invenio_pidbox/translations/messages.pot invenio_pidbox
uv run pybabel update -i invenio_pidbox/translations/messages.pot \
  -d invenio_pidbox/translations --no-wrap
# translate the new entries, then
uv run pybabel compile -d invenio_pidbox/translations
# a new language
uv run pybabel init -i invenio_pidbox/translations/messages.pot \
  -d invenio_pidbox/translations -l fr --no-wrap
```

The React components of the deposit form and search pages translate through
invenio-rdm-records' i18next catalogs and aren't covered here.

### Profile pages

```python
PIDBOX_PERSON_PROFILES = True        # people: pages and search
PIDBOX_ORGANIZATION_PROFILES = True  # organizations: pages and search
PIDBOX_CONTAINER_PROFILES = True     # containers (journals, blogs): pages and search
```

Each switch covers one kind of entity entirely:

| Surface | `PIDBOX_PERSON_PROFILES` | `PIDBOX_ORGANIZATION_PROFILES` | `PIDBOX_CONTAINER_PROFILES` |
|---|---|---|---|
| Pages | `/people/`, `/people/<orcid>` | `/organizations/`, `/organizations/<ror>` | `/containers/`, `/containers/<issn>` |
| Search | `/api/pidbox/names`, `/api/pidbox/people` | `/api/pidbox/affiliations`, `/api/pidbox/funders`, `/api/pidbox/organizations` | `/api/pidbox/containers` |

The pages are always routed and redirect to the record search when their kind is
off; the search endpoints are registered only while it is on.

`/api/pidbox/people`, `/api/pidbox/organizations` and `/api/pidbox/containers`
take `?community=<slug or id>`: the people, organizations or containers of
that community's records. On a community's pages the menubar search offers the
community's works, people, organizations and containers, and keeps the
community with the search; it has no search of all works there.

Only people with works here have a page, and the people search lists only
them: the store holds everyone with an ORCID iD, the instance the works of a
few. A person's page answers 404 when the reader can see none of their works.
The people search (`/api/pidbox/people`) finds the ORCID iDs among the
creators of the records, the most prolific first, keeps those whose names
match the search, and reads them from the store; without a search it lists
the people with the most works. The deposit form's creator autocomplete keeps
`/api/pidbox/names`, which searches the whole store, since a depositor adds
people who have no works here yet.

```python
PIDBOX_PEOPLE_WITH_WORKS = True  # False: pages and search for the whole store
```

Organizations and containers are searched the same way:

```python
PIDBOX_ORGANIZATIONS_WITH_WORKS = True  # False: search the whole store
PIDBOX_CONTAINERS_WITH_WORKS = True     # False: pages and search for the whole store
```

The organization search (`/api/pidbox/organizations`) finds the ROR IDs among
the creators' affiliations and the funders of the records, those with the most
works first, and keeps the organizations whose names, acronyms or other names
match. An organization's page is there whether or not it has works here, as
before. The deposit form's affiliation and funder pickers keep
`/api/pidbox/affiliations` and `/api/pidbox/funders`, which search the whole
store.

A record names its container in the `journal:journal` custom field, by title
and ISSN, so the container search (`/api/pidbox/containers`) finds the ISSNs
among the records, those with the most works first, reads each container from
the store by ISSN, and keeps those whose titles match. A container named by two
of its ISSNs is listed once. A container's page, `/containers/<issn>`, answers
404 when the reader can see none of its works, and lists its works with the
metrics above them. A container without an ISSN — a repository, a DataCite
client — is named by no record, and has no page; an instance without the
`journal:journal` custom field has no containers to list.

Both searches count their facets over what they list — organizations by type
and country, containers by type, country and language — so the counts and the
list agree. With `PIDBOX_CONTAINERS_WITH_WORKS = False` the containers are
searched in the store's index instead, faceted by the same three, which needs
an index built by commonmeta-rs 0.12.15 or later (`commonmeta search --index
--full`).

A person's page lists the records with their ORCID iD among the creators. An
organization's page lists the records with its ROR ID as a creator's affiliation
or as a funder, so a funder's page shows the works it funded; the affiliations
and funders facets narrow the list to either. The metrics above the list count
the same records.

The column beside the metrics cards of both pages takes the same items as the
front page's, the open license ring by default:

```python
PIDBOX_PROFILE_METRICS_COLUMN = ["license"]  # e.g. ["first"]
```

Funders follow the organization switch because they *are* organizations — the
endpoint serves ROR records, those typed as a funder first. Citations
follow neither: `/api/pidbox/citations/<doi>` is about works, and is always
served.

Both **on** by default, and independent of each other — serving these pages is
what the package is for. Either can be switched off, including from the
environment:

```bash
INVENIO_PIDBOX_PERSON_PROFILES=False
```

Use `False` or `0`, not `false`: Invenio literal-evals the value and keeps the
raw string when that fails, so lowercase `false` is a non-empty string and reads
as **on**.

A kind that is off still has its four page routes, and they redirect to the
record search instead of rendering — `/people/<orcid>` goes to the records that
person wrote, which is the same place the page already went for a profile the
store does not hold. The setting changes no data.

That matters for templates. `url_for("invenio_pidbox.person_profile", …)`
raises `BuildError` for an endpoint that was never registered, so leaving the
routes out did not give a dead link: it gave a 500 on every page linking to a
profile, on instances that had switched profiles off on purpose. The endpoints
therefore always resolve, and the switch decides what the page does.

The deposit form follows suit. With `…NAMES_PROVIDER = "pidbox"`, each picker
is pointed at pidbox only for a kind that is on, and otherwise keeps the
vocabulary URL it had before this package was installed — pointing the form at
an endpoint that was never registered would leave the picker silently empty,
which reads as "no matches" rather than as a misconfiguration.

The search-result components still link to `/people/<orcid>` and
`/organizations/<ror>`; with the matching kind off those links land on the
records instead of a profile, rather than breaking.

### Deposit autocomplete

- `APP_RDM_DEPOSIT_FORM_AUTOCOMPLETE_NAMES`
- `APP_RDM_DEPOSIT_FORM_AUTOCOMPLETE_NAMES_PROVIDER`
- `PIDBOX_AUTOCOMPLETE_API`

To enable pidbox autocomplete in the deposit form, set:

```python
APP_RDM_DEPOSIT_FORM_AUTOCOMPLETE_NAMES = "search"
APP_RDM_DEPOSIT_FORM_AUTOCOMPLETE_NAMES_PROVIDER = "pidbox"
```

The endpoint URLs can be overridden with:

```python
PIDBOX_AUTOCOMPLETE_API = {
    "names": "/api/pidbox/names",
    "affiliations": "/api/pidbox/affiliations",
    "funders": "/api/pidbox/funders",
    "awards": "/api/pidbox/awards",
}
```

The funders endpoint returns every organization, those with `"funder"` in their
`types` first. A commit accepts any ROR organization as a funder, as
InvenioRDM's own funders vocabulary does: many funders, such as ministries, are
typed government rather than funder.

### Record relations

```python
PIDBOX_RECORD_RELATIONS = True
```

Off by default. InvenioRDM validates every affiliation, funder and award id on
each record commit against the `affiliations`, `funders` and `awards`
vocabularies, so a record naming an organization or award that was never
imported into them is rejected with `InvalidRelationValue`. With this on, the
store is consulted first and the vocabulary second, making the accepted set the
union of the two rather than a swap — an unreadable store degrades to exactly
the stock behaviour. A community's organizations, funders and awards are
resolved the same way, as its settings form names them as the deposit form
does; with pidbox's autocomplete on, the form's organizations picker searches
the store's organizations (`PIDBOX_AUTOCOMPLETE_API["affiliations"]`) rather
than the affiliations vocabulary.

Turning this on changes which records an instance will accept, which is why
installing the package does not.

### Awards

The funding field of the deposit form and of a community's settings searches
the `awards` vocabulary, which an instance fills from OpenAIRE or leaves empty.
With `APP_RDM_DEPOSIT_FORM_AUTOCOMPLETE_NAMES_PROVIDER = "pidbox"`, both search
the store's grants instead, through `/api/pidbox/awards`: Crossref grant
records and DataCite Awards, which commonmeta reads as works of type `Grant`
(commonmeta-rs 0.12.15 and later read their title, number, funders and
program).

A grant is offered as the vocabulary offers an award — its title, number,
program, funder and DOI — so the form, its funder filter and a record's
funding look as they do for an award from the vocabulary. Its id is the
grant's DOI, bare and lowercased (`10.35802/079527`), which never collides with
the vocabulary's `<funder ROR>::<number>`. A funder Crossref names by Crossref
Funder ID is offered by the ROR id the store knows it by.

The field itself is InvenioRDM's: pidbox only changes the URL it searches, on
the deposit form through `InvenioAppRdm.Deposit.FundingField.container` and on
a community's settings through
`InvenioCommunities.CommunityProfileForm.AccordionField.MetadataFunding`. The
community settings page is overridden
(`invenio_communities/details/settings/profile.html`) to load pidbox's
components and render the URLs, as it has no deposit form config to read them
from.

A record or community naming a grant is accepted when `PIDBOX_RECORD_RELATIONS`
is on (see [Record relations](#record-relations)); without it, only an award in
the vocabulary is.

The store has to be enriched and its search index rebuilt with a commonmeta-rs
that reads grants, as the index holds what the reader made of each record.

### Facet labels

Facets label their buckets from the vocabularies, so an organization accepted by
the relations above but absent from the vocabulary shows as a raw ROR id. The
store-backed labels fill only those gaps, asking the vocabulary first so a
curated, localized title keeps winning:

```python
from invenio_pidbox.facets import StoreAffiliationsLabels, StoreFundersLabels
```

Use them where the facet is declared, in place of the stock
`AffiliationsLabels` / `FundersLabels` — for example
`value_labels=StoreFundersLabels("funders")`.

### Store access

- `PIDBOX_STORE_TIMEOUT` — seconds a single store read may take before the
  caller gives up (default `2.0`; `0` disables the deadline)
- `PIDBOX_STORE_FAILURE_THRESHOLD` — consecutive timeouts before the store is
  treated as unavailable (default `3`)
- `PIDBOX_STORE_RECOVERY_TIME` — seconds to leave an unavailable store alone
  before trying again (default `60.0`)
- `PIDBOX_CITATIONS_TIMEOUT` — seconds each store read of the Refresh
  citations job may take, in place of `PIDBOX_STORE_TIMEOUT` (default `300.0`):
  it holds no request, and reads up to `PIDBOX_CITATIONS_MAX` citing works at a
  time

These exist because a store shared with a writer can get very slow: reads that
normally take a millisecond have blocked for minutes while an import ran against
the same file, and since a relation is resolved on every record commit, that was
enough to exhaust the request threads and have gunicorn kill the worker. A slow
store is therefore treated as an unavailable one.

### Store status

The administration panel shows the store's status under System, beside the
jobs, at `/administration/pidbox/store`. It is read-only, as the store is
written outside InvenioRDM, and reports what this site sees:

- the store, and whether it can be read;
- the search index, naming every file in it the site can't read (tantivy
  writes `meta.json` and `.managed.json` owner-only, and search fails on them);
- each source's version, last download and record count, from the store's
  `settings` and `downloads` tables;
- what keeps the store from working here, such as a store that stopped
  answering in time.

It reads no more than those two small tables, with the deadline of every other
store read.

### Versions

The works imports link versions as Zenodo does. A work in the store names its
versions with DataCite's `HasVersion` and `IsVersionOf` relations: a concept
DOI stands for all versions of a work, and each version has a DOI of its own.

- A concept isn't imported as a record of its own; its versions are, read from
  the store when the run didn't select them.
- The first version is created as a record, and its parent gets the concept
  DOI, which InvenioRDM shows as "Cite all versions". Every further version is
  created as a new version of those records, oldest first.
- A version imported before, or by another run, gets the concept DOI on its
  parent when it's imported again (also without `update`).

InvenioRDM mints parent DOIs for its own records, with its DataCite or
Crossref provider. An imported concept DOI was registered elsewhere, by Zenodo
for one, so the import sets it as an external PID. The instance needs an
external provider for parent DOIs; without it, publishing a further version of
a parent with such a DOI fails. An instance that doesn't mint DOIs, as below;
one that does keeps its DataCite or Crossref provider first and adds
`"external"` to the providers, with a `condition` that mints only for its own
DOIs:

```python
from invenio_rdm_records.services.pids import providers

RDM_PARENT_PERSISTENT_IDENTIFIER_PROVIDERS = [
    providers.ExternalPIDProvider("external", "doi", label="Concept DOI"),
]
RDM_PARENT_PERSISTENT_IDENTIFIERS = {
    "doi": {
        "providers": ["external"],
        "required": False,
        "condition": lambda record: False,  # never minted on publishing
        "label": "Concept DOI",
        "validator": idutils.is_doi,
        "normalizer": idutils.normalize_doi,
        "is_enabled": providers.ExternalPIDProvider.is_enabled,
    },
}
```

The **Link versions** job (`pidbox_link_versions`) moves works imported
before to this shape. Each record that is a concept (versions, and no concept
of its own) is removed, with a tombstone ("duplicate"), and its DOI goes to its
versions' parent; versions not here yet are imported. A concept whose versions
here have more than one parent is left alone and listed in the run's log, as
putting two parents together is left to a person. The job starts as a dry run
that only counts.

### Communities in the jobs

```python
PIDBOX_JOBS_COMMUNITY_TYPES = []  # the default; e.g. ["journal", "organization", "funder"]
```

With community types set, the jobs offer a **Community** select: the
communities of those types, read when the form opens.

- The works imports (**Import a work**, **Import works by ROR ID**, **by ORCID
  iD**, **by container**) add their works to it once they are published, those
  already here too, in bulk and without inclusion requests (`bulk_add`), so no
  notification goes out. A work already in the community stays in it. Each
  batch logs how many it added and how many the community refused.
- **Refresh citations**, **Attach PDFs** and **Attach software archives** take
  only the records of it.

A run naming a community that isn't of those types fails before it does anything.
With `RDM_COMMUNITY_REQUIRED_TO_PUBLISH` on, an import run must name one:
InvenioRDM lets the system publish a record in no community, so the imports
refuse a run without one before importing anything.
**Refresh citations** also takes a single **DOI**, and at most so many
**Records**, as the attachments do.

### Stopping an import

An import run sends its works out in batches, each a subtask of the run, all
at once. The Jobs dashboard's **Stop** sets the run cancelling, and each batch
checks that before it imports anything: a batch of a stopped run leaves its
works alone (counted as `cancelled`) and closes its subtask, so the run ends
cancelled once the batches already importing have finished. The stop is
remembered in the cache, as finishing a subtask sets the run running again.
Running the same import again resumes: the works already here are skipped.

### References on import

A publisher deposits a reference as text in its own style, or as a DOI alone,
for which the InvenioRDM writer fills the text the field requires with "Unknown
title"; so does the software a JOSS paper describes, its first reference (from
Crossref's `references` relation). The imports give the references one style,
as the deposit form does: a reference to a work the store holds is rendered as
a citation of the work's metadata, in the instance's citation style (APA:
software labelled `[Computer software]`), whatever text was deposited. One the
store doesn't hold keeps its deposited text, else shows its DOI, and one with
neither text nor identifier is left out. The store is read once per record.
Works imported before get it with `update`.

### Attaching PDFs

The works are imported metadata-only. The **Attach PDFs** job
(`pidbox_attach_pdfs`) adds the PDF of each work under CC BY to its record, as
Zenodo's records carry theirs: CC BY lets anyone copy and share the work.

- It takes the published, metadata-only records whose rights are CC BY, any
  version or port (`cc-by-4.0`, `cc-by-3.0-de`), but not `-sa`, `-nc` or `-nd`.
- The PDF's URL is the first PDF among the work's files in the store, as its
  publisher or OpenAlex gives it. The job downloads it with a User-Agent of
  `invenio-pidbox`, and keeps it only if it is a PDF of at most
  `PIDBOX_PDF_MAX_SIZE` bytes (default 50 MB); a login page or a challenge is
  refused and counted.
- The PDF is added to the record in place, without a new version: the record's
  edit draft, its files unlocked and enabled, the PDF uploaded, the draft
  published. A failure discards the edit, so the record stays as it was.
- The files go to the instance's files location, which needs to be writable
  (for an S3 bucket, `INVENIO_S3_*` and a location naming the bucket).

It starts as a dry run that counts the records and those the store has a PDF
for. A DOI takes just that record, to try one first; Records takes the first
ones. The records go out in batches, as the imports' do, each logging what it
attached, found no PDF for, and failed with.


## Routes

| Route | Purpose | Served when |
|---|---|---|
| `/people/` | people list and search page | always routed; redirects when off |
| `/people/<orcid>` | person profile page | always routed; redirects when off |
| `/api/pidbox/names` | creator autocomplete | `PIDBOX_PERSON_PROFILES` |
| `/organizations/` | organization list and search page | always routed; redirects when off |
| `/organizations/<ror>` | organization profile page | always routed; redirects when off |
| `/api/pidbox/organizations` | organizations with works here | `PIDBOX_ORGANIZATION_PROFILES` |
| `/containers/` | container list and search page | always routed; redirects when off |
| `/containers/<issn>` | container profile page | always routed; redirects when off |
| `/api/pidbox/containers` | container search | `PIDBOX_CONTAINER_PROFILES` |
| `/api/pidbox/affiliations` | affiliation autocomplete | `PIDBOX_ORGANIZATION_PROFILES` |
| `/api/pidbox/funders` | funder autocomplete | `PIDBOX_ORGANIZATION_PROFILES` |
| `/api/pidbox/works/<doi>` | a DOI as a deposit record | always |
| `/api/pidbox/citations/<doi>` | works citing a DOI | always |
| `/api/pidbox/awards` | the store's grants, as awards | always |

Both switches are off by default, so a default install serves only the
works, citations and awards routes — see [Profile pages](#profile-pages) above.

Each API route is also registered without the `/api` prefix, because the same
extension is registered on the UI app and the API app, and Invenio mounts the
API app *at* `/api` and strips the prefix.

Autocomplete requests carrying `?suggest=` are capped at 50 results; the profile
search pages are fixed to 10 results per page and 100 in total.

### Attaching software archives

A JOSS paper describes a piece of software, whose archive JOSS deposits on
Zenodo: a zip of the GitHub release, or a tarball. commonmeta gives the paper a
`describes` relation to it (from Crossref's `references` relation), and the
archive's metadata stays on Zenodo, linked from the paper. The **Attach
software archives** job (`pidbox_attach_archives`) adds the archive's files to
the paper's record, beside its PDF.

- It takes the published records with a `describes` relation to a Zenodo DOI
  (`10.5281/zenodo.N`, Zenodo's record `N`).
- It lists the Zenodo record's files with one request
  (`/api/records/N/files`), and downloads each file the record doesn't have
  yet, named without the GitHub owner's folder
  (`owner/repo-v1.0.zip` becomes `repo-v1.0.zip`). A download goes to a
  temporary file, and is kept only if its size and MD5 checksum are Zenodo's.
  There is no size limit, unless `PIDBOX_ARCHIVE_MAX_SIZE` sets one in bytes.
- The files are added to the record in place, as the Attach PDFs job adds a
  PDF: the record keeps its files, and a failure leaves it as it was. The
  record's page goes on previewing the PDF: a record with a PDF and no default
  preview chosen gets the PDF as its default preview.
- Zenodo is a shared service: a request answered with 429 or a server error is
  tried again, after Zenodo's `Retry-After` or a growing pause, four times at
  most, and the job pauses `PIDBOX_ZENODO_DELAY` seconds (default 1) between
  records. A record that has the files already is skipped, so the job can run
  again; a restricted or deleted archive is counted, with its reason.
- `PIDBOX_ZENODO_URL` (default `https://zenodo.org`) points it at another
  InvenioRDM, e.g. Zenodo's sandbox.

It starts as a dry run that counts the records, without asking Zenodo
anything. A DOI takes just that record; Records takes the first ones. The
records go out in batches of five.

### Filling the deposit form from a DOI

When a depositor picks "Yes, I already have one" and enters a DOI, the form
looks it up in the store and fills itself in:

```http
GET /api/pidbox/works/<doi>
```

The DOI is returned as an InvenioRDM record — `metadata`, `custom_fields`, and
`pids.doi.provider` already `external`. The conversion is commonmeta-rs' own
InvenioRDM writer, the same one `commonmeta push` uses to create records, so a
form is filled with exactly what an import would have written rather than from a
second mapping kept here.

A DOI the store does not hold answers `204`, not `404`: the DOI may well exist
elsewhere, the form asked a fair question, and the depositor types as before.
Nothing is fetched over the network.

The form-side half is an override of `InvenioAppRdm.Deposit.PIDField.container`,
which wraps the stock DOI block rather than replacing it — the radio buttons and
the identifier input are still InvenioRDM's. It fills only fields the form has
left empty, so typed input is never overwritten, and it waits for typing to stop
before asking. Record JSON is not form state (a vocabulary is `{"id": "x"}` in a
record and `"x"` in the form), so the record is passed through the deposit
form's own serializer rather than merged raw.

### Citations

```http
GET /api/pidbox/citations/<doi>
```

`<doi>` is a bare DOI or a DOI URL. The response uses the usual hits envelope,
and each hit is a commonmeta work, unchanged:

```json
{"hits": {"hits": [{"id": "https://doi.org/10.1234/a", "title": "Work a"}], "total": 3}}
```

Which relations count as a citation (`References`, `Cites`, `IsSupplementedBy` —
DataCite's definition) is decided by commonmeta-rs, not by this package.

`total` is the citation count and can exceed the number of hits: it is read from
the relation index, while hits are hydrated works, so a citing DOI whose work
has not been imported yet is counted but cannot be listed.

Concept DOIs are also left out of the hits. A versioned publisher — Rogue
Scholar, Zenodo — registers a version DOI and a parent DOI standing over it, and
both cite, so the same work would otherwise appear twice under two identifiers
with one citation text between them. The parent is the one carrying a
`HasVersion` relation, and it is dropped in favour of the specific version that
did the citing. The count knows nothing about versions, so such a citation
counts two and lists one.

`size` (default 10, max 100) and `page` paginate. With commonmeta-rs 0.12.21 or
later a page hydrates only its works, even of a DOI cited tens of thousands of
times; before, every page hydrates every citing work. `size=0` returns just the
count, answered from an index.

### The `pidbox:citations` custom field

Records can also carry the works they cite, as a list of
`{identifier, scheme, reference}` entries indexed with the record:

```json
{
  "identifier": "10.59350/4q8j1-1ap35",
  "scheme": "doi",
  "reference": "Willighagen, E. (2007, May 25). Numbers are copyrighted?. <i>Chem-bla-ics</i>."
}
```

`reference` is the citing work rendered as a formatted citation, so a landing
page can show a reference list rather than a column of DOIs. It uses the
instance's own `RDM_CITATION_STYLES_DEFAULT` (`apa` unless changed), so a stored
reference reads the way the citation box on the same page does. RDM has no
config for the locale — it renders in the requesting user's language, which a
background sweep does not have — so `PIDBOX_CITATIONS_LOCALE` supplies it,
defaulting to the `en-US` RDM itself falls back to.

This is the record-side view of a citation, and it is independent of the
store-side one above — the field says what a record cites, the store says what
cites a DOI. They point in opposite directions, so their numbers are not
expected to match.

The field is not registered automatically, because a custom field has to exist
in the search mapping before a record can use it. To enable it:

```python
from invenio_pidbox.custom_fields import (
    CITATIONS_FACET,
    CITATIONS_QUERY_FIELD,
    CitationsCF,
    PIDBOX_NAMESPACE,
)

RDM_NAMESPACES = {**RDM_NAMESPACES, **PIDBOX_NAMESPACE}
RDM_CUSTOM_FIELDS = [*RDM_CUSTOM_FIELDS, CitationsCF(name="pidbox:citations")]
RDM_FACETS = {**RDM_FACETS, "citations": CITATIONS_FACET}
```

Then create the mapping:

```bash
invenio rdm-records custom-fields init -f pidbox:citations
```

`CITATIONS_QUERY_FIELD` is a `QueryParser` mapping entry, so adding
`"citations": CITATIONS_QUERY_FIELD` to `RDM_SEARCH`'s parser mapping makes
`citations:10.5555/12345678` searchable. Declaring `CITATIONS_FACET` does not
display it — the facet also has to be named in `RDM_SEARCH`'s `facets` list.

commonmeta-rs fills the field when it pushes a record: citing works become
`IsReferencedBy` relations, the InvenioRDM serializer maps those to
`custom_fields["pidbox:citations"]`, and `commonmeta push`/`put --to inveniordm`
sends them to the REST API. Reading records back reverses it. So the store stays
the source of truth and the field is a projection of it onto each record.

That name is hardcoded in commonmeta-rs. Versions before 0.9.80 write
`rs:citations` instead, and against them the field is defined, indexed, and
never populated.

This field comes from Rogue Scholar, where it was `rs:citations`. It is
unchanged apart from the namespace, and the two names are different fields: an
instance holding records under the old one has to migrate and reindex them, and
until it does, those records read as having no citations.

### The citation count

`pidbox:citation_count` is how many works cite a record, among those the
commonmeta store knows, for this version of the record. `pidbox:cited` is
`cited` for a record with citations. Both are written into the record's search
document when it is indexed, beside InvenioRDM's views and downloads (`stats`)
(`invenio_pidbox.dumpers`). They need the fields registered, which
`CITATIONS_CUSTOM_FIELDS` does with the citations, and their mappings
(`invenio rdm-records custom-fields init`):

```python
from invenio_pidbox.custom_fields import (
    CITATIONS_CUSTOM_FIELDS,
    CITATIONS_SORT_OPTION,
    CITED_FACET,
)

RDM_CUSTOM_FIELDS = [*RDM_CUSTOM_FIELDS, *CITATIONS_CUSTOM_FIELDS]
RDM_SORT_OPTIONS = {**RDM_SORT_OPTIONS, "mostcited": CITATIONS_SORT_OPTION}
RDM_FACETS = {**RDM_FACETS, "cited": CITED_FACET}
# and "mostcited" in RDM_SEARCH["sort"], "cited" in RDM_SEARCH["facets"]
```

A record stores at most `PIDBOX_CITATIONS_MAX` citations (default 1000), the
newest: a DOI cited twenty thousand times would otherwise carry megabytes of
references through every edit, index and API response. The Refresh citations
job and the import of a single work store the number of them all beside them,
as `pidbox:citation_count`, and that is the count of such a record. Any other
record's count is the length of `pidbox:citations`. A landing page lists
citations past those stored a page at a time with `invenio_pidbox.tasks.
citation_page`, which reads and formats only that page.

"Most cited" sorts by the count; the facet filters the records with citations.
A record gets its count when it is next indexed: the Refresh citations job
reindexes those whose citations change, a full reindex the others.

### Keeping the field current

A push writes the citations a record had *at that moment*. What makes it stale
afterwards is other records arriving, which is not an event on this record, so
nothing in InvenioRDM would ever notice.

The package therefore ships a sweep, as a job in the **Jobs** administration
dashboard:

```text
Refresh citations   (pidbox_refresh_citations)
```

Installing the package makes the job available there; it does not schedule it.
Whether it runs at all, how often, and with what arguments is set in the
dashboard — this one edits records, which is not something installing a package
should start doing on a timer. Running it needs the Celery worker a standard
deployment already has.

For every record with a DOI the sweep compares `count_sqlite_citations` — an
index lookup — against the number of citations the record already stores, and
skips the record without hydrating anything when they agree. Only a mismatch
pays for the full read, and only a genuine difference in identifiers is written
back, as a metadata edit through the records service (same version, same DOI,
new revision).

For a first run, set the dashboard's custom arguments to bound it and check the
counts it reports:

```json
{"max_records": 100}
```

It returns `{"scanned", "hydrated", "updated", "failed"}`. The same task can be
called directly, for example from `invenio shell`:

```python
from invenio_pidbox.tasks import refresh_citations

refresh_citations(max_records=100)
```

Rendering a citation costs about 25 ms, so a reference already stored for a DOI
is kept rather than rendered again: a run only formats citations the record did
not already have. Records written by `commonmeta push` carry identifiers with no
reference text, and the sweep backfills those.

Three behaviours worth knowing:

- The dashboard's **`since` is ignored**. A record's citations change when other
  records are imported, which does not modify the record, so no timestamp on it
  reflects the change — filtering by one would skip exactly the records that
  need updating. Being cheap on unchanged records is what replaces it.
- A record cited by a work the store has not imported has a count higher than
  anything that can be listed, so it takes the slow path on every run and writes
  nothing. Correct, but not free. A citing work with a concept DOI (below) does
  the same.
- The sweep **never clears** a record's citations. Every store read degrades to
  "none" when the store is unavailable, which is indistinguishable from a DOI
  nothing cites, so a record that holds citations keeps them rather than risk
  emptying every record in the instance.

### Keeping the field through an update

InvenioRDM replaces `custom_fields` with what an update sends, so a field the
record holds and the payload leaves out is deleted rather than left alone. That
is right for every field a deposit form renders, and wrong for this one: nothing
edits citations by hand, so a payload that says nothing about them means
"unknown", not "none". Clearing them costs the sweep a citeproc run and two
revisions to put them back, for a field neither side meant to change.

A service component holds the line. Its rule is that the field absent from an
update keeps what the record has, and the field present in an update — `[]`
included — is the payload deciding:

```python
from invenio_pidbox.components import citations_components

RDM_RECORDS_SERVICE_COMPONENTS = citations_components()
```

`citations_components()` returns InvenioRDM's default component list with the
custom fields component replaced, in place, by the subclass that spares this
one field. Order matters in that list, which is why it substitutes rather than
appends. An instance that already customises the list passes its own:
`citations_components(MY_COMPONENTS)`. Being handed a list with nothing to
replace is a `ValueError`, since a config that quietly installed nothing would
read as one that worked.

A new version starts with no citations. They name the DOI they cite and a new
version has its own, so inheriting them would be wrong — and the sweep's
refusal to clear means a new version that inherited them would hold them for
good.

Deposit form edits need nothing: the form round-trips `custom_fields` whole,
including fields it does not render.

`commonmeta push` carries the field itself, from commonmeta-py 0.293 on: it
reads the record before writing over it and sends back the citations it holds,
with the formatted `reference` text folded into any it does describe. The
component covers the clients that do not — and covers push against an instance
running an older commonmeta-py — but only the writer can keep that text, which
the record would otherwise pay 25 ms a citation to render again.

## How It Works

When a request path matches `/people/<orcid>` or `/organizations/<ror>`, the
extension loads the corresponding commonmeta record from SQLite and exposes
template-friendly objects such as person, organization, employment, identifiers,
relations, location, orcid, ror, and search_config. It also registers the
profile routes and a `country_name` template filter, so it runs against a
standard invenio-app-rdm installation.

For deposit autocomplete it patches invenio-app-rdm's form config at runtime to
inject the endpoint URLs, and loads overridable components that switch the
person, organization and funder remote selects to those endpoints. Awards lookup
stays on the existing awards API.

Reads are optional throughout, and each has a defined fallback: a profile falls
back to a record search, an autocomplete to no suggestions, a relation to the
vocabulary, a facet label to the bare id, a citation listing to none. An absent,
unreadable or slow store therefore costs a feature, not the page.

## Development

```bash
uv sync --extra tests
uv run pytest
```

## Entry points

| Group | Name | Value |
|---|---|---|
| `invenio_base.apps` | `invenio_pidbox` | `invenio_pidbox.ext:InvenioPidbox` |
| `invenio_base.api_apps` | `invenio_pidbox` | `invenio_pidbox.ext:InvenioPidbox` |
| `invenio_assets.webpack` | `invenio_pidbox` | `invenio_pidbox.webpack:profiles` |
| `invenio_administration.views` | `pidbox_store_status` | `invenio_pidbox.administration:StoreStatusView` |
| `invenio_jobs.jobs` | `pidbox_link_versions` | `invenio_pidbox.jobs:LinkVersionsJob` |
| `invenio_jobs.jobs` | `pidbox_attach_pdfs` | `invenio_pidbox.jobs:AttachPdfsJob` |

## License

MIT
