Skip to content
This repository has been archived by the owner on Feb 5, 2024. It is now read-only.

Commit

Permalink
feat: add weekday to notion (#22)
Browse files Browse the repository at this point in the history
* feat: add weekday to notion

* chore: fix circular import

* fix: typo

* chore: fix test docker compose

* style: lint alembic migration

* ci: black and lint all code

* feat: add settings endpoint

* feat: add LOCALE_WEEKDAY_NAMES
  • Loading branch information
sralloza authored Nov 8, 2021
1 parent 5c53a85 commit 06a8c78
Show file tree
Hide file tree
Showing 8 changed files with 62 additions and 11 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/linter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ jobs:
run: poetry install

- name: Run black
run: poetry run black --check app
run: poetry run black --check .

- name: Check imports
run: poetry run isort --check app
run: poetry run isort --check .

- name: Lint with pylint
run: poetry run pylint app
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ You need to supply the following environment variables (required ones are marked
- 🚩 **MYSQL_PORT** (`str`): mysql port.
- 🚩 **MYSQL_USER** (`str`): mysql user.

### Other

- **LOCALE_WEEKDAY_NAMES** (`list(str)`): weekday names, starting with Sunday and ending with Saturday. Must contain 7 elements (one for each week day).

## Future

AWS and notion settings are currently needed. If you want to use this app without one of them (or both) add an issue and I'll make it optional and configurable.
Expand Down
1 change: 0 additions & 1 deletion alembic/versions/032390abe0c6_create_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

from alembic import op


# revision identifiers, used by Alembic.
revision = "032390abe0c6"
down_revision = "f2b0ccdc9f11"
Expand Down
7 changes: 7 additions & 0 deletions app/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from fastapi import APIRouter

from ..core.config import Settings, settings
from ..utils.misc import get_version
from ..utils.responses import Version

Expand All @@ -12,3 +13,9 @@
def get_version_endpoint():
"""Returns the current backend version."""
return Version(version=get_version())


@router.get("/settings", response_model=Settings, summary="Get settings")
def get_settings():
"""Returns the backend settings."""
return settings
21 changes: 20 additions & 1 deletion app/core/config.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
"""Config module."""

from typing import Any, Dict, Optional
import json
from typing import Any, Dict, List, Optional

from pydantic import UUID4, BaseSettings, validator


def list_parse_fallback(v):
try:
return json.loads(v)
except json.JSONDecodeError:
return v.split(",")


class Settings(BaseSettings):
# Server
API_TOKEN: str
Expand Down Expand Up @@ -36,6 +44,9 @@ class Settings(BaseSettings):
# Defined dinamically
DATABASE_URI: str = ""

# Other
LOCALE_WEEKDAY_NAMES: Optional[List[str]]

@validator("DATABASE_URI", pre=True)
def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
if isinstance(v, str):
Expand All @@ -46,9 +57,17 @@ def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any
f"{values.get('MYSQL_PORT')}/{values.get('MYSQL_DATABASE')}"
)

@validator("LOCALE_WEEKDAY_NAMES")
def check_locale_names(cls, v):
if isinstance(v, list):
if len(v) != 7:
raise ValueError("must have 7 elements (one for each week day)")
return v

class Config:
case_sensitive = True
env_file = ".env"
json_loads = list_parse_fallback


settings = Settings()
23 changes: 19 additions & 4 deletions app/cron/update_notion_meals.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Update notion meals cron sript."""

from datetime import datetime, timedelta

from .. import crud
from ..core.config import settings
from ..core.notion import create_notion_block, update_notion_text
Expand All @@ -8,6 +10,16 @@
from .base import scheduler


def get_weekday(delta_days: int = 0) -> str:
"""Return the weekday in words given a delta in days."""
date = datetime.now() + timedelta(days=delta_days)

if settings.LOCALE_WEEKDAY_NAMES:
return settings.LOCALE_WEEKDAY_NAMES[int(date.strftime("%w"))]

return date.strftime("%A")


# Should fire everyday at 05:00
@scheduler.scheduled_job("cron", id="update-notion-meals", hour="5", minute="0")
def update_notion_meals():
Expand All @@ -22,21 +34,24 @@ def update_notion_meals():
dat_meal = Meal.from_orm(dat_meal) if dat_meal else None

blocks = []
blocks.append(create_notion_block("Hoy\n", bold=True))
weekday = get_weekday(0)
blocks.append(create_notion_block(f"Hoy ({weekday})\n", bold=True))
if today_meal:
blocks.extend(today_meal.to_notion_blocks())

blocks.append(create_notion_block("\nMañana\n", bold=True))
weekday = get_weekday(1)
blocks.append(create_notion_block(f"\nMañana ({weekday})\n", bold=True))
if tomorrow_meal:
blocks.extend(tomorrow_meal.to_notion_blocks())

if settings.NOTION_ADD_DAY_AFTER_TOMORROW:
blocks.append(create_notion_block("\nPasado mañana\n", bold=True))
weekday = get_weekday(2)
blocks.append(create_notion_block(f"\nPasado mañana ({weekday})\n", bold=True))
if dat_meal:
blocks.extend(dat_meal.to_notion_blocks())

if len(blocks) <= 3:
print("warning: not blocks detected in cron-script update-notion-meals")
print("warning: no blocks detected in cron-script update-notion-meals")
return

update_notion_text(blocks)
11 changes: 9 additions & 2 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ services:
env_file:
- .env
environment:
- MYSQL_USER=root
- MYSQL_PASSWORD=root
- MYSQL_HOST=database
- MYSQL_PORT=3306
- MYSQL_DATABASE=meal-planner

# If you don't have this environment variables in your
# terminal, put them in the .env file
- AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
Expand All @@ -16,5 +22,6 @@ services:

database:
image: mysql:5.7
env_file:
- .env
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=meal-planner
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "meal-planner"
version = "1.4.0"
version = "1.5.0"
description = ""
authors = ["Diego Alloza González <[email protected]>"]
packages = [
Expand Down

0 comments on commit 06a8c78

Please sign in to comment.