python-sendparcel 0.3.0__py3-none-any.whl → 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-sendparcel
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: Framework-agnostic parcel shipping core for Python.
5
5
  Project-URL: Homepage, https://github.com/python-sendparcel/python-sendparcel
6
6
  Project-URL: Repository, https://github.com/python-sendparcel/python-sendparcel
@@ -1,20 +1,20 @@
1
- sendparcel/__init__.py,sha256=OZbB9xNjPbJvnKnaqHv4Ds7-IFc-M8sbjSgkszdNNE8,1521
1
+ sendparcel/__init__.py,sha256=jnFj2CbAJQLE4eeOerlAWgn0ub--fqRdhkscFRvBkfA,1689
2
2
  sendparcel/batch.py,sha256=4K3PgCOtV2QUNRqH_DuuhqbSYwIiNe-mSk6HKNORsmA,9332
3
3
  sendparcel/concurrent.py,sha256=RFkuIjL9XehDqBc2cHXivbzYlJtR_9ZxjAqO5_hxJzY,2082
4
4
  sendparcel/enums.py,sha256=e1UM9ka5zWJg4naMCoVeUrIy_PVPPEYHOBh6XiXaW4Q,687
5
5
  sendparcel/exceptions.py,sha256=zC5_o9oQfNuOBKaiw5csaHAJmhYsZc3WVbOaoq7s1W0,1437
6
6
  sendparcel/factory.py,sha256=VVB8Kz3J-7QI-VjrJsMwKso5SVZf97yZBX5nMbnCMM4,1045
7
- sendparcel/flow.py,sha256=6NED69FuqrvoVVXMk6P2V1RymLX_4V3-KIm7Ch2aAXk,10360
7
+ sendparcel/flow.py,sha256=ur-GNH9UinrQy2ttErFXzRB4TTh4jdbBP8BlokIKA4A,13328
8
8
  sendparcel/fsm.py,sha256=bRkt8tj_mg71Wq8obhhKK6nrQuN2a4Y_YXiL7kYxPDU,3134
9
9
  sendparcel/logging.py,sha256=TOetzdKJtl6YIY9Dpq-uxWB-jituOEKx0DpWmGrrBMU,4256
10
10
  sendparcel/protocols.py,sha256=7YX2KTOEG5Nje6bzibmIODFiTX7tgqb6I3WYgx9uVS4,2344
11
- sendparcel/provider.py,sha256=H28ZjvBpHY4C3LBvSm7DYa645300N4k2-X2fvl0epqc,8201
11
+ sendparcel/provider.py,sha256=lXuUevoDVdzqHFry0Mm_lSRgAJF5t6HQ1rj6sL5-_Js,10525
12
12
  sendparcel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
13
  sendparcel/registry.py,sha256=CCaU7Esd6vS5eVvvv_oLuWEhd9j17Zk3-hEOZl-_7Vk,3790
14
- sendparcel/types.py,sha256=nNECD7J6WZSlB8-SXnkperAW3d5zmKOM-9l-u9dZ5mk,3042
14
+ sendparcel/types.py,sha256=E96qcbQ6qfpvtA-LRdIzQounYXDWnfMNZJypzJ3dI1g,4855
15
15
  sendparcel/providers/__init__.py,sha256=ff82dvrWuPS-UIGF5AoX_fgpcYZaGu2k6q2yrxMZacI,192
16
16
  sendparcel/providers/dummy.py,sha256=J_FOzy0NsgKeI3Zxe0vTfPBdVeVSXKGd_zyMWfBL58Q,2836
17
- python_sendparcel-0.3.0.dist-info/METADATA,sha256=UJGCgut2oKHrg8P6HylzOvU2LeWCLE7l-0aoAoOCEpQ,7175
18
- python_sendparcel-0.3.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
19
- python_sendparcel-0.3.0.dist-info/licenses/LICENSE,sha256=IZXSBOjgGvChgayLmtTnU40iE7hsrrU3WVEYKx0sywY,1075
20
- python_sendparcel-0.3.0.dist-info/RECORD,,
17
+ python_sendparcel-0.3.1.dist-info/METADATA,sha256=vdcN_KGTpb5PjfoxvcSZXHerCcomZE7WDfS9dMdPXhk,7175
18
+ python_sendparcel-0.3.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
19
+ python_sendparcel-0.3.1.dist-info/licenses/LICENSE,sha256=IZXSBOjgGvChgayLmtTnU40iE7hsrrU3WVEYKx0sywY,1075
20
+ python_sendparcel-0.3.1.dist-info/RECORD,,
sendparcel/__init__.py CHANGED
@@ -21,8 +21,13 @@ from sendparcel.providers.dummy import DummyProvider
21
21
  from sendparcel.registry import registry
22
22
  from sendparcel.types import (
23
23
  CallbackContext,
24
+ CancelOutcome,
25
+ CancelReason,
24
26
  CreateLabelOutcome,
25
27
  CreateShipmentOutcome,
28
+ GeoPoint,
29
+ PickupPoint,
30
+ Quote,
26
31
  ShipmentUpdateOutcome,
27
32
  ShipmentUpdateResult,
28
33
  )
@@ -32,16 +37,21 @@ __all__ = [
32
37
  "BatchCreateResult",
33
38
  "BatchResult",
34
39
  "CallbackContext",
40
+ "CancelOutcome",
41
+ "CancelReason",
35
42
  "CommunicationError",
36
43
  "ConfirmationMethod",
37
44
  "CreateLabelOutcome",
38
45
  "CreateShipmentOutcome",
39
46
  "DummyProvider",
47
+ "GeoPoint",
40
48
  "InvalidCallbackError",
41
49
  "InvalidTransitionError",
42
50
  "LabelFormat",
51
+ "PickupPoint",
43
52
  "ProviderCapabilityError",
44
53
  "ProviderNotFoundError",
54
+ "Quote",
45
55
  "SendParcelException",
46
56
  "ShipmentBatch",
47
57
  "ShipmentFlow",
sendparcel/flow.py CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from dataclasses import dataclass
5
6
  from typing import Any
6
7
 
7
8
  import httpx
@@ -19,14 +20,30 @@ from sendparcel.registry import registry as default_registry
19
20
  from sendparcel.types import (
20
21
  AddressInfo,
21
22
  CallbackContext,
23
+ CancelOutcome,
24
+ CancelReason,
22
25
  CreateLabelOutcome,
23
26
  CreateShipmentOutcome,
27
+ GeoPoint,
24
28
  ParcelInfo,
29
+ PickupPoint,
25
30
  ShipmentUpdateOutcome,
26
31
  ShipmentUpdateResult,
27
32
  )
28
33
 
29
34
 
35
+ @dataclass(slots=True)
36
+ class _PointSearchShipment:
37
+ """Placeholder satisfying the Shipment protocol for provider calls
38
+ that do not operate on a specific shipment (e.g. point search)."""
39
+
40
+ provider: str
41
+ id: str = ""
42
+ status: str = "new"
43
+ external_id: str = ""
44
+ tracking_number: str = ""
45
+
46
+
30
47
  class ShipmentFlow:
31
48
  """Framework-agnostic shipment orchestration."""
32
49
 
@@ -193,19 +210,87 @@ class ShipmentFlow:
193
210
  saved = await self._apply_update(shipment, normalized_update)
194
211
  return ShipmentUpdateOutcome(shipment=saved, update=normalized_update)
195
212
 
196
- async def cancel_shipment(self, shipment: Shipment, **kwargs: Any) -> bool:
197
- """Cancel shipment via provider and persist state."""
198
-
213
+ async def cancel_shipment(
214
+ self, shipment: Shipment, **kwargs: Any
215
+ ) -> CancelOutcome:
216
+ """Cancel shipment via provider and persist state.
217
+
218
+ Returns a structured :class:`CancelOutcome` so callers can
219
+ distinguish permanent denies from retryable failures.
220
+
221
+ - ``CANCELLED`` / ``ALREADY_CANCELLED`` → transitions shipment to
222
+ ``CANCELLED``.
223
+ - ``REFUSED_IN_TRANSIT`` / ``NOT_CANCELLABLE`` → leaves shipment
224
+ in current state (caller decides UX).
225
+ - ``TRANSIENT_ERROR`` → raises ``CommunicationError`` (retryable),
226
+ no state change.
227
+ - ``AUTH_ERROR`` → re-raises provider auth error.
228
+ """
199
229
  provider = self._get_provider(shipment)
200
- cancelled = await self._call_provider(
201
- provider.cancel_shipment(**kwargs)
202
- )
203
- if cancelled:
230
+ outcome = await self._call_provider(provider.cancel_shipment(**kwargs))
231
+ if outcome.get("reason") == CancelReason.TRANSIENT_ERROR:
232
+ raise CommunicationError(
233
+ outcome.get("detail") or "Cancel failed with transient error",
234
+ context={
235
+ "provider_status_code": outcome.get("provider_status_code"),
236
+ "reason": CancelReason.TRANSIENT_ERROR,
237
+ },
238
+ )
239
+ if outcome.get("cancelled"):
204
240
  transition_shipment(shipment, ShipmentStatus.CANCELLED)
205
241
  await self.repository.update_fields(
206
242
  shipment_id=shipment.id, status=shipment.status
207
243
  )
208
- return bool(cancelled)
244
+ return outcome
245
+
246
+ async def search_points(
247
+ self,
248
+ provider_slug: str,
249
+ *,
250
+ query: str | None = None,
251
+ near: GeoPoint | None = None,
252
+ radius_m: int | None = None,
253
+ point_type: str | None = None,
254
+ limit: int = 20,
255
+ **kwargs: Any,
256
+ ) -> list[PickupPoint]:
257
+ """Search carrier pickup points via the registered provider.
258
+
259
+ Convenience method that delegates to the provider's
260
+ ``search_points`` capability. Raises
261
+ ``ProviderCapabilityError`` if the provider does not support
262
+ point search.
263
+
264
+ Args:
265
+ provider_slug: Provider identifier.
266
+ query: Free-text search (city, address, or point code).
267
+ near: :class:`GeoPoint` for proximity search.
268
+ radius_m: Search radius in metres when ``near`` is given.
269
+ point_type: Provider taxonomy filter.
270
+ limit: Maximum number of results.
271
+
272
+ Returns:
273
+ List of :class:`PickupPoint` results.
274
+ """
275
+ provider_class = self.registry.get_by_slug(provider_slug)
276
+ provider_config = self.config.get(provider_slug, {})
277
+ from sendparcel.factory import create_provider
278
+
279
+ provider = create_provider(
280
+ _PointSearchShipment(provider=provider_slug),
281
+ provider_class,
282
+ provider_config,
283
+ )
284
+ return await self._call_provider(
285
+ provider.search_points(
286
+ query=query,
287
+ near=near,
288
+ radius_m=radius_m,
289
+ point_type=point_type,
290
+ limit=limit,
291
+ **kwargs,
292
+ )
293
+ )
209
294
 
210
295
  def _get_provider(self, shipment: Shipment) -> BaseProvider:
211
296
  from sendparcel.factory import create_provider
sendparcel/provider.py CHANGED
@@ -12,8 +12,12 @@ from sendparcel.protocols import Shipment
12
12
  from sendparcel.types import (
13
13
  AddressInfo,
14
14
  CallbackContext,
15
+ CancelOutcome,
16
+ GeoPoint,
15
17
  LabelInfo,
16
18
  ParcelInfo,
19
+ PickupPoint,
20
+ Quote,
17
21
  ShipmentCreateResult,
18
22
  ShipmentUpdateResult,
19
23
  )
@@ -230,9 +234,13 @@ class BaseProvider(ABC):
230
234
  "status polling"
231
235
  )
232
236
 
233
- async def cancel_shipment(self, **kwargs: Any) -> bool:
237
+ async def cancel_shipment(self, **kwargs: Any) -> CancelOutcome:
234
238
  """Cancel shipment if provider supports cancellation.
235
239
 
240
+ Returns a structured :class:`CancelOutcome` so callers can
241
+ distinguish permanent denies (REFUSED_IN_TRANSIT, NOT_CANCELLABLE)
242
+ from retryable failures (TRANSIENT_ERROR).
243
+
236
244
  Raises :exc:`ProviderCapabilityError` if the provider does not
237
245
  support cancellation.
238
246
  """
@@ -240,3 +248,63 @@ class BaseProvider(ABC):
240
248
  f"Provider {self.__class__.__name__!r} does not support "
241
249
  "cancellation"
242
250
  )
251
+
252
+ async def search_points(
253
+ self,
254
+ *,
255
+ query: str | None = None,
256
+ near: GeoPoint | None = None,
257
+ radius_m: int | None = None,
258
+ point_type: str | None = None,
259
+ limit: int = 20,
260
+ **kwargs: Any,
261
+ ) -> list[PickupPoint]:
262
+ """Search carrier pickup points (lockers, parcel shops, etc.).
263
+
264
+ Args:
265
+ query: Free-text search (city, address, or point code).
266
+ near: :class:`GeoPoint` for proximity search.
267
+ radius_m: Search radius in metres when ``near`` is given.
268
+ point_type: Provider taxonomy filter (e.g. "parcel_locker").
269
+ limit: Maximum number of results to return.
270
+
271
+ Returns:
272
+ List of :class:`PickupPoint` results, ordered by distance
273
+ when ``near`` is given, else by relevance/name.
274
+
275
+ Raises:
276
+ ProviderCapabilityError: If the provider does not support
277
+ point search.
278
+ """
279
+ raise ProviderCapabilityError(
280
+ f"Provider {self.__class__.__name__!r} does not support "
281
+ "pickup point search"
282
+ )
283
+
284
+ async def get_quote(
285
+ self,
286
+ *,
287
+ service: str,
288
+ parcels: list[ParcelInfo],
289
+ sender_address: AddressInfo | None = None,
290
+ receiver_address: AddressInfo | None = None,
291
+ **kwargs: Any,
292
+ ) -> Quote:
293
+ """Get a shipping rate quote for a service/route combination.
294
+
295
+ Args:
296
+ service: Service slug (e.g. "parcel_locker_31_0").
297
+ parcels: List of parcel definitions.
298
+ sender_address: Optional sender address.
299
+ receiver_address: Optional receiver address.
300
+
301
+ Returns:
302
+ :class:`Quote` with carrier cost as ``Decimal``.
303
+
304
+ Raises:
305
+ ProviderCapabilityError: If the provider does not support
306
+ rate lookup (callers should fall back to static pricing).
307
+ """
308
+ raise ProviderCapabilityError(
309
+ f"Provider {self.__class__.__name__!r} does not support rate lookup"
310
+ )
sendparcel/types.py CHANGED
@@ -5,7 +5,9 @@ from __future__ import annotations
5
5
  import hashlib
6
6
  import json
7
7
  from dataclasses import dataclass
8
+ from datetime import datetime
8
9
  from decimal import Decimal
10
+ from enum import StrEnum
9
11
  from typing import Any, TypedDict
10
12
 
11
13
  from sendparcel.enums import LabelFormat
@@ -107,6 +109,81 @@ class ShipmentUpdateOutcome:
107
109
  update: ShipmentUpdateResult
108
110
 
109
111
 
112
+ class CancelReason(StrEnum):
113
+ """Reason for a cancel_shipment outcome."""
114
+
115
+ CANCELLED = "cancelled"
116
+ ALREADY_CANCELLED = "already_cancelled"
117
+ REFUSED_IN_TRANSIT = "refused_in_transit"
118
+ NOT_CANCELLABLE = "not_cancellable"
119
+ TRANSIENT_ERROR = "transient_error"
120
+ AUTH_ERROR = "auth_error"
121
+
122
+
123
+ class _CancelOutcomeRequired(TypedDict):
124
+ cancelled: bool
125
+ reason: CancelReason
126
+ retryable: bool
127
+
128
+
129
+ class CancelOutcome(_CancelOutcomeRequired, total=False):
130
+ """Structured result from cancel_shipment.
131
+
132
+ Replaces the bare bool return so callers can distinguish permanent
133
+ denies (REFUSED_IN_TRANSIT, NOT_CANCELLABLE) from retryable failures
134
+ (TRANSIENT_ERROR).
135
+ """
136
+
137
+ provider_status_code: int | None
138
+ detail: str | None
139
+
140
+
141
+ class GeoPoint(TypedDict):
142
+ """Geographic coordinate pair."""
143
+
144
+ lat: float
145
+ lng: float
146
+
147
+
148
+ class _PickupPointRequired(TypedDict):
149
+ code: str
150
+ name: str
151
+ provider_slug: str
152
+ address: str
153
+
154
+
155
+ class PickupPoint(_PickupPointRequired, total=False):
156
+ """Carrier pickup point (locker, parcel shop, etc.).
157
+
158
+ ``code`` is the machine id used as ``target_point`` in
159
+ ``create_shipment``, so a searched point is directly usable
160
+ without translation.
161
+ """
162
+
163
+ location: GeoPoint | None
164
+ opening_hours: str | None
165
+ point_type: str | None
166
+ raw: dict[str, Any] | None
167
+
168
+
169
+ class _QuoteRequired(TypedDict):
170
+ provider_slug: str
171
+ service: str
172
+ amount: Decimal
173
+ currency: str
174
+
175
+
176
+ class Quote(_QuoteRequired, total=False):
177
+ """Shipping rate quote from a carrier.
178
+
179
+ ``amount`` is the carrier cost in the provider's currency.
180
+ Use ``Decimal`` — never ``float`` — for monetary values.
181
+ """
182
+
183
+ valid_until: datetime | None
184
+ raw: dict[str, Any] | None
185
+
186
+
110
187
  @dataclass(slots=True)
111
188
  class CallbackContext:
112
189
  """Everything needed to process a webhook callback.