Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
push:
branches: [master]
pull_request:
workflow_call:

permissions:
contents: read
Expand All @@ -12,8 +13,8 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6.8.0
with:
python-version: "3.11"
- run: uv sync --locked
Expand All @@ -26,11 +27,11 @@ jobs:
strategy:
fail-fast: false
matrix:
# 3.11 is the floor because toolio-ml runs on Databricks DBR 15.4.
# 3.11 is the oldest supported version (requires-python).
python-version: ["3.11", "3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6.8.0
with:
python-version: ${{ matrix.python-version }}
- run: uv sync --locked
Expand All @@ -40,8 +41,8 @@ jobs:
# The reference data must be exactly what the pinned JS package produces.
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: "22"
- name: Check generated data is up to date
Expand All @@ -51,15 +52,15 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6.8.0
- run: uv build
- name: Check the wheel installs and imports with no dependencies
run: |
uv venv --python 3.11 /tmp/wheel-check
uv pip install --python /tmp/wheel-check dist/*.whl
/tmp/wheel-check/bin/python -c "import retail_calendar, sys; assert not set(sys.modules) & {'pandas', 'numpy'}"
- uses: actions/upload-artifact@v4
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: dist
path: dist/
53 changes: 53 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
name: Release

# Pushing a v* tag runs CI, then publishes a GitHub Release with the wheel and sdist attached.
# Projects install the wheel from the release URL, pinned by its SHA-256 (see README).
on:
push:
tags: ["v*"]

permissions:
contents: read

jobs:
ci:
uses: ./.github/workflows/ci.yml

release:
needs: ci
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
fetch-depth: 0
- uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6.8.0
- name: Check the tag is on master and matches the package version
run: |
if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/master; then
echo "Tag $GITHUB_REF_NAME is not on master" >&2
exit 1
fi
version="$(uv version --short)"
if [[ "$GITHUB_REF_NAME" != "v$version" ]]; then
echo "Tag $GITHUB_REF_NAME does not match the package version $version" >&2
exit 1
fi
- run: uv build
- name: Publish the release
env:
GH_TOKEN: ${{ github.token }}
run: |
wheel="$(cd dist && ls *.whl)"
sha256="$(sha256sum "dist/$wheel" | cut -d' ' -f1)"
url="https://github.com/$GITHUB_REPOSITORY/releases/download/$GITHUB_REF_NAME/$wheel"
cat > notes.md <<NOTES
Install with this line in requirements.txt:

\`\`\`
retail-calendar @ $url#sha256=$sha256
\`\`\`
NOTES
# With assets, gh uploads them to a draft and publishes it only once they're all uploaded.
gh release create "$GITHUB_REF_NAME" dist/* --title "$GITHUB_REF_NAME" --notes-file notes.md --verify-tag
55 changes: 38 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@ A configurable merchandising and retail calendar for Python: NRF 4-5-4, 4-4-5, 5
calendars, with their Gregorian boundaries.

This is a port of the [`retail-calendar`](https://github.com/holonk/retail-calendar) npm package (v4.1.2). It
produces the same calendars, and its integer and label values match the JS package, the `calendarconfiguration` table
and retail-calendar-api, so tenant configurations can be used as they are.
produces the same calendars, and its integer and label values match the JS package, so a calendar configuration can be
shared between the two as it is.

- No dependencies outside the Python standard library.
- Typed (`py.typed`), immutable value objects, cached calendars.
- Python 3.11+ (toolio-ml runs on Databricks DBR 15.4, which has Python 3.11).
- Python 3.11+.

> [!IMPORTANT]
> **Note for AI agents and contributors: keep this repo and [holonk/retail-calendar](https://github.com/holonk/retail-calendar) in sync.**
>
> The two packages are one calendar in two languages. retail-calendar-api, holonk and the frontend use the JS
> package; toolio-ml uses this one. If they ever disagree, services disagree about which week a date belongs to. When
> you add a feature, fix a bug or change behavior in either repo:
> The two packages are one calendar in two languages. Systems that use both must agree on which week a date belongs
> to, so the packages must never disagree. When you add a feature, fix a bug or change behavior in either repo:
>
> 1. Make the same change in the other repo, in the same piece of work. Never fix a bug on one side only, even an
> obvious one such as the December-only `LAST_DAY_BEFORE_EOM_EXCEPT_LEAP_YEAR` look-ahead.
Expand All @@ -27,17 +26,27 @@ and retail-calendar-api, so tenant configurations can be used as they are.
> (see [Parity with the JS package](#parity-with-the-js-package)) and commit it with the Python change.
> `tests/test_golden.py` must pass against the regenerated data.
> 5. Update both READMEs, including the [JS to Python table](#coming-from-the-js-package) below.
> 6. Release both packages (see [Releasing](#releasing)).
>
> Python-only conveniences that don't change calendar results don't need a JS counterpart. If you're unsure whether
> a change affects results, it does: mirror it.
>
> Like the JS package, this library stays dependency-free. Integration helpers that need other libraries (pandas
> DataFrame conversions, database access, ...) belong in the consuming repo, such as toolio-ml, not here.
> DataFrame conversions, database access, ...) belong in the projects that use it, not here.

## Installation

Each release on GitHub has the wheel attached. Its release notes give the line to put in `requirements.txt`, with the
wheel's SHA-256 so pip rejects any other file:

```text
retail-calendar @ https://github.com/holonk/retail-calendar-python/releases/download/v1.0.0/retail_calendar-1.0.0-py3-none-any.whl#sha256=...
```

This needs no git and no build step. To install a release directly:

```shell
uv add "retail-calendar @ git+ssh://git@github.com/holonk/retail-calendar-python.git@v1.0.0"
pip install https://github.com/holonk/retail-calendar-python/releases/download/v1.0.0/retail_calendar-1.0.0-py3-none-any.whl
```

## Usage
Expand Down Expand Up @@ -90,7 +99,7 @@ day.date, day.day_of_year, day.day_of_week, day.day_of_month, day.week_of_year,

### Dates to retail weeks and back

These mirror retail-calendar-api's endpoints:
Conversions between dates and `(retail year, 0-based week)` segments:

```python
from retail_calendar import DateSegment, date_to_segment, leap_years, segment_to_date, week_of_gregorian_date
Expand All @@ -107,10 +116,11 @@ dt.date(2017, 3, 1) in calendar # True

`datetime` values (including `pandas.Timestamp`) are accepted wherever a date is; their time is ignored.

### Configuration from the database or the API
### Configuration from a dictionary

`RetailCalendarOptions.from_dict` accepts the JS package's keys as well as the `calendarconfiguration` /
retail-calendar-api keys, with integer or label values. Unrelated keys are ignored.
`RetailCalendarOptions.from_dict` accepts the JS package's keys as well as the alternative names used in stored
configurations and HTTP request bodies (`lastDayOfTheWeek`, `lastMonthOfTheYear`, `lastWeekCalculationMethod`), with
integer or label values. Unrelated keys are ignored.

```python
RetailCalendarOptions.from_dict(
Expand All @@ -125,9 +135,8 @@ RetailCalendarOptions.from_dict(
options.to_dict() # the JS package's camelCase shape
```

Only `Weekly` and `Daily` configurations describe a retail calendar. `Monthly` rows (`granularity = 'Monthly'`) have
no week grouping, week end day or week calculation method, so `from_dict` raises `ValueError` for them. Filter on
`granularity` before building options.
A configuration without a week grouping, week end day or week calculation method (a month-only calendar, for
example) does not describe a retail calendar, so `from_dict` raises `ValueError` for it.

## 53-week years

Expand Down Expand Up @@ -186,8 +195,7 @@ Differences in behavior:

- **No timezone effects.** The JS package does its date math in the host's local time, so DST shifts can move a year
boundary by a week, depending on where it runs: 9 to 54 of 21,420 tested calendars differ between UTC and other
zones. This package works on plain dates and always matches the JS package running in UTC, as retail-calendar-api
does.
zones. This package works on plain dates and always matches the JS package running in UTC.
- **Validation.** Invalid options (unknown labels, `add_leap_week_to_month` outside 0 to 11, missing custom leap year
options, unsupported years) raise `ValueError` when created instead of failing later or producing wrong calendars.
- **Immutability.** Calendars, weeks, months, days and options are frozen, so the cache can be shared safely.
Expand Down Expand Up @@ -230,3 +238,16 @@ npm run generate # runs in TZ=UTC
Some fixtures in `tests/data` are converted from the JS package's tests. The JS fixture for the "last day nearest
EOM, 4-4-5, arbitrary leap year" case had stray spaces in some dates (`"2024-01 -08"`), which its parser tolerated;
they are fixed here.

### Releasing

1. Bump `version` in `pyproject.toml` (`uv version --bump patch`, `minor` or `major`) and merge it to `master`.
2. Tag the merge commit and push the tag:

```shell
git tag v1.0.1 && git push origin v1.0.1
```

The release workflow runs CI, checks that the tag matches the version, builds the wheel and sdist and publishes them as
a GitHub Release. Its notes give the `requirements.txt` line with the wheel's SHA-256. A published version is never
rebuilt or replaced, since projects pin its hash.
6 changes: 3 additions & 3 deletions scripts/golden/generate.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
// cd scripts/golden && npm ci && npm run generate
//
// The JS package does its date math in the host's local time, so its output depends on the timezone (DST shifts
// can move a year boundary by a week). The reference is the package running in UTC, which is what
// retail-calendar-api runs in. This script refuses to run in any other timezone.
// can move a year boundary by a week). The reference is the package running in UTC, which is what the Python port
// matches. This script refuses to run in any other timezone.

import { mkdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
Expand Down Expand Up @@ -130,7 +130,7 @@ function digests(configs) {
writeGzip('digests.csv.gz', rows.join('\n') + '\n')
}

// 3. weekOfGregorianDate (what retail-calendar-api's get-date-segments-from-dates uses) on random dates.
// 3. weekOfGregorianDate on random dates.
function lookups(configs) {
let seed = 20261008 // deterministic linear congruential generator, so the output is reproducible
const random = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648)
Expand Down
11 changes: 5 additions & 6 deletions src/retail_calendar/enums.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
"""Calendar configuration enums.

Integer values are identical to the JS ``retail-calendar`` package, so configurations stored as integers (for example
in the ``calendarconfiguration`` table) are interchangeable between the two implementations. Each member also has a
:attr:`~_LabeledIntEnum.label`: the string used by the database and by retail-calendar-api (``"4-4-5"``,
``"Saturday"``, ...).
Integer values are identical to the JS ``retail-calendar`` package, so configurations stored as integers are
interchangeable between the two implementations. Each member also has a :attr:`~_LabeledIntEnum.label`: the string
form used in stored configurations (``"4-4-5"``, ``"Saturday"``, ...).
"""

from __future__ import annotations
Expand All @@ -17,7 +16,7 @@ class _LabeledIntEnum(IntEnum):

@property
def label(self) -> str:
"""The label used for this member by the database and retail-calendar-api."""
"""The string form of this member in stored configurations."""
return self.name.title()

@classmethod
Expand Down Expand Up @@ -125,7 +124,7 @@ class WeekCalculation(_LabeledIntEnum):

@property
def label(self) -> str:
"""The ``lastWeekCalculationMethod`` value of the database and retail-calendar-api."""
"""The string form of this member, as in a ``lastWeekCalculationMethod`` key."""
return _WEEK_CALCULATION_LABELS[self]


Expand Down
8 changes: 3 additions & 5 deletions src/retail_calendar/lookup.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
"""Conversions between Gregorian dates and retail weeks.

These mirror the retail-calendar-api endpoints:

* ``get-date-segments-from-dates`` -> :func:`date_to_segment`
* ``get-dates-from-date-segments`` -> :func:`segment_to_date`
* ``get-leap-years`` -> :func:`leap_years`
* :func:`date_to_segment`: the retail year and 0-based week containing a date
* :func:`segment_to_date`: the first day of a retail week
* :func:`leap_years`: the years with 53 weeks
"""

from __future__ import annotations
Expand Down
2 changes: 1 addition & 1 deletion src/retail_calendar/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def gregorian_day_of_year(self) -> int:

@dataclass(frozen=True, slots=True)
class DateSegment:
"""A retail week identified the way retail-calendar-api and toolio-ml do: retail year plus 0-based week."""
"""A retail week identified by its retail year and 0-based week of the year."""

year: int
week: int
10 changes: 5 additions & 5 deletions src/retail_calendar/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@

from retail_calendar.enums import LastDayOfWeek, LastMonthOfYear, WeekCalculation, WeekGrouping

# Each option accepts the key used by the JS package and the key used by the calendarconfiguration table and
# retail-calendar-api request bodies.
# Each option accepts the key used by the JS package and the alternative key used in stored configurations and
# HTTP request bodies.
_KEY_ALIASES: dict[str, tuple[str, ...]] = {
"week_grouping": ("weekGrouping", "week_grouping"),
"last_day_of_week": ("lastDayOfWeek", "lastDayOfTheWeek", "last_day_of_week"),
Expand Down Expand Up @@ -85,9 +85,9 @@ def _validate(self) -> None:
def from_dict(cls, data: Mapping[str, Any]) -> Self:
"""Build options from a camelCase mapping.

Accepts the keys of the JS package (``weekGrouping``, ``lastDayOfWeek``, ...) and of the
``calendarconfiguration`` table / retail-calendar-api (``lastDayOfTheWeek``, ``lastWeekCalculationMethod``,
...). Values may be enum members, integers or labels. ``None`` values fall back to the defaults, an
Accepts the keys of the JS package (``weekGrouping``, ``lastDayOfWeek``, ...) and the alternative keys used in
stored configurations and HTTP request bodies (``lastDayOfTheWeek``, ``lastWeekCalculationMethod``, ...).
Values may be enum members, integers or labels. ``None`` values fall back to the defaults, an
``addLeapWeekToMonth`` of ``-1`` means "no month", and unrelated keys are ignored.
"""
kwargs: dict[str, Any] = {}
Expand Down
2 changes: 1 addition & 1 deletion tests/test_lookup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Port of the JS package's ``__tests__/gregorian_helpers.test.ts``, plus the retail-calendar-api style helpers."""
"""Port of the JS package's ``__tests__/gregorian_helpers.test.ts``, plus the date and segment conversion helpers."""

from __future__ import annotations

Expand Down
2 changes: 1 addition & 1 deletion tests/test_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def test_js_package_shape(self) -> None:
data = {"weekGrouping": 2, "lastDayOfWeek": 6, "lastMonthOfYear": 0, "weekCalculation": 2}
assert RetailCalendarOptions.from_dict(data) == NRF_CALENDAR_OPTIONS

def test_calendarconfiguration_row_shape(self) -> None:
def test_stored_configuration_shape(self) -> None:
row = {
"id": 7,
"granularity": "Weekly",
Expand Down
Loading