Skip to content

API

Dependencies

Views

me(request)

The function me returns a user.

Endpoint
  • Path: /api/me
  • Method: GET

Parameters:

Name Type Description Default
request
required

Returns:

Type Description
UserSchema

Returns a user.

Source code in backend/backend/api.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
@api.get("/me", response=UserSchema)
def me(request):
    """
    The function `me` returns a user.

    Endpoint:
        - **Path**: `/api/me`
        - **Method**: `GET`

    Args:
        request ():

    Returns:
        (UserSchema): Returns a user.
    """
    return request.user

Schemas

UserSchema

Schema to validate a User

Attributes:

Name Type Description
username str

The user's username.

is_authenticated bool

Wether or not the use is authenticated.

email str

The user's email address.

first_name str

The user's first name.

last_name str

The user's last name.

Source code in backend/backend/api.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
class UserSchema(Schema):
    """
    Schema to validate a User

    Attributes:
        username (str): The user's username.
        is_authenticated (bool): Wether or not the use is authenticated.
        email (str): The user's email address.
        first_name (str): The user's first name.
        last_name (str): The user's last name.
    """

    username: str
    is_authenticated: bool
    email: str = None
    first_name: str = None
    last_name: str = None

Version

Views

list_version(request)

The function list_version retrieves the app version number from the backend.

Parameters:

Name Type Description Default
request HttpRequest

The HTTP request object.

required

Returns:

Type Description
VersionOut

a version object

Source code in backend/backend/api.py
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
@api.get("/version/list", response=VersionOut)
def list_version(request):
    """
    The function `list_version` retrieves the app version number
    from the backend.

    Args:
        request (HttpRequest): The HTTP request object.

    Returns:
        (VersionOut): a version object
    """

    return {"version_number": api.version}

Schemas

VersionOut

Schema to represent a Version.

Attributes:

Name Type Description
version_number str

The version of the app.

Source code in backend/backend/api.py
132
133
134
135
136
137
138
139
140
class VersionOut(Schema):
    """
    Schema to represent a Version.

    Attributes:
        version_number (str): The version of the app.
    """

    version_number: str

Aisle

Views

create_aisle(request, payload)

The function create_aisle creates an Aisle.

Endpoint
  • Path: /api/aisles
  • Method: POST

Parameters:

Name Type Description Default
request
required
payload AisleIn

An object using schema of AisleIn.

required

Returns:

Name Type Description
id int

returns the id of the created Aisle.

Source code in backend/backend/api.py
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
@api.post("/aisles")
def create_aisle(request, payload: AisleIn):
    """
    The function `create_aisle` creates an Aisle.

    Endpoint:
        - **Path**: `/api/aisles`
        - **Method**: `POST`

    Args:
        request ():
        payload (AisleIn): An object using schema of AisleIn.

    Returns:
        id (int): returns the id of the created Aisle.
    """
    aisle = Aisle.objects.create(**payload.dict())
    broadcast_invalidate(["aisles"])
    return {"id": aisle.id}

get_aisle(request, aisle_id)

The function get_aisle returns an Aisle.

Endpoint
  • Path: /api/aisles/{aisle_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
aisle_id int

An ID of an Aisle.

required

Returns:

Type Description
AisleOut

returns the Aisle object.

Source code in backend/backend/api.py
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
@api.get("/aisles/{aisle_id}", response=AisleOut)
def get_aisle(request, aisle_id: int):
    """
    The function `get_aisle` returns an Aisle.

    Endpoint:
        - **Path**: `/api/aisles/{aisle_id}`
        - **Method**: `GET`

    Args:
        request ():
        aisle_id (int): An ID of an Aisle.

    Returns:
        (AisleOut): returns the Aisle object.
    """
    aisle = get_object_or_404(Aisle, id=aisle_id)
    return aisle

list_aisles(request)

The function list_aisles returns a list of Aisles.

Endpoint
  • Path: /api/aisles
  • Method: GET

Parameters:

Name Type Description Default
request
required

Returns:

Type Description
List[AisleOut]

returns a list of Aisle objects.

Source code in backend/backend/api.py
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
@api.get("/aisles", response=List[AisleOut])
def list_aisles(request):
    """
    The function `list_aisles` returns a list of Aisles.

    Endpoint:
        - **Path**: `/api/aisles`
        - **Method**: `GET`

    Args:
        request ():

    Returns:
        (List[AisleOut]): returns a list of Aisle objects.
    """
    qs = Aisle.objects.all()
    return qs

list_aislesbystore(request, store_id)

The function list_aislesbystore returns a list of Aisles for a matching store ID.

Endpoint
  • Path: /api/aislesbystore/{store_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
store_id int

An ID of a Store.

required

Returns:

Type Description
List[AisleOut]

Returns a list of Aisles.

Source code in backend/backend/api.py
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
@api.get("/aislesbystore/{store_id}", response=List[AisleOut])
def list_aislesbystore(request, store_id: int):
    """
    The function `list_aislesbystore` returns a list of Aisles for a matching
    store ID.

    Endpoint:
        - **Path**: `/api/aislesbystore/{store_id}`
        - **Method**: `GET`

    Args:
        request ():
        store_id (int): An ID of a Store.

    Returns:
        (List[AisleOut]): Returns a list of Aisles.
    """
    qs = Aisle.objects.all().filter(store__id=store_id).order_by("order")
    return qs

update_aisle(request, aisle_id, payload)

The function update_aisle updates an Aisle

Endpoint
  • Path: /api/aisles/{aisle_id}
  • Method: PUT

Parameters:

Name Type Description Default
request
required
aisle_id int

The ID of an aisle object.

required
payload AisleIn

An Aisle object.

required

Returns:

Name Type Description
success bool

True if successfully updated.

Source code in backend/backend/api.py
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
@api.put("/aisles/{aisle_id}")
def update_aisle(request, aisle_id: int, payload: AisleIn):
    """
    The function `update_aisle` updates an Aisle

    Endpoint:
        - **Path**: `/api/aisles/{aisle_id}`
        - **Method**: `PUT`

    Args:
        request ():
        aisle_id (int): The ID of an aisle object.
        payload (AisleIn): An Aisle object.

    Returns:
        success (bool): True if successfully updated.
    """
    aisle = get_object_or_404(Aisle, id=aisle_id)
    aisle.name = payload.name
    aisle.order = payload.order
    aisle.store_id = payload.store_id
    aisle.save()
    broadcast_invalidate(["aisles"])
    return {"success": True}

delete_aisle(request, aisle_id)

The function delete_aisle deletes a given Aisle.

Endpoint
  • Path: /api/aisles/{aisle_id}
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
aisle_id int

ID of an Aisle to delete.

required

Returns:

Name Type Description
success bool

True if successfully deleted.

Source code in backend/backend/api.py
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
@api.delete("/aisles/{aisle_id}")
def delete_aisle(request, aisle_id: int):
    """
    The function `delete_aisle` deletes a given Aisle.

    Endpoint:
        - **Path**: `/api/aisles/{aisle_id}`
        - **Method**: `DELETE`

    Args:
        request ():
        aisle_id (int): ID of an Aisle to delete.

    Returns:
        success (bool): True if successfully deleted.
    """
    aisle = get_object_or_404(Aisle, id=aisle_id)
    aisle.delete()
    broadcast_invalidate(["aisles"])
    return {"success": True}

Schemas

AisleIn

Schema to validate an Aisle.

Attributes:

Name Type Description
name str

The name of the aisle.

order int

The order of the aisle. Default = 1.

store_id int

The ID of a Store object.

Source code in backend/backend/api.py
186
187
188
189
190
191
192
193
194
195
196
197
198
class AisleIn(Schema):
    """
    Schema to validate an Aisle.

    Attributes:
        name (str): The name of the aisle.
        order (int): The order of the aisle. Default = 1.
        store_id (int): The ID of a Store object.
    """

    name: str
    order: int = 1
    store_id: int

AisleOut

Schema to represent an Aisle.

Attributes:

Name Type Description
id int

ID integer. Unique.

name str

The name of the Aisle.

order int

The order of the Aisle. Default = 1.

store_id int

The ID of the store.

store StoreOut

The Store object.

Source code in backend/backend/api.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
class AisleOut(Schema):
    """
    Schema to represent an Aisle.

    Attributes:
        id (int): ID integer. Unique.
        name (str): The name of the Aisle.
        order (int): The order of the Aisle. Default = 1.
        store_id (int): The ID of the store.
        store (StoreOut): The Store object.
    """

    id: int
    name: str
    order: int = 1
    store_id: int
    store: StoreOut

AislesWithItems

Schema to represent an Aisle with ListItems assigned to it.

Attributes:

Name Type Description
id int

ID of the aisle.

name str

The name of the aisle.

order int

The order of the aisle.

store_id int

The id of the store this aisle is in.

listitems List[ListItemOut]

A list of list items in this aisle.

Source code in backend/backend/api.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
class AislesWithItems(Schema):
    """
    Schema to represent an Aisle with ListItems assigned to it.

    Attributes:
        id (int): ID of the aisle.
        name (str): The name of the aisle.
        order (int): The order of the aisle.
        store_id (int): The id of the store this aisle is in.
        listitems (List[ListItemOut]): A list of list items in this aisle.
    """

    id: int
    name: str
    order: int = 1
    store_id: int
    listitems: List[ListItemOut]

Store

Views

create_store(request, payload)

The function create_store creates a Store.

Endpoint
  • Path: /api/stores
  • Method: POST

Parameters:

Name Type Description Default
request
required
payload StoreIn

A Store object to add.

required

Returns:

Name Type Description
id int

The ID of the added Store.

Source code in backend/backend/api.py
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
@api.post("/stores")
def create_store(request, payload: StoreIn):
    """
    The function `create_store` creates a Store.

    Endpoint:
        - **Path**: `/api/stores`
        - **Method**: `POST`

    Args:
        request ():
        payload (StoreIn): A Store object to add.

    Returns:
        id (int): The ID of the added Store.
    """
    store = Store.objects.create(**payload.dict())
    broadcast_invalidate(["stores"])
    return {"id": store.id}

get_store(request, store_id)

The function get_store returns a Store object for a given ID.

Endpoint
  • Path: /api/stores/{store_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
store_id int

ID of a Store to retreive.

required

Returns:

Type Description
StoreOut

A Store object.

Source code in backend/backend/api.py
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
@api.get("/stores/{store_id}", response=StoreOut)
def get_store(request, store_id: int):
    """
    The function `get_store` returns a Store object for a given ID.

    Endpoint:
        - **Path**: `/api/stores/{store_id}`
        - **Method**: `GET`

    Args:
        request ():
        store_id (int): ID of a Store to retreive.

    Returns:
        (StoreOut): A Store object.
    """
    store = get_object_or_404(Store, id=store_id)
    return store

list_stores(request)

The function list_stores returns a list of Stores.

Endpoint
  • Path: /api/stores
  • Method: GET

Parameters:

Name Type Description Default
request
required

Returns:

Type Description
List[StoreOut]

A list of Store objects.

Source code in backend/backend/api.py
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
@api.get("/stores", response=List[StoreOut])
def list_stores(request):
    """
    The function `list_stores` returns a list of Stores.

    Endpoint:
        - **Path**: `/api/stores`
        - **Method**: `GET`

    Args:
        request ():

    Returns:
        (List[StoreOut]): A list of Store objects.
    """
    qs = Store.objects.all()
    return qs

update_store(request, store_id, payload)

The function update_store updates a give Store.

Endpoint
  • Path: /api/stores/{store_id}
  • Method: PUT

Parameters:

Name Type Description Default
request
required
store_id int

ID of a Store to update.

required
payload StoreIn

A Store object with updates.

required

Returns:

Name Type Description
success bool

True if successfully updated.

Source code in backend/backend/api.py
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
@api.put("/stores/{store_id}")
def update_store(request, store_id: int, payload: StoreIn):
    """
    The function `update_store` updates a give Store.

    Endpoint:
        - **Path**: `/api/stores/{store_id}`
        - **Method**: `PUT`

    Args:
        request ():
        store_id (int): ID of a Store to update.
        payload (StoreIn): A Store object with updates.

    Returns:
        success (bool): True if successfully updated.
    """
    store = get_object_or_404(Store, id=store_id)
    store.name = payload.name
    store.save()
    broadcast_invalidate(["stores"])
    return {"success": True}

delete_store(request, store_id)

The function delete_store deletes a given Store.

Endpoint
  • Path: /api/stores/{store_id}
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
store_id int

ID of a Store to delete.

required

Returns:

Name Type Description
success bool

True if successfully deleted.

Source code in backend/backend/api.py
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
@api.delete("/stores/{store_id}")
def delete_store(request, store_id: int):
    """
    The function `delete_store` deletes a given Store.

    Endpoint:
        - **Path**: `/api/stores/{store_id}`
        - **Method**: `DELETE`

    Args:
        request ():
        store_id (int): ID of a Store to delete.

    Returns:
        success (bool): True if successfully deleted.
    """
    store = get_object_or_404(Store, id=store_id)
    store.delete()
    broadcast_invalidate(["stores"])
    return {"success": True}

Schemas

StoreIn

Schema to validate a Store.

Attributes:

Name Type Description
name str

The name of the store.

Source code in backend/backend/api.py
162
163
164
165
166
167
168
169
170
class StoreIn(Schema):
    """
    Schema to validate a Store.

    Attributes:
        name (str): The name of the store.
    """

    name: str

StoreOut

Schema to represent a Store.

Attributes:

Name Type Description
id int

ID integer. Unique.

name str

The name of the store.

Source code in backend/backend/api.py
173
174
175
176
177
178
179
180
181
182
183
class StoreOut(Schema):
    """
    Schema to represent a Store.

    Attributes:
        id (int): ID integer. Unique.
        name (str): The name of the store.
    """

    id: int
    name: str

Item

Views

create_item(request, payload)

The function create_item creates an Item.

Endpoint
  • Path: /api/items
  • Method: POST

Parameters:

Name Type Description Default
request
required
payload ItemIn

An object using schema of ItemIn.

required

Returns:

Name Type Description
id int

returns the id of the created Item.

Source code in backend/backend/api.py
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
@api.post("/items", response=ItemOut)
def create_item(request, payload: ItemIn):
    """
    The function `create_item` creates an Item.

    Endpoint:
        - **Path**: `/api/items`
        - **Method**: `POST`

    Args:
        request ():
        payload (ItemIn): An object using schema of ItemIn.

    Returns:
        id (int): returns the id of the created Item.
    """
    item = Item.objects.create(**payload.dict())
    broadcast_invalidate(["items"])
    return item

get_item(request, item_id)

The function get_item returns an Item.

Endpoint
  • Path: /api/items/{item_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
item_id int

The ID of an Item.

required

Returns:

Type Description
ItemOut

returns an Item object.

Source code in backend/backend/api.py
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
@api.get("/items/{item_id}", response=ItemOut)
def get_item(request, item_id: int):
    """
    The function `get_item` returns an Item.

    Endpoint:
        - **Path**: `/api/items/{item_id}`
        - **Method**: `GET`

    Args:
        request ():
        item_id (int): The ID of an Item.

    Returns:
        (ItemOut): returns an Item object.
    """
    item = get_object_or_404(Item, id=item_id)
    return item

list_items(request, page=Query(1), page_size=Query(15), full=Query(False))

The function list_items returns a paginated list of Items.

Endpoint
  • Path: /api/items
  • Method: GET

Parameters:

Name Type Description Default
request
required
page int

The page number to return. Optional. Default = 1.

Query(1)
page_size int

Hoe many items per page. Optional. Default = 15.

Query(15)
full bool

Wehter this is a full request or not. Optional. Default = False.

Query(False)

Returns:

Type Description
PaginatedItems

returns a PaginatedItems object.

Source code in backend/backend/api.py
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
@api.get("/items", response=PaginatedItems)
def list_items(
    request,
    page: Optional[int] = Query(1),
    page_size: Optional[int] = Query(15),
    full: Optional[bool] = Query(False),
):
    """
    The function `list_items` returns a paginated list of Items.

    Endpoint:
        - **Path**: `/api/items`
        - **Method**: `GET`

    Args:
        request ():
        page (int): The page number to return. Optional. Default = 1.
        page_size (int): Hoe many items per page. Optional. Default = 15.
        full (bool): Wehter this is a full request or not. Optional. Default = False.

    Returns:
        (PaginatedItems): returns a PaginatedItems object.
    """
    qs = Item.objects.all().order_by("name")
    total_pages = 0
    item_list = []
    if not full:
        if len(qs) > 0:
            paginator = Paginator(qs, page_size)
            page_obj = paginator.page(page)
            item_list = list(page_obj.object_list)
            total_pages = paginator.num_pages
    else:
        item_list = list(qs)
    total_records = len(qs)
    paginated_items = PaginatedItems(
        items=item_list,
        current_page=page,
        total_pages=total_pages,
        total_records=total_records,
    )
    return paginated_items

update_item(request, item_id, payload)

The function update_item updates an Item.

Endpoint
  • Path: /api/items/{item_id}
  • Method: PUT

Parameters:

Name Type Description Default
request
required
item_id int

ID of the item to update.

required
payload ItemIn

An Item object with updates.

required

Returns:

Name Type Description
success bool

True if successfully updated.

Source code in backend/backend/api.py
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
@api.put("/items/{item_id}")
def update_item(request, item_id: int, payload: ItemIn):
    """
    The function `update_item` updates an Item.

    Endpoint:
        - **Path**: `/api/items/{item_id}`
        - **Method**: `PUT`

    Args:
        request ():
        item_id (int): ID of the item to update.
        payload (ItemIn): An Item object with updates.

    Returns:
        success (bool): True if successfully updated.
    """
    item = get_object_or_404(Item, id=item_id)
    item.name = payload.name
    item.matches = payload.matches
    item.save()
    broadcast_invalidate(["items"])
    return {"success": True}

delete_item(request, item_id)

The function delete_item deletes a given Item.

Endpoint
  • Path: /api/items/{item_id}
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
item_id int

ID of an Item to delete.

required

Returns:

Name Type Description
success bool

True if successfully deleted.

Source code in backend/backend/api.py
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
@api.delete("/items/{item_id}")
def delete_item(request, item_id: int):
    """
    The function `delete_item` deletes a given Item.

    Endpoint:
        - **Path**: `/api/items/{item_id}`
        - **Method**: `DELETE`

    Args:
        request ():
        item_id (int): ID of an Item to delete.

    Returns:
        success (bool): True if successfully deleted.
    """
    item = get_object_or_404(Item, id=item_id)
    item.delete()
    broadcast_invalidate(["items"])
    return {"success": True}

upload_item_image(request, item_id, image=File(...))

The function upload_item_image sets the photo for an Item, replacing any photo already on it.

Endpoint
  • Path: /api/items/{item_id}/image
  • Method: POST

Parameters:

Name Type Description Default
request
required
item_id int

ID of the Item to attach the photo to.

required
image UploadedFile

The uploaded photo, as multipart form data.

File(...)

Returns:

Type Description
ItemOut

The Item, with its new image paths.

Source code in backend/backend/api.py
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
@api.post("/items/{item_id}/image", response=ItemOut)
def upload_item_image(request, item_id: int, image: UploadedFile = File(...)):
    """
    The function `upload_item_image` sets the photo for an Item, replacing any
    photo already on it.

    Endpoint:
        - **Path**: `/api/items/{item_id}/image`
        - **Method**: `POST`

    Args:
        request ():
        item_id (int): ID of the Item to attach the photo to.
        image (UploadedFile): The uploaded photo, as multipart form data.

    Returns:
        (ItemOut): The Item, with its new image paths.
    """
    item = get_object_or_404(Item, id=item_id)
    item = store_upload(item, image)
    broadcast_invalidate(ITEM_IMAGE_KEYS)
    return item

delete_item_image(request, item_id)

The function delete_item_image removes the photo from an Item.

Endpoint
  • Path: /api/items/{item_id}/image
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
item_id int

ID of the Item to remove the photo from.

required

Returns:

Type Description
ItemOut

The Item, with its image paths cleared.

Source code in backend/backend/api.py
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
@api.delete("/items/{item_id}/image", response=ItemOut)
def delete_item_image(request, item_id: int):
    """
    The function `delete_item_image` removes the photo from an Item.

    Endpoint:
        - **Path**: `/api/items/{item_id}/image`
        - **Method**: `DELETE`

    Args:
        request ():
        item_id (int): ID of the Item to remove the photo from.

    Returns:
        (ItemOut): The Item, with its image paths cleared.
    """
    item = get_object_or_404(Item, id=item_id)
    item = clear_upload(item)
    broadcast_invalidate(ITEM_IMAGE_KEYS)
    return item

Schemas

ItemIn

Schema to validate an Item.

Attributes:

Name Type Description
name str

The name of the item.

matches str

Names that match this item.

aisle AisleOut

Last aisle used for this item.

Source code in backend/backend/api.py
220
221
222
223
224
225
226
227
228
229
230
231
232
class ItemIn(Schema):
    """
    Schema to validate an Item.

    Attributes:
        name (str): The name of the item.
        matches (str): Names that match this item.
        aisle (AisleOut): Last aisle used for this item.
    """

    name: str
    matches: str = None
    aisle: Optional[AisleOut]

ItemOut

Schema to represent an Item.

Attributes:

Name Type Description
id int

ID integer. Unique.

name str

The name of the item.

matches str

Names that macth this item.

aisle AisleOut

Last aisle used for this item. Optional.

image_url str

Path to the full photo, for tap-to-enlarge. None when the item has no photo.

thumbnail_url str

Path to the thumbnail shown on rows. None when the item has no photo.

Source code in backend/backend/api.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
class ItemOut(Schema):
    """
    Schema to represent an Item.

    Attributes:
        id (int): ID integer. Unique.
        name (str): The name of the item.
        matches (str): Names that macth this item.
        aisle (AisleOut): Last aisle used for this item. Optional.
        image_url (str): Path to the full photo, for tap-to-enlarge. None when
            the item has no photo.
        thumbnail_url (str): Path to the thumbnail shown on rows. None when the
            item has no photo.
    """

    id: int
    name: str
    matches: str = None
    aisle: Optional[AisleOut]
    image_url: str = None
    thumbnail_url: str = None

    @staticmethod
    def resolve_image_url(obj):
        """
        Returns:
            (str): The media path of the full photo, or None.
        """
        return image_path(obj.image)

    @staticmethod
    def resolve_thumbnail_url(obj):
        """
        Returns:
            (str): The media path of the thumbnail, or None.
        """
        return image_path(obj.thumbnail)

PaginatedItems

Schema to represent a paginated list of Items.

Attributes:

Name Type Description
items List[ItemOut]

A paginated list of items.

current_page int

The current page of the list.

total_pages int

The total number of pages of items.

total_records int

The total count of items.

Source code in backend/backend/api.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
class PaginatedItems(Schema):
    """
    Schema to represent a paginated list of Items.

    Attributes:
        items (List[ItemOut]): A paginated list of items.
        current_page (int): The current page of the list.
        total_pages (int): The total number of pages of items.
        total_records (int): The total count of items.
    """

    items: List[ItemOut]
    current_page: int
    total_pages: int
    total_records: int

ListItem

Views

create_listitem(request, payload)

The function create_listitem creates a ListItem.

Endpoint
  • Path: /api/listitems
  • Method: POST

Parameters:

Name Type Description Default
request
required
payload ListItemIn

An object using schema of ListItemIn.

required

Returns:

Name Type Description
id int

returns the id of the created ListItem.

Source code in backend/backend/api.py
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
@api.post("/listitems")
def create_listitem(request, payload: ListItemIn):
    """
    The function `create_listitem` creates a ListItem.

    Endpoint:
        - **Path**: `/api/listitems`
        - **Method**: `POST`

    Args:
        request ():
        payload (ListItemIn): An object using schema of ListItemIn.

    Returns:
        id (int): returns the id of the created ListItem.
    """
    # Only an item still to be found is a candidate to merge into. Adding
    # something you have already put in the cart means you need more of it, so
    # it starts a new line rather than reopening the old one — otherwise the
    # quantities add together and the row silently reverts to unpurchased,
    # which reads as the app forgetting you bought it.
    existing_item = ListItem.objects.filter(
        shopping_list_id=payload.shopping_list_id,
        item_id=payload.item_id,
        purchased=False,
    ).first()
    if existing_item is None:
        listitem = ListItem.objects.create(**payload.dict())
        item = Item.objects.get(id=payload.item_id)
        item.aisle_id = payload.aisle_id
        item.save()
        broadcast_invalidate(["fullshoppinglist", "shoppinglists"])
        return {"id": listitem.id}
    else:
        existing_item.qty += payload.qty
        existing_item.save()
        broadcast_invalidate(["fullshoppinglist", "shoppinglists"])
        return {"id": existing_item.id}

get_listitem(request, listitem_id)

The function get_listitem returns a ListItem

Endpoint
  • Path: /api/listitems/{listitem_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
listitem_id int

The ID of a ListItem.

required

Returns:

Type Description
ListItemOut

returns a ListItem object.

Source code in backend/backend/api.py
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
@api.get("/listitems/{listitem_id}", response=ListItemOut)
def get_listitem(request, listitem_id: int):
    """
    The function `get_listitem` returns a ListItem

    Endpoint:
        - **Path**: `/api/listitems/{listitem_id}`
        - **Method**: `GET`

    Args:
        request ():
        listitem_id (int): The ID of a ListItem.

    Returns:
        (ListItemOut): returns a ListItem object.
    """
    listitem = get_object_or_404(ListItem, id=listitem_id)
    return listitem

list_listitems(request)

The function list_listitems returns a list of ListItems.

Endpoint
  • Path: /api/listitems
  • Method: GET

Parameters:

Name Type Description Default
request
required

Returns:

Type Description
List[ListItemOut]

Returns a list of ListItem objects.

Source code in backend/backend/api.py
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
@api.get("/listitems", response=List[ListItemOut])
def list_listitems(request):
    """
    The function `list_listitems` returns a list of ListItems.

    Endpoint:
        - **Path**: `/api/listitems`
        - **Method**: `GET`

    Args:
        request ():

    Returns:
        (List[ListItemOut]): Returns a list of ListItem objects.
    """
    qs = ListItem.objects.all()
    return qs

update_listitem(request, listitem_id, payload)

The function update_listitem updates a ListItem.

Endpoint
  • Path: /api/listitems/{listitem_id}
  • Method: PUT

Parameters:

Name Type Description Default
request
required
listitem_id int

The ID of a ListItem to update.

required
payload ListItemIn

A ListItem object with updates.

required

Returns:

Name Type Description
success bool

True if successfully updated.

Source code in backend/backend/api.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
@api.put("/listitems/{listitem_id}")
def update_listitem(request, listitem_id: int, payload: ListItemIn):
    """
    The function `update_listitem` updates a ListItem.

    Endpoint:
        - **Path**: `/api/listitems/{listitem_id}`
        - **Method**: `PUT`

    Args:
        request ():
        listitem_id (int): The ID of a ListItem to update.
        payload (ListItemIn): A ListItem object with updates.

    Returns:
        success (bool): True if successfully updated.
    """
    listitem = get_object_or_404(ListItem, id=listitem_id)
    listitem.qty = payload.qty
    listitem.purchased = payload.purchased
    listitem.notes = payload.notes
    listitem.purch_date = payload.purch_date
    listitem.item_id = payload.item_id
    listitem.aisle_id = payload.aisle_id
    listitem.shopping_list_id = payload.shopping_list_id
    listitem.save()
    # Ticking off a row that was split out from a bought one puts both in the
    # cart; unticking does the same in reverse. Either way they fold back into
    # a single line. A no-op unless a genuine duplicate exists, so editing the
    # notes or quantity of an ordinary row is unaffected.
    merge_duplicate_listitem(listitem)
    broadcast_invalidate(["fullshoppinglist", "shoppinglists"])
    return {"success": True}

delete_listitem(request, listitem_id)

The function delete_listitem deletes a given ListItem.

Endpoint
  • Path: /api/listitems/{listitem_id}
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
listitem_id int

ID of an ListItem to delete.

required

Returns:

Name Type Description
success bool

True if successfully deleted.

Source code in backend/backend/api.py
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
@api.delete("/listitems/{listitem_id}")
def delete_listitem(request, listitem_id: int):
    """
    The function `delete_listitem` deletes a given ListItem.

    Endpoint:
        - **Path**: `/api/listitems/{listitem_id}`
        - **Method**: `DELETE`

    Args:
        request ():
        listitem_id (int): ID of an ListItem to delete.

    Returns:
        success (bool): True if successfully deleted.
    """
    listitem = get_object_or_404(ListItem, id=listitem_id)
    listitem.delete()
    broadcast_invalidate(["fullshoppinglist", "shoppinglists"])
    return {"success": True}

delete_listitems_by_shoppinglist(request, shoppinglist_id)

The function delete_listitems_by_shoppinglist deletes all ListItems for a given ShoppingList ID.

Endpoint
  • Path: /api/listitems/deleteall/{shoppinglist_id}
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
shoppinglist_id int

ID of a ShoppingList.

required

Returns:

Name Type Description
success bool

True if successfully deleted.

Source code in backend/backend/api.py
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
@api.delete("/listitems/deleteall/{shoppinglist_id}")
def delete_listitems_by_shoppinglist(request, shoppinglist_id: int):
    """
    The function `delete_listitems_by_shoppinglist` deletes all ListItems for
    a given ShoppingList ID.

    Endpoint:
        - **Path**: `/api/listitems/deleteall/{shoppinglist_id}`
        - **Method**: `DELETE`

    Args:
        request ():
        shoppinglist_id (int): ID of a ShoppingList.

    Returns:
        success (bool): True if successfully deleted.
    """
    listitems = ListItem.objects.filter(shopping_list_id=shoppinglist_id)
    listitems.delete()
    broadcast_invalidate(["fullshoppinglist", "shoppinglists"])
    return {"success": True}

delete_purchased_listitems_by_shoppinglist(request, shoppinglist_id)

The function delete_purchased_listitems_by_shoppinglist deletes all ListItems markded as purchased on a given ShoppingList.

Endpoint
  • Path: /api/listitems/deletepurchased/{shoppinglist_id}
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
shoppinglist_id int

ID of a ShoppingList.

required

Returns:

Name Type Description
success bool

True if successfully deleted.

Source code in backend/backend/api.py
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
@api.delete("/listitems/deletepurchased/{shoppinglist_id}")
def delete_purchased_listitems_by_shoppinglist(request, shoppinglist_id: int):
    """
    The function `delete_purchased_listitems_by_shoppinglist` deletes all ListItems
    markded as purchased on a given ShoppingList.

    Endpoint:
        - **Path**: `/api/listitems/deletepurchased/{shoppinglist_id}`
        - **Method**: `DELETE`

    Args:
        request ():
        shoppinglist_id (int): ID of a ShoppingList.

    Returns:
        success (bool): True if successfully deleted.
    """
    listitems = ListItem.objects.filter(
        shopping_list_id=shoppinglist_id, purchased=True
    )
    listitems.delete()
    broadcast_invalidate(["fullshoppinglist", "shoppinglists"])
    return {"success": True}

Schemas

ListItemIn

Schema to validate a ListItem.

Attributes:

Name Type Description
qty int

The quantity of list items. Default = 1.

purchased bool

Wether the list item has been purchsaed. Default = False.

notes str

Notes for the list item. Default = None.

purch_date date

Last aisle used for this item. Default = None.

item_id int

ID of the item.

aisle_id int

ID of the aisle.

shopping_list_id int

ID of the shopping list.

Source code in backend/backend/api.py
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
class ListItemIn(Schema):
    """
    Schema to validate a ListItem.

    Attributes:
        qty (int): The quantity of list items. Default = 1.
        purchased (bool): Wether the list item has been purchsaed. Default = False.
        notes (str): Notes for the list item. Default = None.
        purch_date (date): Last aisle used for this item. Default = None.
        item_id (int): ID of the item.
        aisle_id (int): ID of the aisle.
        shopping_list_id (int): ID of the shopping list.
    """

    qty: int = 1
    purchased: bool = False
    notes: str = None
    purch_date: date = None
    item_id: int
    aisle_id: int
    shopping_list_id: int

ListItemOut

Schema to represent a ListItem.

Attributes:

Name Type Description
id int

The ID of the list item.

qty int

The quantity of list items. Default = 1.

purchased bool

Wether the list item has been purchsaed. Default = False.

notes str

Notes for the list item. Default = None.

purch_date date

Last aisle used for this item. Default = None.

item_id int

ID of the item.

aisle_id int

ID of the aisle.

shopping_list_id int

ID of the shopping list.

item ItemOut

Object representing the item for the list item.

Source code in backend/backend/api.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
class ListItemOut(Schema):
    """
    Schema to represent a ListItem.

    Attributes:
        id (int): The ID of the list item.
        qty (int): The quantity of list items. Default = 1.
        purchased (bool): Wether the list item has been purchsaed. Default = False.
        notes (str): Notes for the list item. Default = None.
        purch_date (date): Last aisle used for this item. Default = None.
        item_id (int): ID of the item.
        aisle_id (int): ID of the aisle.
        shopping_list_id (int): ID of the shopping list.
        item (ItemOut): Object representing the item for the list item.
    """

    id: int
    qty: int = 1
    purchased: bool = False
    notes: str = None
    purch_date: date = None
    item_id: int
    aisle_id: int
    shopping_list_id: int
    item: ItemOut

Shopping List

Views

create_shoppinglist(request, payload)

The function create_shoppinglist creates a ShoppingList.

Endpoint
  • Path: /api/shoppinglists
  • Method: POST

Parameters:

Name Type Description Default
request
required
payload ShoppingListIn

An object using schema of ShoppingListIn.

required

Returns:

Name Type Description
id int

returns the id of the created ShoppingList.

Source code in backend/backend/api.py
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
@api.post("/shoppinglists")
def create_shoppinglist(request, payload: ShoppingListIn):
    """
    The function `create_shoppinglist` creates a ShoppingList.

    Endpoint:
        - **Path**: `/api/shoppinglists`
        - **Method**: `POST`

    Args:
        request ():
        payload (ShoppingListIn): An object using schema of ShoppingListIn.

    Returns:
        id (int): returns the id of the created ShoppingList.
    """
    shoppinglist = ShoppingList.objects.create(**payload.dict())
    broadcast_invalidate(["shoppinglists"])
    return {"id": shoppinglist.id}

get_shoppinglist(request, shoppinglist_id)

The function get_shoppinglist returns a ShoppingList.

Endpoint
  • Path: /api/shoppinglists/{shoppinglist_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
shoppinglist_id int

An ID of a ShoppingList.

required

Returns:

Type Description
ShoppingListOut

returns a ShoppingList object.

Source code in backend/backend/api.py
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
@api.get("/shoppinglists/{shoppinglist_id}", response=ShoppingListOut)
def get_shoppinglist(request, shoppinglist_id: int):
    """
    The function `get_shoppinglist` returns a ShoppingList.

    Endpoint:
        - **Path**: `/api/shoppinglists/{shoppinglist_id}`
        - **Method**: `GET`

    Args:
        request ():
        shoppinglist_id (int): An ID of a ShoppingList.

    Returns:
        (ShoppingListOut): returns a ShoppingList object.
    """
    shoppinglist = get_object_or_404(shoppinglist_queryset(), id=shoppinglist_id)
    return shoppinglist

get_shoppinglistfull(request, shoppinglist_id)

The function get_shoppinglistfull returns a ShoppingList with aisles and items.

Endpoint
  • Path: /api/shoppinglistfull/{shoppinglist_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
shoppinglist_id int

The ID of a ShoppingList.

required

Returns:

Type Description
ShoppingListFull

returns a ShoppingListFull object.

Source code in backend/backend/api.py
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
@api.get("/shoppinglistfull/{shoppinglist_id}", response=ShoppingListFull)
def get_shoppinglistfull(request, shoppinglist_id: int):
    """
    The function `get_shoppinglistfull` returns a ShoppingList with aisles and items.

    Endpoint:
        - **Path**: `/api/shoppinglistfull/{shoppinglist_id}`
        - **Method**: `GET`

    Args:
        request ():
        shoppinglist_id (int): The ID of a ShoppingList.

    Returns:
        (ShoppingListFull): returns a ShoppingListFull object.
    """
    shoppinglist = get_object_or_404(ShoppingList, id=shoppinglist_id)
    store = shoppinglist.store
    aisles = Aisle.objects.filter(
        store=store,
        listitem__shopping_list=shoppinglist,
        listitem__purchased=False,
    ).order_by("order", "name")
    purchasedaisles = Aisle.objects.filter(
        store=store,
        listitem__shopping_list=shoppinglist,
        listitem__purchased=True,
    ).order_by("order", "name")
    aisles_dict = {
        aisle.id: AislesWithItems(
            id=aisle.id,
            name=aisle.name,
            order=aisle.order,
            store_id=store.id,
            listitems=[],
        )
        for aisle in aisles
    }
    purchased_aisles_dict = {
        aisle.id: AislesWithItems(
            id=aisle.id,
            name=aisle.name,
            order=aisle.order,
            store_id=store.id,
            listitems=[],
        )
        for aisle in purchasedaisles
    }
    # select_related because every row below reads listitem.item and
    # listitem.aisle; without it a full list costs two extra queries per row.
    listitems = (
        ListItem.objects.filter(shopping_list=shoppinglist, purchased=False)
        .select_related("item", "aisle")
        .order_by("purchased", "item__name")
    )
    purchasedlistitems = (
        ListItem.objects.filter(shopping_list=shoppinglist, purchased=True)
        .select_related("item", "aisle")
        .order_by("purchased", "item__name")
    )
    total_purchased_count = ListItem.objects.filter(
        shopping_list=shoppinglist, purchased=True
    ).count()
    total_items_count = (
        ListItem.objects.filter(shopping_list=shoppinglist)
        .order_by("purchased", "item__name")
        .count()
    )

    for listitem in listitems:
        aisles_dict[listitem.aisle.id].listitems.append(
            ListItemOut(
                id=listitem.id,
                qty=listitem.qty,
                purchased=listitem.purchased,
                notes=listitem.notes,
                purch_date=listitem.purch_date,
                item_id=listitem.item.id,
                aisle_id=listitem.aisle_id,
                shopping_list_id=listitem.shopping_list.id,
                # Built by hand rather than from_orm so the item's aisle is left
                # off: it is redundant here (the row already sits under an aisle)
                # and resolving it would cost two queries per row. The image
                # paths have to be passed explicitly for the same reason — the
                # ItemOut resolvers only run under from_orm.
                item=ItemOut(
                    id=listitem.item.id,
                    name=listitem.item.name,
                    matches=listitem.item.matches,
                    image_url=image_path(listitem.item.image),
                    thumbnail_url=image_path(listitem.item.thumbnail),
                ),
            )
        )

    for listitem in purchasedlistitems:
        purchased_aisles_dict[listitem.aisle.id].listitems.append(
            ListItemOut(
                id=listitem.id,
                qty=listitem.qty,
                purchased=listitem.purchased,
                notes=listitem.notes,
                purch_date=listitem.purch_date,
                item_id=listitem.item.id,
                aisle_id=listitem.aisle_id,
                shopping_list_id=listitem.shopping_list.id,
                # Built by hand rather than from_orm so the item's aisle is left
                # off: it is redundant here (the row already sits under an aisle)
                # and resolving it would cost two queries per row. The image
                # paths have to be passed explicitly for the same reason — the
                # ItemOut resolvers only run under from_orm.
                item=ItemOut(
                    id=listitem.item.id,
                    name=listitem.item.name,
                    matches=listitem.item.matches,
                    image_url=image_path(listitem.item.image),
                    thumbnail_url=image_path(listitem.item.thumbnail),
                ),
            )
        )

    response_data = ShoppingListFull(
        id=shoppinglist.id,
        name=shoppinglist.name,
        store_id=store.id,
        store=StoreOut(id=store.id, name=store.name),
        aisles=list(aisles_dict.values()),
        purchased_aisles=list(purchased_aisles_dict.values()),
        totalitems=total_items_count,
        totalpurchased=total_purchased_count,
    )
    return response_data

list_shoppinglists(request)

The function list_shoppinglists returns a list of ShoppingLists.

Endpoint
  • Path: /api/shoppinglists
  • Method: GET

Parameters:

Name Type Description Default
request
required

Returns:

Type Description
List[ShoppingListOut]

Returns a list of ShoppingList objects.

Source code in backend/backend/api.py
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
@api.get("/shoppinglists", response=List[ShoppingListOut])
def list_shoppinglists(request):
    """
    The function `list_shoppinglists` returns a list of ShoppingLists.

    Endpoint:
        - **Path**: `/api/shoppinglists`
        - **Method**: `GET`

    Args:
        request ():

    Returns:
        (List[ShoppingListOut]): Returns a list of ShoppingList objects.
    """
    qs = shoppinglist_queryset().order_by("store__name", "name")
    return qs

list_listsbystore(request, store_id)

The function list_listsbystore returns a list of ShoppingLists for a given Store ID.

Endpoint
  • Path: /api/listsbystore/{store_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
store_id int

The ID of a Store.

required

Returns:

Type Description
List[ShoppingListOut]

Returns a list of ShoppingList objects.

Source code in backend/backend/api.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
@api.get("/listsbystore/{store_id}", response=List[ShoppingListOut])
def list_listsbystore(request, store_id: int):
    """
    The function `list_listsbystore` returns a list of ShoppingLists for a given
    Store ID.

    Endpoint:
        - **Path**: `/api/listsbystore/{store_id}`
        - **Method**: `GET`

    Args:
        request ():
        store_id (int): The ID of a Store.

    Returns:
        (List[ShoppingListOut]): Returns a list of ShoppingList objects.
    """
    qs = shoppinglist_queryset().filter(store__id=store_id).order_by("name")
    return qs

update_shoppinglist(request, shoppinglist_id, payload)

The function update_shoppinglist updates a given ShoppingList.

Endpoint
  • Path: /api/shoppinglists/{shoppinglist_id}
  • Method: PUT

Parameters:

Name Type Description Default
request
required
shoppinglist_id int

ID of the Shoppinglist to update.

required
payload ShoppingListIn

A ShoppingList object with updates.

required

Returns:

Name Type Description
success bpp;

True if successfully updated.

Source code in backend/backend/api.py
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
@api.put("/shoppinglists/{shoppinglist_id}")
def update_shoppinglist(request, shoppinglist_id: int, payload: ShoppingListIn):
    """
    The function `update_shoppinglist` updates a given ShoppingList.

    Endpoint:
        - **Path**: `/api/shoppinglists/{shoppinglist_id}`
        - **Method**: `PUT`

    Args:
        request ():
        shoppinglist_id (int): ID of the Shoppinglist to update.
        payload (ShoppingListIn): A ShoppingList object with updates.

    Returns:
        success (bpp;): True if successfully updated.
    """
    shoppinglist = get_object_or_404(ShoppingList, id=shoppinglist_id)
    shoppinglist.name = payload.name
    shoppinglist.store_id = payload.store_id
    shoppinglist.save()
    broadcast_invalidate(["shoppinglists"])
    return {"success": True}

delete_shoppinglist(request, shoppinglist_id)

The function delete_shoppinglist deletes a given ShoppingList.

Endpoint
  • Path: /api/shoppinglists/{shoppinglist_id}
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
shoppinglist_id int

ID of a ShoppingList to delete.

required

Returns:

Name Type Description
success bool

True if successfully deleted.

Source code in backend/backend/api.py
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
@api.delete("/shoppinglists/{shoppinglist_id}")
def delete_shoppinglist(request, shoppinglist_id: int):
    """
    The function `delete_shoppinglist` deletes a given ShoppingList.

    Endpoint:
        - **Path**: `/api/shoppinglists/{shoppinglist_id}`
        - **Method**: `DELETE`

    Args:
        request ():
        shoppinglist_id (int): ID of a ShoppingList to delete.

    Returns:
        success (bool): True if successfully deleted.
    """
    shoppinglist = get_object_or_404(ShoppingList, id=shoppinglist_id)
    shoppinglist.delete()
    broadcast_invalidate(["shoppinglists"])
    return {"success": True}

Schemas

ShoppingListIn

Schema to validate a ShoppingList.

Attributes:

Name Type Description
name str

The name of the shopping list.

store_id int

The ID of the store for the shopping list.

Source code in backend/backend/api.py
341
342
343
344
345
346
347
348
349
350
351
class ShoppingListIn(Schema):
    """
    Schema to validate a ShoppingList.

    Attributes:
        name (str): The name of the shopping list.
        store_id (int): The ID of the store for the shopping list.
    """

    name: str
    store_id: int

ShoppingListOut

Schema to represent a ShoppingList.

Attributes:

Name Type Description
id int

ID of the shopping list.

name str

The name of the shopping list.

store_id int

The ID of the store for the shopping list.

store StoreOut

The Store object.

totalitems int

The total number of items on the shopping list.

totalpurchased int

The number of items marked purchased.

preview_items List[ListPreviewItem]

The first few items, unpurchased first, for previewing the list without fetching it in full.

Source code in backend/backend/api.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
class ShoppingListOut(Schema):
    """
    Schema to represent a ShoppingList.

    Attributes:
        id (int): ID of the shopping list.
        name (str): The name of the shopping list.
        store_id (int): The ID of the store for the shopping list.
        store (StoreOut): The Store object.
        totalitems (int): The total number of items on the shopping list.
        totalpurchased (int): The number of items marked purchased.
        preview_items (List[ListPreviewItem]): The first few items, unpurchased first,
            for previewing the list without fetching it in full.
    """

    id: int
    name: str
    store_id: int
    store: StoreOut
    totalitems: int = 0
    totalpurchased: int = 0
    preview_items: List[ListPreviewItem] = []

    @staticmethod
    def resolve_preview_items(obj):
        """
        Returns the first few list items, already ordered unpurchased-first by the
        prefetch in `shoppinglist_queryset`. Falls back to an empty list when the
        object was not loaded through that queryset.
        """
        listitems = getattr(obj, "listitem_set", None)
        if listitems is None:
            return []
        return [
            ListPreviewItem(name=listitem.item.name, purchased=listitem.purchased)
            for listitem in listitems.all()[:LIST_PREVIEW_ITEM_COUNT]
        ]

ShoppingListFull

Schema to represent a ShoppingList with ListItems assigned to it.

Attributes:

Name Type Description
id int

ID of the shopping list.

name str

The name of the shopping list.

store_id int

The ID of the store for this shopping list.

store StoreOut

The Store object.

aisles List[AislesWithItems]

A list of aisles with listitems assigned.

purchased_aisles List[AislesWithItems]

A list of aisles with listitems marked as purchased.

totalitems int

The total number of items on the shopping list.

totalpurchased int

The total number of items marked purchased on the shopping list.

Source code in backend/backend/api.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
class ShoppingListFull(Schema):
    """
    Schema to represent a ShoppingList with ListItems assigned to it.

    Attributes:
        id (int): ID of the shopping list.
        name (str): The name of the shopping list.
        store_id (int): The ID of the store for this shopping list.
        store (StoreOut): The Store object.
        aisles (List[AislesWithItems]): A list of aisles with listitems assigned.
        purchased_aisles (List[AislesWithItems]): A list of aisles with listitems marked as
            purchased.
        totalitems (int): The total number of items on the shopping list.
        totalpurchased (int): The total number of items marked purchased on the shopping list.
    """

    id: int
    name: str
    store_id: int
    store: StoreOut
    aisles: List[AislesWithItems]
    purchased_aisles: List[AislesWithItems]
    totalitems: int
    totalpurchased: int

Freezer

Views

create_freezer(request, payload)

The function create_freezer creates a Freezer.

Endpoint
  • Path: /api/freezers
  • Method: POST

Parameters:

Name Type Description Default
request
required
payload FreezerIn

A Freezer object to add.

required

Returns:

Name Type Description
id int

The ID of the added Freezer.

Source code in backend/backend/api.py
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
@api.post("/freezers")
def create_freezer(request, payload: FreezerIn):
    """
    The function `create_freezer` creates a Freezer.

    Endpoint:
        - **Path**: `/api/freezers`
        - **Method**: `POST`

    Args:
        request ():
        payload (FreezerIn): A Freezer object to add.

    Returns:
        id (int): The ID of the added Freezer.
    """
    freezer = Freezer.objects.create(**payload.dict())
    broadcast_invalidate(["freezers"])
    return {"id": freezer.id}

get_freezer(request, freezer_id)

The function get_freezer returns a Freezer object for a given ID.

Endpoint
  • Path: /api/freezers/{freezer_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
freezer_id int

ID of a Freezer to retreive.

required

Returns:

Type Description
FreezerOut

A Freezer object.

Source code in backend/backend/api.py
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
@api.get("/freezers/{freezer_id}", response=FreezerOut)
def get_freezer(request, freezer_id: int):
    """
    The function `get_freezer` returns a Freezer object for a given ID.

    Endpoint:
        - **Path**: `/api/freezers/{freezer_id}`
        - **Method**: `GET`

    Args:
        request ():
        freezer_id (int): ID of a Freezer to retreive.

    Returns:
        (FreezerOut): A Freezer object.
    """
    freezer = get_object_or_404(freezer_queryset(), id=freezer_id)
    return freezer

get_freezerfull(request, freezer_id)

The function get_freezerfull returns a Freezer with its frozen foods.

Items are ordered so the ones closest to their discard date come first, with undated items last.

Endpoint
  • Path: /api/freezerfull/{freezer_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
freezer_id int

The ID of a Freezer.

required

Returns:

Type Description
FreezerFull

A FreezerFull object.

Source code in backend/backend/api.py
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
@api.get("/freezerfull/{freezer_id}", response=FreezerFull)
def get_freezerfull(request, freezer_id: int):
    """
    The function `get_freezerfull` returns a Freezer with its frozen foods.

    Items are ordered so the ones closest to their discard date come first,
    with undated items last.

    Endpoint:
        - **Path**: `/api/freezerfull/{freezer_id}`
        - **Method**: `GET`

    Args:
        request ():
        freezer_id (int): The ID of a Freezer.

    Returns:
        (FreezerFull): A FreezerFull object.
    """
    freezer = get_object_or_404(Freezer, id=freezer_id)
    freezeritems = FreezerItem.objects.filter(freezer=freezer).order_by(
        F("discard_date").asc(nulls_last=True), "name"
    )
    totalexpired = FreezerItem.objects.filter(
        freezer=freezer, discard_date__lt=date.today()
    ).count()
    return FreezerFull(
        id=freezer.id,
        name=freezer.name,
        location=freezer.location,
        freezeritems=[FreezerItemOut.from_orm(fi) for fi in freezeritems],
        totalitems=freezeritems.count(),
        totalexpired=totalexpired,
    )

list_freezers(request)

The function list_freezers returns a list of Freezers.

Endpoint
  • Path: /api/freezers
  • Method: GET

Parameters:

Name Type Description Default
request
required

Returns:

Type Description
List[FreezerOut]

A list of Freezer objects.

Source code in backend/backend/api.py
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
@api.get("/freezers", response=List[FreezerOut])
def list_freezers(request):
    """
    The function `list_freezers` returns a list of Freezers.

    Endpoint:
        - **Path**: `/api/freezers`
        - **Method**: `GET`

    Args:
        request ():

    Returns:
        (List[FreezerOut]): A list of Freezer objects.
    """
    qs = freezer_queryset().order_by("name")
    return qs

update_freezer(request, freezer_id, payload)

The function update_freezer updates a given Freezer.

Endpoint
  • Path: /api/freezers/{freezer_id}
  • Method: PUT

Parameters:

Name Type Description Default
request
required
freezer_id int

ID of a Freezer to update.

required
payload FreezerIn

A Freezer object with updates.

required

Returns:

Name Type Description
success bool

True if successfully updated.

Source code in backend/backend/api.py
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
@api.put("/freezers/{freezer_id}")
def update_freezer(request, freezer_id: int, payload: FreezerIn):
    """
    The function `update_freezer` updates a given Freezer.

    Endpoint:
        - **Path**: `/api/freezers/{freezer_id}`
        - **Method**: `PUT`

    Args:
        request ():
        freezer_id (int): ID of a Freezer to update.
        payload (FreezerIn): A Freezer object with updates.

    Returns:
        success (bool): True if successfully updated.
    """
    freezer = get_object_or_404(Freezer, id=freezer_id)
    freezer.name = payload.name
    freezer.location = payload.location
    freezer.save()
    broadcast_invalidate(["freezers", "freezerfull"])
    return {"success": True}

delete_freezer(request, freezer_id)

The function delete_freezer deletes a given Freezer and everything in it.

Endpoint
  • Path: /api/freezers/{freezer_id}
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
freezer_id int

ID of a Freezer to delete.

required

Returns:

Name Type Description
success bool

True if successfully deleted.

Source code in backend/backend/api.py
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
@api.delete("/freezers/{freezer_id}")
def delete_freezer(request, freezer_id: int):
    """
    The function `delete_freezer` deletes a given Freezer and everything in it.

    Endpoint:
        - **Path**: `/api/freezers/{freezer_id}`
        - **Method**: `DELETE`

    Args:
        request ():
        freezer_id (int): ID of a Freezer to delete.

    Returns:
        success (bool): True if successfully deleted.
    """
    freezer = get_object_or_404(Freezer, id=freezer_id)
    freezer.delete()
    broadcast_invalidate(["freezers", "freezeritems", "freezerfull"])
    return {"success": True}

Schemas

FreezerIn

Schema to validate a Freezer.

Attributes:

Name Type Description
name str

The name of the freezer.

location str

Where the freezer is. Default = None.

Source code in backend/backend/api.py
451
452
453
454
455
456
457
458
459
460
461
class FreezerIn(Schema):
    """
    Schema to validate a Freezer.

    Attributes:
        name (str): The name of the freezer.
        location (str): Where the freezer is. Default = None.
    """

    name: str
    location: str = None

FreezerOut

Schema to represent a Freezer.

Attributes:

Name Type Description
id int

ID integer. Unique.

name str

The name of the freezer.

location str

Where the freezer is. Default = None.

totalitems int

The total number of frozen foods in this freezer.

totalexpired int

How many are already past their discard date.

totalexpiring int

How many reach their discard date within FREEZER_SOON_DAYS days, not counting the ones already past it.

preview_items List[FreezerPreviewItem]

The items closest to their discard date, for previewing the freezer without fetching it whole.

Source code in backend/backend/api.py
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
class FreezerOut(Schema):
    """
    Schema to represent a Freezer.

    Attributes:
        id (int): ID integer. Unique.
        name (str): The name of the freezer.
        location (str): Where the freezer is. Default = None.
        totalitems (int): The total number of frozen foods in this freezer.
        totalexpired (int): How many are already past their discard date.
        totalexpiring (int): How many reach their discard date within
            FREEZER_SOON_DAYS days, not counting the ones already past it.
        preview_items (List[FreezerPreviewItem]): The items closest to their
            discard date, for previewing the freezer without fetching it whole.
    """

    id: int
    name: str
    location: str = None
    totalitems: int = 0
    totalexpired: int = 0
    totalexpiring: int = 0
    preview_items: List[FreezerPreviewItem] = []

    @staticmethod
    def resolve_preview_items(obj):
        """
        Returns the items closest to their discard date, already ordered by the
        prefetch in `freezer_queryset`. Falls back to an empty list when the
        object was not loaded through that queryset.
        """
        freezeritems = getattr(obj, "freezeritem_set", None)
        if freezeritems is None:
            return []
        return [
            FreezerPreviewItem(
                name=freezeritem.name,
                days_until_discard=freezeritem.days_until_discard,
                is_expired=freezeritem.is_expired,
            )
            for freezeritem in freezeritems.all()[:FREEZER_PREVIEW_ITEM_COUNT]
        ]

FreezerFull

Schema to represent a Freezer with the FreezerItems stored in it.

Attributes:

Name Type Description
id int

ID of the freezer.

name str

The name of the freezer.

location str

Where the freezer is. Default = None.

freezeritems List[FreezerItemOut]

The frozen foods in this freezer.

totalitems int

The total number of frozen foods in this freezer.

totalexpired int

How many of those are past their discard date.

Source code in backend/backend/api.py
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
class FreezerFull(Schema):
    """
    Schema to represent a Freezer with the FreezerItems stored in it.

    Attributes:
        id (int): ID of the freezer.
        name (str): The name of the freezer.
        location (str): Where the freezer is. Default = None.
        freezeritems (List[FreezerItemOut]): The frozen foods in this freezer.
        totalitems (int): The total number of frozen foods in this freezer.
        totalexpired (int): How many of those are past their discard date.
    """

    id: int
    name: str
    location: str = None
    freezeritems: List[FreezerItemOut]
    totalitems: int
    totalexpired: int

FreezerItem

Views

create_freezeritem(request, payload)

The function create_freezeritem creates a FreezerItem.

Endpoint
  • Path: /api/freezeritems
  • Method: POST

Parameters:

Name Type Description Default
request
required
payload FreezerItemIn

A FreezerItem object to add.

required

Returns:

Name Type Description
id int

The ID of the added FreezerItem.

Source code in backend/backend/api.py
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
@api.post("/freezeritems")
def create_freezeritem(request, payload: FreezerItemIn):
    """
    The function `create_freezeritem` creates a FreezerItem.

    Endpoint:
        - **Path**: `/api/freezeritems`
        - **Method**: `POST`

    Args:
        request ():
        payload (FreezerItemIn): A FreezerItem object to add.

    Returns:
        id (int): The ID of the added FreezerItem.
    """
    freezeritem = FreezerItem.objects.create(**payload.dict())
    FreezerLog.record(FreezerLog.ACTION_ADDED, freezeritem)
    # "freezers" too: the freezer list carries the dashboard's item and expiry
    # counts, so they go stale whenever an item is added, changed or removed.
    broadcast_invalidate(
        ["freezers", "freezeritems", "freezerfull", "freezerlog"]
    )
    return {"id": freezeritem.id}

get_freezeritem(request, freezeritem_id)

The function get_freezeritem returns a FreezerItem for a given ID.

Endpoint
  • Path: /api/freezeritems/{freezeritem_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
freezeritem_id int

ID of a FreezerItem to retreive.

required

Returns:

Type Description
FreezerItemOut

A FreezerItem object.

Source code in backend/backend/api.py
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
@api.get("/freezeritems/{freezeritem_id}", response=FreezerItemOut)
def get_freezeritem(request, freezeritem_id: int):
    """
    The function `get_freezeritem` returns a FreezerItem for a given ID.

    Endpoint:
        - **Path**: `/api/freezeritems/{freezeritem_id}`
        - **Method**: `GET`

    Args:
        request ():
        freezeritem_id (int): ID of a FreezerItem to retreive.

    Returns:
        (FreezerItemOut): A FreezerItem object.
    """
    freezeritem = get_object_or_404(FreezerItem, id=freezeritem_id)
    return freezeritem

list_freezeritems(request)

The function list_freezeritems returns a list of all FreezerItems.

Endpoint
  • Path: /api/freezeritems
  • Method: GET

Parameters:

Name Type Description Default
request
required

Returns:

Type Description
List[FreezerItemOut]

A list of FreezerItem objects.

Source code in backend/backend/api.py
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
@api.get("/freezeritems", response=List[FreezerItemOut])
def list_freezeritems(request):
    """
    The function `list_freezeritems` returns a list of all FreezerItems.

    Endpoint:
        - **Path**: `/api/freezeritems`
        - **Method**: `GET`

    Args:
        request ():

    Returns:
        (List[FreezerItemOut]): A list of FreezerItem objects.
    """
    qs = FreezerItem.objects.all().order_by(
        F("discard_date").asc(nulls_last=True), "name"
    )
    return qs

list_freezeritemsbyfreezer(request, freezer_id)

The function list_freezeritemsbyfreezer returns the FreezerItems in a given Freezer.

Endpoint
  • Path: /api/freezeritemsbyfreezer/{freezer_id}
  • Method: GET

Parameters:

Name Type Description Default
request
required
freezer_id int

ID of the Freezer to list frozen foods for.

required

Returns:

Type Description
List[FreezerItemOut]

A list of FreezerItem objects.

Source code in backend/backend/api.py
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
@api.get("/freezeritemsbyfreezer/{freezer_id}", response=List[FreezerItemOut])
def list_freezeritemsbyfreezer(request, freezer_id: int):
    """
    The function `list_freezeritemsbyfreezer` returns the FreezerItems in a
    given Freezer.

    Endpoint:
        - **Path**: `/api/freezeritemsbyfreezer/{freezer_id}`
        - **Method**: `GET`

    Args:
        request ():
        freezer_id (int): ID of the Freezer to list frozen foods for.

    Returns:
        (List[FreezerItemOut]): A list of FreezerItem objects.
    """
    qs = FreezerItem.objects.filter(freezer_id=freezer_id).order_by(
        F("discard_date").asc(nulls_last=True), "name"
    )
    return qs

list_freezeritemsexpiring(request, days=FREEZER_SOON_DAYS)

The function list_freezeritemsexpiring returns FreezerItems that are already past their discard date or reach it within days days.

Endpoint
  • Path: /api/freezeritemsexpiring
  • Method: GET

Parameters:

Name Type Description Default
request
required
days int

How many days ahead to look. Default = 14.

FREEZER_SOON_DAYS

Returns:

Type Description
List[FreezerItemOut]

A list of FreezerItem objects.

Source code in backend/backend/api.py
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
@api.get("/freezeritemsexpiring", response=List[FreezerItemOut])
def list_freezeritemsexpiring(request, days: int = FREEZER_SOON_DAYS):
    """
    The function `list_freezeritemsexpiring` returns FreezerItems that are
    already past their discard date or reach it within `days` days.

    Endpoint:
        - **Path**: `/api/freezeritemsexpiring`
        - **Method**: `GET`

    Args:
        request ():
        days (int): How many days ahead to look. Default = 14.

    Returns:
        (List[FreezerItemOut]): A list of FreezerItem objects.
    """
    cutoff = date.today() + timedelta(days=days)
    qs = FreezerItem.objects.filter(
        discard_date__isnull=False, discard_date__lte=cutoff
    ).order_by("discard_date", "name")
    return qs

update_freezeritem(request, freezeritem_id, payload)

The function update_freezeritem updates a given FreezerItem.

Endpoint
  • Path: /api/freezeritems/{freezeritem_id}
  • Method: PUT

Parameters:

Name Type Description Default
request
required
freezeritem_id int

ID of a FreezerItem to update.

required
payload FreezerItemIn

A FreezerItem object with updates.

required

Returns:

Name Type Description
success bool

True if successfully updated.

Source code in backend/backend/api.py
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
@api.put("/freezeritems/{freezeritem_id}")
def update_freezeritem(request, freezeritem_id: int, payload: FreezerItemIn):
    """
    The function `update_freezeritem` updates a given FreezerItem.

    Endpoint:
        - **Path**: `/api/freezeritems/{freezeritem_id}`
        - **Method**: `PUT`

    Args:
        request ():
        freezeritem_id (int): ID of a FreezerItem to update.
        payload (FreezerItemIn): A FreezerItem object with updates.

    Returns:
        success (bool): True if successfully updated.
    """
    freezeritem = get_object_or_404(FreezerItem, id=freezeritem_id)
    freezeritem.name = payload.name
    freezeritem.qty = payload.qty
    freezeritem.unit = payload.unit
    # Assigned unconditionally: None is a meaningful value here ("date added
    # unknown"), so clearing the field has to be possible.
    freezeritem.date_added = payload.date_added
    freezeritem.discard_date = payload.discard_date
    freezeritem.notes = payload.notes
    freezeritem.freezer_id = payload.freezer_id
    freezeritem.save()
    # "freezers" too: the freezer list carries the dashboard's item and expiry
    # counts, so they go stale whenever an item is added, changed or removed.
    broadcast_invalidate(["freezers", "freezeritems", "freezerfull"])
    return {"success": True}

use_freezeritem(request, freezeritem_id, payload)

The function use_freezeritem takes some of a FreezerItem out of the freezer, removing the row once none are left.

The decrement-or-delete decision is made here rather than in the frontend so it stays atomic: a client that read qty, subtracted and then chose between PUT and DELETE can strand a row at qty 0 if the two calls straddle another edit.

Endpoint
  • Path: /api/freezeritems/{freezeritem_id}/use
  • Method: POST

Parameters:

Name Type Description Default
request
required
freezeritem_id int

ID of the FreezerItem being used.

required
payload FreezerItemUseIn

How many to use.

required

Returns:

Type Description
FreezerItemChangeOut

What happened to the row.

Raises:

Type Description
HttpError

400 if the quantity is not positive or exceeds what is actually in the freezer.

Source code in backend/backend/api.py
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
@api.post("/freezeritems/{freezeritem_id}/use", response=FreezerItemChangeOut)
def use_freezeritem(request, freezeritem_id: int, payload: FreezerItemUseIn):
    """
    The function `use_freezeritem` takes some of a FreezerItem out of the
    freezer, removing the row once none are left.

    The decrement-or-delete decision is made here rather than in the frontend so
    it stays atomic: a client that read qty, subtracted and then chose between
    PUT and DELETE can strand a row at qty 0 if the two calls straddle another
    edit.

    Endpoint:
        - **Path**: `/api/freezeritems/{freezeritem_id}/use`
        - **Method**: `POST`

    Args:
        request ():
        freezeritem_id (int): ID of the FreezerItem being used.
        payload (FreezerItemUseIn): How many to use.

    Returns:
        (FreezerItemChangeOut): What happened to the row.

    Raises:
        HttpError: 400 if the quantity is not positive or exceeds what is
            actually in the freezer.
    """
    freezeritem = get_object_or_404(FreezerItem, id=freezeritem_id)
    if payload.qty < 1:
        raise HttpError(400, "Quantity to use must be at least 1.")
    if payload.qty > freezeritem.qty:
        # Deliberately an error rather than a clamp. Being asked to use more
        # than exists means the client is working from a stale count, and
        # quietly emptying the row would hide that.
        raise HttpError(
            400,
            f"Only {freezeritem.qty} of {freezeritem.name} in the freezer.",
        )

    remaining = freezeritem.qty - payload.qty
    # Written before the delete below, so the entry still catches the FK.
    FreezerLog.record(FreezerLog.ACTION_USED, freezeritem, qty=payload.qty)
    if remaining == 0:
        freezeritem.delete()
        result = FreezerItemChangeOut(removed=True, remaining=0)
    else:
        freezeritem.qty = remaining
        freezeritem.save()
        result = FreezerItemChangeOut(
            removed=False,
            remaining=remaining,
            item=FreezerItemOut.from_orm(freezeritem),
        )

    # "freezers" too: the freezer list carries the dashboard's item and expiry
    # counts, so they go stale whenever an item is added, changed or removed.
    broadcast_invalidate(
        ["freezers", "freezeritems", "freezerfull", "freezerlog"]
    )
    return result

transfer_freezeritem(request, freezeritem_id, payload)

The function transfer_freezeritem moves a FreezerItem, or part of one, to another freezer.

Moving the whole quantity relocates the existing row so its photo and history follow it. Moving part of it splits off a new row on the target and decrements the source. The split row shares the source's photo rather than copying the file — see _still_referenced in api/images.py for the guard that stops one row's deletion from blanking the other's picture.

A matching name already in the target freezer is left alone rather than merged into: two batches of the same food usually have different discard dates, and merging would have to silently discard one of them.

Endpoint
  • Path: /api/freezeritems/{freezeritem_id}/transfer
  • Method: POST

Parameters:

Name Type Description Default
request
required
freezeritem_id int

ID of the FreezerItem being moved.

required
payload FreezerItemTransferIn

Where to move it, and how many.

required

Returns:

Type Description
FreezerItemChangeOut

What happened to the row.

Raises:

Type Description
HttpError

400 if the quantity is not positive, exceeds what is in the freezer, or the target freezer is the one it is already in.

Source code in backend/backend/api.py
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
@api.post(
    "/freezeritems/{freezeritem_id}/transfer", response=FreezerItemChangeOut
)
def transfer_freezeritem(
    request, freezeritem_id: int, payload: FreezerItemTransferIn
):
    """
    The function `transfer_freezeritem` moves a FreezerItem, or part of one, to
    another freezer.

    Moving the whole quantity relocates the existing row so its photo and
    history follow it. Moving part of it splits off a new row on the target and
    decrements the source. The split row **shares** the source's photo rather
    than copying the file — see `_still_referenced` in `api/images.py` for the
    guard that stops one row's deletion from blanking the other's picture.

    A matching name already in the target freezer is left alone rather than
    merged into: two batches of the same food usually have different discard
    dates, and merging would have to silently discard one of them.

    Endpoint:
        - **Path**: `/api/freezeritems/{freezeritem_id}/transfer`
        - **Method**: `POST`

    Args:
        request ():
        freezeritem_id (int): ID of the FreezerItem being moved.
        payload (FreezerItemTransferIn): Where to move it, and how many.

    Returns:
        (FreezerItemChangeOut): What happened to the row.

    Raises:
        HttpError: 400 if the quantity is not positive, exceeds what is in the
            freezer, or the target freezer is the one it is already in.
    """
    freezeritem = get_object_or_404(FreezerItem, id=freezeritem_id)
    target = get_object_or_404(Freezer, id=payload.freezer_id)

    if target.id == freezeritem.freezer_id:
        raise HttpError(400, f"{freezeritem.name} is already in {target.name}.")

    # None means "all of them", which is the common case and saves the caller
    # having to read the count back first.
    qty = freezeritem.qty if payload.qty is None else payload.qty
    if qty < 1:
        raise HttpError(400, "Quantity to transfer must be at least 1.")
    if qty > freezeritem.qty:
        raise HttpError(
            400,
            f"Only {freezeritem.qty} of {freezeritem.name} in the freezer.",
        )

    # Captured before the move reassigns it, so the entry names where the food
    # came from rather than where it ended up.
    source = freezeritem.freezer
    FreezerLog.record(
        FreezerLog.ACTION_MOVED,
        freezeritem,
        qty=qty,
        freezer=source,
        to_freezer=target,
    )

    if qty == freezeritem.qty:
        freezeritem.freezer = target
        freezeritem.save()
        result = FreezerItemChangeOut(
            removed=False,
            remaining=freezeritem.qty,
            item=FreezerItemOut.from_orm(freezeritem),
        )
    else:
        with transaction.atomic():
            created = FreezerItem.objects.create(
                name=freezeritem.name,
                qty=qty,
                unit=freezeritem.unit,
                date_added=freezeritem.date_added,
                discard_date=freezeritem.discard_date,
                notes=freezeritem.notes,
                freezer=target,
                # Same file, not a copy: it is the same food, and duplicating
                # the bytes on every split would grow the media volume for no
                # benefit.
                image=freezeritem.image.name or "",
                thumbnail=freezeritem.thumbnail.name or "",
            )
            freezeritem.qty -= qty
            freezeritem.save()
        result = FreezerItemChangeOut(
            removed=False,
            remaining=freezeritem.qty,
            item=FreezerItemOut.from_orm(freezeritem),
            created=FreezerItemOut.from_orm(created),
        )

    # "freezers" too: the freezer list carries the dashboard's item and expiry
    # counts, so they go stale whenever an item is added, changed or removed.
    broadcast_invalidate(
        ["freezers", "freezeritems", "freezerfull", "freezerlog"]
    )
    return result

delete_freezeritem(request, freezeritem_id)

The function delete_freezeritem deletes a given FreezerItem.

Endpoint
  • Path: /api/freezeritems/{freezeritem_id}
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
freezeritem_id int

ID of a FreezerItem to delete.

required

Returns:

Name Type Description
success bool

True if successfully deleted.

Source code in backend/backend/api.py
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
@api.delete("/freezeritems/{freezeritem_id}")
def delete_freezeritem(request, freezeritem_id: int):
    """
    The function `delete_freezeritem` deletes a given FreezerItem.

    Endpoint:
        - **Path**: `/api/freezeritems/{freezeritem_id}`
        - **Method**: `DELETE`

    Args:
        request ():
        freezeritem_id (int): ID of a FreezerItem to delete.

    Returns:
        success (bool): True if successfully deleted.
    """
    freezeritem = get_object_or_404(FreezerItem, id=freezeritem_id)
    # Removing food through the app means it was thrown out — using it has its
    # own endpoint now, so this path no longer carries both meanings.
    FreezerLog.record(FreezerLog.ACTION_DISCARDED, freezeritem)
    freezeritem.delete()
    # "freezers" too: the freezer list carries the dashboard's item and expiry
    # counts, so they go stale whenever an item is added, changed or removed.
    broadcast_invalidate(
        ["freezers", "freezeritems", "freezerfull", "freezerlog"]
    )
    return {"success": True}

upload_freezeritem_image(request, freezeritem_id, image=File(...))

The function upload_freezeritem_image sets the photo for a FreezerItem, replacing any photo already on it.

Endpoint
  • Path: /api/freezeritems/{freezeritem_id}/image
  • Method: POST

Parameters:

Name Type Description Default
request
required
freezeritem_id int

ID of the FreezerItem to attach the photo to.

required
image UploadedFile

The uploaded photo, as multipart form data.

File(...)

Returns:

Type Description
FreezerItemOut

The FreezerItem, with its new image paths.

Source code in backend/backend/api.py
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
@api.post("/freezeritems/{freezeritem_id}/image", response=FreezerItemOut)
def upload_freezeritem_image(
    request, freezeritem_id: int, image: UploadedFile = File(...)
):
    """
    The function `upload_freezeritem_image` sets the photo for a FreezerItem,
    replacing any photo already on it.

    Endpoint:
        - **Path**: `/api/freezeritems/{freezeritem_id}/image`
        - **Method**: `POST`

    Args:
        request ():
        freezeritem_id (int): ID of the FreezerItem to attach the photo to.
        image (UploadedFile): The uploaded photo, as multipart form data.

    Returns:
        (FreezerItemOut): The FreezerItem, with its new image paths.
    """
    freezeritem = get_object_or_404(FreezerItem, id=freezeritem_id)
    freezeritem = store_upload(freezeritem, image)
    broadcast_invalidate(FREEZERITEM_IMAGE_KEYS)
    return freezeritem

delete_freezeritem_image(request, freezeritem_id)

The function delete_freezeritem_image removes the photo from a FreezerItem.

Endpoint
  • Path: /api/freezeritems/{freezeritem_id}/image
  • Method: DELETE

Parameters:

Name Type Description Default
request
required
freezeritem_id int

ID of the FreezerItem to remove the photo from.

required

Returns:

Type Description
FreezerItemOut

The FreezerItem, with its image paths cleared.

Source code in backend/backend/api.py
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
@api.delete("/freezeritems/{freezeritem_id}/image", response=FreezerItemOut)
def delete_freezeritem_image(request, freezeritem_id: int):
    """
    The function `delete_freezeritem_image` removes the photo from a
    FreezerItem.

    Endpoint:
        - **Path**: `/api/freezeritems/{freezeritem_id}/image`
        - **Method**: `DELETE`

    Args:
        request ():
        freezeritem_id (int): ID of the FreezerItem to remove the photo from.

    Returns:
        (FreezerItemOut): The FreezerItem, with its image paths cleared.
    """
    freezeritem = get_object_or_404(FreezerItem, id=freezeritem_id)
    freezeritem = clear_upload(freezeritem)
    broadcast_invalidate(FREEZERITEM_IMAGE_KEYS)
    return freezeritem

Schemas

FreezerItemIn

Schema to validate a FreezerItem.

Attributes:

Name Type Description
name str

The name of the frozen food.

qty int

How much is stored. Default = 1.

unit str

The unit for qty. Default = None.

date_added date

The date this went into the freezer. Default = None, meaning the date is unknown.

discard_date date

The date this should be thrown out. Default = None.

notes str

Notes for the frozen food. Default = None.

freezer_id int

ID of the freezer.

Source code in backend/backend/api.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
class FreezerItemIn(Schema):
    """
    Schema to validate a FreezerItem.

    Attributes:
        name (str): The name of the frozen food.
        qty (int): How much is stored. Default = 1.
        unit (str): The unit for qty. Default = None.
        date_added (date): The date this went into the freezer. Default = None,
            meaning the date is unknown.
        discard_date (date): The date this should be thrown out. Default = None.
        notes (str): Notes for the frozen food. Default = None.
        freezer_id (int): ID of the freezer.
    """

    name: str
    qty: int = 1
    unit: str = None
    date_added: date = None
    discard_date: date = None
    notes: str = None
    freezer_id: int

FreezerItemOut

Schema to represent a FreezerItem.

Attributes:

Name Type Description
id int

The ID of the freezer item.

name str

The name of the frozen food.

qty int

How much is stored. Default = 1.

unit str

The unit for qty. Default = None.

date_added date

The date this went into the freezer. None when the date is unknown.

discard_date date

The date this should be thrown out. Default = None.

notes str

Notes for the frozen food. Default = None.

freezer_id int

ID of the freezer.

days_until_discard int

Days left before discard_date, negative once past it. None when no discard_date is set.

is_expired bool

True if the discard date has passed.

image_url str

Path to the full photo, for tap-to-enlarge. None when the frozen food has no photo.

thumbnail_url str

Path to the thumbnail shown on rows. None when the frozen food has no photo.

Source code in backend/backend/api.py
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
class FreezerItemOut(Schema):
    """
    Schema to represent a FreezerItem.

    Attributes:
        id (int): The ID of the freezer item.
        name (str): The name of the frozen food.
        qty (int): How much is stored. Default = 1.
        unit (str): The unit for qty. Default = None.
        date_added (date): The date this went into the freezer. None when the
            date is unknown.
        discard_date (date): The date this should be thrown out. Default = None.
        notes (str): Notes for the frozen food. Default = None.
        freezer_id (int): ID of the freezer.
        days_until_discard (int): Days left before discard_date, negative once
            past it. None when no discard_date is set.
        is_expired (bool): True if the discard date has passed.
        image_url (str): Path to the full photo, for tap-to-enlarge. None when
            the frozen food has no photo.
        thumbnail_url (str): Path to the thumbnail shown on rows. None when the
            frozen food has no photo.
    """

    id: int
    name: str
    qty: int = 1
    unit: str = None
    date_added: date = None
    discard_date: date = None
    notes: str = None
    freezer_id: int
    days_until_discard: int = None
    is_expired: bool = False
    image_url: str = None
    thumbnail_url: str = None

    @staticmethod
    def resolve_image_url(obj):
        """
        Returns:
            (str): The media path of the full photo, or None.
        """
        return image_path(obj.image)

    @staticmethod
    def resolve_thumbnail_url(obj):
        """
        Returns:
            (str): The media path of the thumbnail, or None.
        """
        return image_path(obj.thumbnail)

FreezerItemUseIn

Schema to validate taking some of a FreezerItem out of the freezer.

Attributes:

Name Type Description
qty int

How many to use. Default = 1.

Source code in backend/backend/api.py
601
602
603
604
605
606
607
608
609
class FreezerItemUseIn(Schema):
    """
    Schema to validate taking some of a FreezerItem out of the freezer.

    Attributes:
        qty (int): How many to use. Default = 1.
    """

    qty: int = 1

FreezerItemTransferIn

Schema to validate moving a FreezerItem to another freezer.

Attributes:

Name Type Description
freezer_id int

ID of the freezer to move the food into.

qty int

How many to move. Default = None, meaning move all of them, which relocates the row rather than splitting it.

Source code in backend/backend/api.py
612
613
614
615
616
617
618
619
620
621
622
623
class FreezerItemTransferIn(Schema):
    """
    Schema to validate moving a FreezerItem to another freezer.

    Attributes:
        freezer_id (int): ID of the freezer to move the food into.
        qty (int): How many to move. Default = None, meaning move all of them,
            which relocates the row rather than splitting it.
    """

    freezer_id: int
    qty: int = None

FreezerItemChangeOut

Schema to report what a use or transfer did to a FreezerItem.

The caller cannot infer this from the request alone: using the last of something removes its row, and transferring all of something moves the row instead of creating one. The frontend needs to know which happened so it can word the confirmation.

Attributes:

Name Type Description
removed bool

True if the source row no longer exists, because the whole quantity was used or moved away.

remaining int

How many are left on the source row. 0 when removed.

item FreezerItemOut

The source row after the change, or None when it was removed.

created FreezerItemOut

The row created on the target freezer by a partial transfer. None for a use, and None for a whole-row transfer since that relocates the existing row.

Source code in backend/backend/api.py
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
class FreezerItemChangeOut(Schema):
    """
    Schema to report what a use or transfer did to a FreezerItem.

    The caller cannot infer this from the request alone: using the last of
    something removes its row, and transferring all of something moves the row
    instead of creating one. The frontend needs to know which happened so it can
    word the confirmation.

    Attributes:
        removed (bool): True if the source row no longer exists, because the
            whole quantity was used or moved away.
        remaining (int): How many are left on the source row. 0 when removed.
        item (FreezerItemOut): The source row after the change, or None when it
            was removed.
        created (FreezerItemOut): The row created on the target freezer by a
            partial transfer. None for a use, and None for a whole-row transfer
            since that relocates the existing row.
    """

    removed: bool = False
    remaining: int = 0
    item: FreezerItemOut = None
    created: FreezerItemOut = None

FreezerLog

Views

list_freezerlog(request, search=None, action=None, page=1, page_size=25)

The function list_freezerlog returns a page of the freezer history, newest first.

Answers "what happened to that meatloaf?" — which is why search matches the stored name on the entry rather than joining back to FreezerItem. The food is usually long deleted by the time anyone asks.

Endpoint
  • Path: /api/freezerlog
  • Method: GET

Parameters:

Name Type Description Default
request
required
search str

Case-insensitive fragment of the food's name. Default = None, meaning every entry.

None
action str

Restrict to one action. Default = None, meaning all.

None
page int

Which page to return. Default = 1.

1
page_size int

How many entries per page. Default = 25.

25

Returns:

Type Description
PaginatedFreezerLog

One page of history.

Source code in backend/backend/api.py
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
@api.get("/freezerlog", response=PaginatedFreezerLog)
def list_freezerlog(
    request,
    search: str = None,
    action: str = None,
    page: int = 1,
    page_size: int = 25,
):
    """
    The function `list_freezerlog` returns a page of the freezer history,
    newest first.

    Answers "what happened to that meatloaf?" — which is why `search` matches
    the **stored** name on the entry rather than joining back to FreezerItem.
    The food is usually long deleted by the time anyone asks.

    Endpoint:
        - **Path**: `/api/freezerlog`
        - **Method**: `GET`

    Args:
        request ():
        search (str): Case-insensitive fragment of the food's name. Default =
            None, meaning every entry.
        action (str): Restrict to one action. Default = None, meaning all.
        page (int): Which page to return. Default = 1.
        page_size (int): How many entries per page. Default = 25.

    Returns:
        (PaginatedFreezerLog): One page of history.
    """
    qs = FreezerLog.objects.all()
    if search:
        qs = qs.filter(name__icontains=search)
    if action:
        qs = qs.filter(action=action)

    # count() rather than len(): the history is the one table that grows without
    # bound, so the whole queryset is never pulled into memory just to size it.
    total_records = qs.count()
    total_pages = 0
    entries = []
    if total_records > 0:
        paginator = Paginator(qs, page_size)
        # A search that shortens the list can leave the page number past the
        # end; clamping beats a 404 the user cannot act on.
        page_obj = paginator.page(min(page, paginator.num_pages))
        entries = list(page_obj.object_list)
        total_pages = paginator.num_pages

    return PaginatedFreezerLog(
        entries=entries,
        current_page=page,
        total_pages=total_pages,
        total_records=total_records,
    )

Schemas

FreezerLogOut

Schema to represent one entry in the freezer history.

The freezer names are the stored text, not a lookup, so an entry still reads correctly after the food and even the freezer it names have been deleted.

Attributes:

Name Type Description
id int

The ID of the log entry.

action str

What happened — "added", "used", "moved" or "discarded".

name str

The food's name when the event happened.

qty int

How many the event concerned.

unit str

The unit for qty. Default = None.

freezer_name str

The freezer it happened in.

to_freezer_name str

Where a move sent it. None for other actions.

freezer_id int

The freezer, if it still exists. Default = None.

freezeritem_id int

The food, if it still exists. Default = None.

occurred datetime

When it happened.

Source code in backend/backend/api.py
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
class FreezerLogOut(Schema):
    """
    Schema to represent one entry in the freezer history.

    The freezer names are the stored text, not a lookup, so an entry still reads
    correctly after the food and even the freezer it names have been deleted.

    Attributes:
        id (int): The ID of the log entry.
        action (str): What happened — "added", "used", "moved" or "discarded".
        name (str): The food's name when the event happened.
        qty (int): How many the event concerned.
        unit (str): The unit for qty. Default = None.
        freezer_name (str): The freezer it happened in.
        to_freezer_name (str): Where a move sent it. None for other actions.
        freezer_id (int): The freezer, if it still exists. Default = None.
        freezeritem_id (int): The food, if it still exists. Default = None.
        occurred (datetime): When it happened.
    """

    id: int
    action: str
    name: str
    qty: int = 1
    unit: str = None
    freezer_name: str
    to_freezer_name: str = None
    freezer_id: int = None
    freezeritem_id: int = None
    occurred: datetime

PaginatedFreezerLog

Schema to represent a paginated page of freezer history.

Paginated because this is the one list in the app that only grows — every use, move and throw-out is kept — so it cannot be returned whole the way the freezer contents are.

Attributes:

Name Type Description
entries List[FreezerLogOut]

One page of history, newest first.

current_page int

The page returned.

total_pages int

The total number of pages.

total_records int

The total count of matching entries.

Source code in backend/backend/api.py
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
class PaginatedFreezerLog(Schema):
    """
    Schema to represent a paginated page of freezer history.

    Paginated because this is the one list in the app that only grows — every
    use, move and throw-out is kept — so it cannot be returned whole the way the
    freezer contents are.

    Attributes:
        entries (List[FreezerLogOut]): One page of history, newest first.
        current_page (int): The page returned.
        total_pages (int): The total number of pages.
        total_records (int): The total count of matching entries.
    """

    entries: List[FreezerLogOut]
    current_page: int
    total_pages: int
    total_records: int