8000 Move `GS1Message.{get,filter}()` to new `GS1ElementStrings` container by jodal · Pull Request #391 · jodal/biip · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Move GS1Message.{get,filter}() to new GS1ElementStrings container #391

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/biip/_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,11 @@ def _parse_gs1_message(
result.gs1_message_error = str(exc)
else:
# If the GS1 Message contains an SSCC, set SSCC on the top-level result.
ai_00 = result.gs1_message.get(ai="00")
ai_00 = result.gs1_message.element_strings.get(ai="00")
if ai_00 is not None:
queue.append((_parse_sscc, ai_00.value))

# If the GS1 Message contains an GTIN, set GTIN on the top-level result.
ai_01 = result.gs1_message.get(ai="01")
ai_01 = result.gs1_message.element_strings.get(ai="01")
if ai_01 is not None:
queue.append((_parse_gtin, ai_01.value))
3 changes: 2 additions & 1 deletion src/biip/gln.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
>>> import biip
>>> gln = (
... biip.parse("4101234567890128")
... .gs1_message.get(data_title="SHIP TO")
... .gs1_message
... .element_strings.get(data_title="SHIP TO")
... .gln
... )
>>> pprint(gln)
Expand Down
56 changes: 56 additions & 0 deletions src/biip/gs1_element_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,3 +376,59 @@ def _get_century(two_digit_year: int) -> int:
def _get_last_day_of_month(year: int, month: int) -> int:
"""Get the last day of the given month."""
return calendar.monthrange(year, month)[1]


class GS1ElementStrings(list[GS1ElementString]):
"""List of GS1 element strings."""

def filter(
self,
*,
ai: str | GS1ApplicationIdentifier | None = None,
data_title: str | None = None,
) -> GS1ElementStrings:
"""Filter element strings by AI or data title.

Args:
ai: AI instance or string to match against the start of the
element string's AI.
data_title: String to find anywhere in the element string's AI
data title.

Returns:
All matching element strings in the list.
"""
if isinstance(ai, GS1ApplicationIdentifier):
ai = ai.ai

result = GS1ElementStrings()

for element_string in self:
ai_match = ai is not None and element_string.ai.ai.startswith(ai)
data_title_match = (
data_title is not None and data_title in element_string.ai.data_title
)
if ai_match or data_title_match:
result.append(element_string)

return result

def get(
self,
*,
ai: str | GS1ApplicationIdentifier | None = None,
data_title: str | None = None,
) -> GS1ElementString | None:
"""Get element string by AI or data title.

Args:
ai: AI instance or string to match against the start of the
element string's AI.
data_title: String to find anywhere in the element string's AI
data title.

Returns:
The first matching element string in the list.
"""
matches = self.filter(ai=ai, data_title=data_title)
return matches[0] if matches else None
117 changes: 39 additions & 78 deletions src/biip/gs1_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,13 @@
)
)

The message object has [`msg.get()`][biip.gs1_messages.GS1Message.get] and
[`msg.filter()`][biip.gs1_messages.GS1Message.filter] methods to lookup element
strings either by the Application Identifier's "data title" or its AI number.
The `element_strings` attribute has
[`element_strings.get()`][biip.gs1_element_strings.GS1ElementStrings.get] and
[`element_strings.filter()`][biip.gs1_element_strings.GS1ElementStrings.filter]
methods to lookup element strings either by the Application Identifier's "data
title" or its AI number.

>>> pprint(msg.get(data_title='BEST BY'))
>>> pprint(msg.element_strings.get(data_title='BEST BY'))
GS1ElementString(
ai=GS1ApplicationIdentifier(
ai='15',
Expand All @@ -92,7 +94,7 @@
],
date=datetime.date(2021, 5, 26)
)
>>> pprint(msg.get(ai="10"))
>>> pprint(msg.element_strings.get(ai="10"))
GS1ElementString(
ai=GS1ApplicationIdentifier(
ai='10',
Expand All @@ -116,11 +118,8 @@

from biip import ParseError
from biip._parser import ParseConfig
from biip.gs1_application_identifiers import (
_GS1_APPLICATION_IDENTIFIERS,
GS1ApplicationIdentifier,
)
from biip.gs1_element_strings import GS1ElementString
from biip.gs1_application_identifiers import _GS1_APPLICATION_IDENTIFIERS
from biip.gs1_element_strings import GS1ElementString, GS1ElementStrings


@dataclass
Expand All @@ -136,7 +135,7 @@ class GS1Message:
value: str
"""Raw unprocessed value."""

element_strings: list[GS1ElementString]
element_strings: GS1ElementStrings
"""List of Element Strings found in the message."""

@classmethod
Expand All @@ -163,7 +162,7 @@ def parse(
config = ParseConfig()

value = value.strip()
element_strings: list[GS1ElementString] = []
element_strings = GS1ElementStrings()
rest = value[:]

while rest:
Expand All @@ -180,6 +179,29 @@ def parse(

return cls(value=value, element_strings=element_strings)

@classmethod
def from_element_strings(cls, element_strings: GS1ElementStrings) -> GS1Message:
"""Create a GS1 message from a list of element strings.

Args:
element_strings: A list of GS1 element strings.

Returns:
GS1Message: The created GS1 message.
"""
parts = chain(
*[
[
es.ai.ai,
es.value,
("\x1d" if es.ai.separator_required else ""),
]
for es in element_strings
]
)
normalized_string = "".join(parts).removesuffix("\x1d")
return cls(value=normalized_string, element_strings=element_strings)

@classmethod
def parse_hri(
cls,
Expand Down Expand Up @@ -216,25 +238,16 @@ def parse_hri(
)
raise ParseError(msg)

pairs: list[tuple[GS1ApplicationIdentifier, str]] = []
element_strings = GS1ElementStrings()
for ai_number, ai_data in matches:
if ai_number not in _GS1_APPLICATION_IDENTIFIERS:
msg = f"Unknown GS1 Application Identifier {ai_number!r} in {value!r}."
raise ParseError(msg)
pairs.append((_GS1_APPLICATION_IDENTIFIERS[ai_number], ai_data))
element_strings.append(
GS1ElementString.extract(f"{ai_number}{ai_data}", config=config)
)

parts = chain(
*[
[
gs1_ai.ai,
ai_data,
("\x1d" if gs1_ai.separator_required else ""),
]
for gs1_ai, ai_data in pairs
]
)
normalized_string = "".join(parts)
return GS1Message.parse(normalized_string, config=config)
return GS1Message.from_element_strings(element_strings)

def as_hri(self) -> str:
"""Render as a human readable interpretation (HRI).
Expand All @@ -245,55 +258,3 @@ def as_hri(self) -> str:
A human-readable string where the AIs are wrapped in parenthesis.
"""
return "".join(es.as_hri() for es in self.element_strings)

def filter(
self,
*,
ai: str | GS1ApplicationIdentifier | None = None,
data_title: str | None = None,
) -> list[GS1ElementString]:
"""Filter Element Strings by AI or data title.

Args:
ai: AI instance or string to match against the start of the
Element String's AI.
data_title: String to find anywhere in the Element String's AI
data title.

Returns:
All matching Element Strings in the message.
"""
if isinstance(ai, GS1ApplicationIdentifier):
ai = ai.ai

result: list[GS1ElementString] = []

for element_string in self.element_strings:
ai_match = ai is not None and element_string.ai.ai.startswith(ai)
data_title_match = (
data_title is not None and data_title in element_string.ai.data_title
)
if ai_match or data_title_match:
result.append(element_string)

return result

def get(
self,
*,
ai: str | GS1ApplicationIdentifier | None = None,
data_title: str | None = None,
) -> GS1ElementString | None:
"""Get Element String by AI or data title.

Args:
ai: AI instance or string to match against the start of the
Element String's AI.
data_title: String to find anywhere in the Element String's AI
data title.

Returns:
The first matching Element String in the message.
"""
matches = self.filter(ai=ai, data_title=data_title)
return matches[0] if matches else None
Loading
Loading
0