Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Use c&c address for tax calculations in Avatax plugin (#10667)

Maciej Korycinski77ae96a71255
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 497c87e363..b450a3c81b 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -197,7 +197,7 @@ class CollectionPointInfo(DeliveryMethodBase):
@singledispatch
def get_delivery_method_info(
delivery_method: Optional[Union["ShippingMethodData", "Warehouse", Callable]],
- address=Optional["Address"],
+ address: Optional["Address"] = None,
) -> DeliveryMethodBase:
if callable(delivery_method):
delivery_method = delivery_method()
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index 1174eac3b5..be64d8921b 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -13,6 +13,7 @@ from django.contrib.sites.models import Site
from django.core.cache import cache
from requests.auth import HTTPBasicAuth
+from ...account.models import Address
from ...checkout import base_calculations
from ...checkout.utils import is_shipping_required
from ...core.taxes import TaxError
@@ -22,7 +23,8 @@ from ...order.utils import (
get_total_order_discount_excluding_shipping,
get_voucher_discount_assigned_to_order,
)
-from ...shipping.models import ShippingMethodChannelListing
+from ...shipping.models import ShippingMethod, ShippingMethodChannelListing
+from ...warehouse.models import Warehouse
if TYPE_CHECKING:
from ...checkout.fetch import CheckoutInfo, CheckoutLineInfo
@@ -146,13 +148,13 @@ def api_get_request(
def _validate_adddress_details(
- shipping_address, is_shipping_required, address, shipping_method
+ shipping_address, is_shipping_required, address, delivery_method
):
if not is_shipping_required and address:
return True
if not shipping_address:
return False
- if not shipping_method:
+ if not delivery_method:
return False
return True
@@ -161,17 +163,23 @@ def _validate_order(order: "Order") -> bool:
"""Validate the order object if it is ready to generate a request to avatax."""
if not order.lines.exists():
return False
- shipping_address = order.shipping_address
shipping_required = order.is_shipping_required()
- address = shipping_address or order.billing_address
- shipping_method = order.shipping_method
+ if order.collection_point_id:
+ collection_point = order.collection_point
+ delivery_method: Union[None, ShippingMethod, Warehouse] = collection_point
+ shipping_address = collection_point.address # type: ignore
+ address = shipping_address
+ else:
+ delivery_method = order.shipping_method
+ shipping_address = order.shipping_address
+ address = shipping_address or order.billing_address
valid_address_details = _validate_adddress_details(
- shipping_address, shipping_required, address, shipping_method
+ shipping_address, shipping_required, address, delivery_method
)
if not valid_address_details:
return False
- if shipping_required:
- channel_listing = shipping_method.channel_listings.filter( # type: ignore
+ if shipping_required and isinstance(delivery_method, ShippingMethod):
+ channel_listing = delivery_method.channel_listings.filter( # type: ignore
channel_id=order.channel_id
).first()
if not channel_listing:
@@ -186,8 +194,8 @@ def _validate_checkout(
if not lines:
return False
- shipping_address = checkout_info.shipping_address
shipping_required = is_shipping_required(lines)
+ shipping_address = checkout_info.delivery_method_info.shipping_address
address = shipping_address or checkout_info.billing_address
return _validate_adddress_details(
shipping_address,
@@ -426,6 +434,21 @@ def get_order_lines_data(
return data
+def _is_single_location(ship_from, ship_to):
+ for key, value in ship_from.items():
+ if key not in ship_to:
+ return False
+ if not value and not ship_to[key]:
+ continue
+ if value is None or ship_to[key] is None:
+ return False
+
+ if value.lower() == ship_to[key].lower():
+ continue
+ return False
+ return True
+
+
def generate_request_data(
transaction_type: str,
lines: List[Dict[str, Any]],
@@ -436,6 +459,26 @@ def generate_request_data(
currency: str,
discount: Optional[Decimal] = None,
):
+ ship_from = {
+ "line1": config.from_street_address,
+ "line2": "",
+ "city": config.from_city,
+ "region": config.from_country_area,
+ "country": config.from_country,
+ "postalCode": config.from_postal_code,
+ }
+ ship_to = {
+ "line1": address.get("street_address_1"),
+ "line2": address.get("street_address_2"),
+ "city": address.get("city"),
+ "region": address.get("country_area"),
+ "country": address.get("country"),
+ "postalCode": address.get("postal_code"),
+ }
+ if _is_single_location(ship_from, ship_to):
+ addresses: Dict[str, Dict] = {"singleLocation": ship_to}
+ else:
+ addresses = {"shipFrom": ship_from, "shipTo": ship_to}
data = {
"companyCode": config.company_name,
"type": transaction_type,
@@ -446,24 +489,7 @@ def generate_request_data(
"customerCode": 0,
# https://developer.avalara.com/avatax/dev-guide/discounts-and-overrides/discounts/
"discount": str(discount) if discount else None,
- "addresses": {
- "shipFrom": {
- "line1": config.from_street_address,
- "line2": None,
- "city": config.from_city,
- "region": config.from_country_area,
- "country": config.from_country,
- "postalCode": config.from_postal_code,
- },
- "shipTo": {
- "line1": address.get("street_address_1"),
- "line2": address.get("street_address_2"),
- "city": address.get("city"),
- "region": address.get("country_area"),
- "country": address.get("country"),
- "postalCode": address.get("postal_code"),
- },
- },
+ "addresses": addresses,
"commit": config.autocommit,
"currencyCode": currency,
"email": customer_email,
@@ -480,7 +506,8 @@ def generate_request_data_from_checkout(
transaction_type=TransactionType.ORDER,
discounts=None,
):
- address = checkout_info.shipping_address or checkout_info.billing_address
+ shipping_address = checkout_info.delivery_method_info.shipping_address
+ address = shipping_address or checkout_info.billing_address
lines = get_checkout_lines_data(
checkout_info, lines_info, config, tax_included, discounts
)
@@ -570,7 +597,11 @@ def get_checkout_tax_data(
def get_order_request_data(
order: "Order", config: AvataxConfiguration, tax_included: bool
):
- address = order.shipping_address or order.billing_address
+ if order.collection_point_id:
+ address: Address = order.collection_point.address # type: ignore
+ else:
+ address = order.shipping_address or order.billing_address # type: ignore
+
transaction = (
TransactionType.INVOICE
if not (order.is_draft() or order.is_unconfirmed())
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index a673e7beca..30ccf993df 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -708,6 +708,7 @@ class AvataxPlugin(BasePlugin):
response = get_checkout_tax_data(
checkout_info, lines_info, self.config.tax_included, discounts, self.config
)
+
if not response or "error" in response:
return None
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_checkout_tax_data_with_single_point.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_checkout_tax_data_with_single_point.yaml
new file mode 100644
index 0000000000..78a63ea853
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_checkout_tax_data_with_single_point.yaml
@@ -0,0 +1,69 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",
+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "123", "discounted": false, "description": "Test product",
+ "ref1": "123"}], "code": "4f12c392-a11d-495d-832e-d19dc82d6b7e", "date": "2022-09-15",
+ "customerCode": 0, "discount": null, "addresses": {"singleLocation": {"line1":
+ "4371 Lucas Knoll Apt. 791", "line2": "", "city": "BENNETTMOUTH", "region":
+ "", "country": "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode":
+ "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '592'
+ User-Agent:
+ - python-requests/2.28.1
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"id":0,"code":"4f12c392-a11d-495d-832e-d19dc82d6b7e","companyId":7799660,"date":"2022-09-15","paymentDate":"2022-09-15","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":24.39,"totalExempt":0.0,"totalDiscount":0.0,"totalTax":5.61,"totalTaxable":24.39,"totalTaxCalculated":5.61,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2022-09-15","exchangeRate":1.0,"email":"[email protected]","modifiedDate":"2022-09-15T08:41:19.7426832Z","modifiedUserId":6479978,"taxDate":"2022-09-15","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test
+ product","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":24.3900,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2022-09-15","tax":5.61,"taxableAmount":24.39,"taxCalculated":5.61,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2022-09-15","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":5.61,"taxableAmount":24.39,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxCalculated":5.61,"rateType":"Standard","rateTypeCode":"S","unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":24.39,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":5.61,"reportingTaxCalculated":5.61,"liabilityType":"Seller"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"4371
+ Lucas Knoll Apt. 791","line2":"","line3":"","city":"BENNETTMOUTH","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
+ Rate","rateType":"Standard","taxable":24.39,"rate":0.230000,"tax":5.61,"taxCalculated":5.61,"nonTaxable":0.0,"exemption":0.0}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 15 Sep 2022 08:41:19 GMT
+ Location:
+ - /api/v2/companies/7799660/transactions/0
+ ServerDuration:
+ - '00:00:00.0100454'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - d44035ff-332d-4fa6-8aa2-76ca07d86cc3
+ x-correlation-id:
+ - d44035ff-332d-4fa6-8aa2-76ca07d86cc3
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_order_tax_data_with_single_location.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_order_tax_data_with_single_location.yaml
new file mode 100644
index 0000000000..52168b2f07
--- /dev/null
+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_order_tax_data_with_single_location.yaml
@@ -0,0 +1,68 @@
+interactions:
+- request:
+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesInvoice",
+ "lines": [{"quantity": 3, "amount": "36.900", "taxCode": "O9999999", "taxIncluded":
+ true, "itemCode": "SKU_A", "discounted": false, "description": "Test product"}],
+ "code": "02ac1095-b6cc-4f64-ad58-63c63c950f42", "date": "2022-09-15", "customerCode":
+ 0, "discount": null, "addresses": {"singleLocation": {"line1": "4371 Lucas Knoll
+ Apt. 791", "line2": "", "city": "BENNETTMOUTH", "region": "", "country": "PL",
+ "postalCode": "53-601"}}, "commit": false, "currencyCode": "USD", "email": "[email protected]"}}'
+ headers:
+ Accept:
+ - '*/*'
+ Accept-Encoding:
+ - gzip, deflate, br
+ Authorization:
+ - Basic Og==
+ Connection:
+ - keep-alive
+ Content-Length:
+ - '584'
+ User-Agent:
+ - python-requests/2.28.1
+ method: POST
+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust
+ response:
+ body:
+ string: '{"id":85009482781094,"code":"02ac1095-b6cc-4f64-ad58-63c63c950f42","companyId":7799660,"date":"2022-09-15","status":"Saved","type":"SalesInvoice","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","taxOverrideType":"None","taxOverrideAmount":0.0,"taxOverrideReason":"","totalAmount":30.0,"totalExempt":0.0,"totalDiscount":0.0,"totalTax":6.9,"totalTaxable":30.0,"totalTaxCalculated":6.9,"adjustmentReason":"NotAdjusted","adjustmentDescription":"","locked":false,"region":"","country":"PL","version":1,"softwareVersion":"22.8.2.0","originAddressId":85009482781095,"destinationAddressId":85009482781095,"exchangeRateEffectiveDate":"2022-09-15","exchangeRate":1.0,"description":"","email":"[email protected]","businessIdentificationNo":"","modifiedDate":"2022-09-15T08:49:34.1753817Z","modifiedUserId":6479978,"taxDate":"2022-09-15","lines":[{"id":85009482781104,"transactionId":85009482781094,"lineNumber":"1","boundaryOverrideId":0,"customerUsageType":"","entityUseCode":"","description":"Test
+ product","destinationAddressId":85009482781095,"originAddressId":85009482781095,"discountAmount":0.0,"discountTypeId":0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"isSSTP":false,"itemCode":"SKU_A","lineAmount":30.0000,"quantity":3.0,"ref1":"","ref2":"","reportingDate":"2022-09-15","revAccount":"","sourcing":"Destination","tax":6.9,"taxableAmount":30.0,"taxCalculated":6.9,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2022-09-15","taxEngine":"","taxOverrideType":"None","businessIdentificationNo":"","taxOverrideAmount":0.0,"taxOverrideReason":"","taxIncluded":true,"details":[{"id":85009482781132,"transactionLineId":85009482781104,"transactionId":85009482781094,"addressId":85009482781095,"country":"PL","region":"PL","countyFIPS":"","stateFIPS":"","exemptAmount":0.0000,"exemptReasonId":4,"inState":true,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"signatureCode":"","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0000,"nonTaxableRuleId":0,"nonTaxableType":"RateRule","rate":0.230000,"rateRuleId":411502,"rateSourceId":0,"serCode":"","sourcing":"Destination","tax":6.9000,"taxableAmount":30.0000,"taxType":"Output","taxSubTypeId":"O","taxTypeGroupId":"InputAndOutput","taxName":"Standard
+ Rate","taxAuthorityTypeId":45,"taxRegionId":205102,"taxCalculated":6.9000,"taxOverride":0.0000,"rateType":"Standard","rateTypeCode":"S","taxableUnits":30.0000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":30.0,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":6.9,"reportingTaxCalculated":6.9,"liabilityType":"Seller"}],"nonPassthroughDetails":[],"lineLocationTypes":[{"documentLineLocationTypeId":85009482781106,"documentLineId":85009482781104,"documentAddressId":85009482781095,"locationTypeCode":"ShipFrom"},{"documentLineLocationTypeId":85009482781107,"documentLineId":85009482781104,"documentAddressId":85009482781095,"locationTypeCode":"ShipTo"},{"documentLineLocationTypeId":85009482781108,"documentLineId":85009482781104,"documentAddressId":85009482781095,"locationTypeCode":"PointOfOrderAcceptance"},{"documentLineLocationTypeId":85009482781109,"documentLineId":85009482781104,"documentAddressId":85009482781095,"locationTypeCode":"PointOfOrderOrigin"},{"documentLineLocationTypeId":85009482781110,"documentLineId":85009482781104,"documentAddressId":85009482781095,"locationTypeCode":"GoodsPlaceOrServiceRendered"},{"documentLineLocationTypeId":85009482781111,"documentLineId":85009482781104,"documentAddressId":85009482781095,"locationTypeCode":"Import"},{"documentLineLocationTypeId":85009482781112,"documentLineId":85009482781104,"documentAddressId":85009482781095,"locationTypeCode":"BillTo"}],"parameters":[{"name":"Transport","value":"None"},{"name":"IsMarketplace","value":"False"},{"name":"IsTriangulation","value":"false"},{"name":"IsGoodsSecondHand","value":"false"}],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0}],"addresses":[{"id":85009482781095,"transactionId":85009482781094,"boundaryLevel":"Zip5","line1":"4371
+ Lucas Knoll Apt. 791","line2":"","line3":"","city":"BENNETTMOUTH","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102}],"locationTypes":[{"documentLocationTypeId":85009482781097,"documentId":85009482781094,"documentAddressId":85009482781095,"locationTypeCode":"ShipFrom"},{"documentLocationTypeId":85009482781098,"documentId":85009482781094,"documentAddressId":85009482781095,"locationTypeCode":"ShipTo"},{"documentLocationTypeId":85009482781099,"documentId":85009482781094,"documentAddressId":85009482781095,"locationTypeCode":"PointOfOrderAcceptance"},{"documentLocationTypeId":85009482781100,"documentId":85009482781094,"documentAddressId":85009482781095,"locationTypeCode":"PointOfOrderOrigin"},{"documentLocationTypeId":85009482781101,"documentId":85009482781094,"documentAddressId":85009482781095,"locationTypeCode":"GoodsPlaceOrServiceRendered"},{"documentLocationTypeId":85009482781102,"documentId":85009482781094,"documentAddressId":85009482781095,"locationTypeCode":"Import"},{"documentLocationTypeId":85009482781103,"documentId":85009482781094,"documentAddressId":85009482781095,"locationTypeCode":"BillTo"}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard
+ Rate","rateType":"Standard","taxable":30.00,"rate":0.230000,"tax":6.90,"taxCalculated":6.90,"nonTaxable":0.00,"exemption":0.00}]}'
+ headers:
+ Connection:
+ - keep-alive
+ Content-Type:
+ - application/json; charset=utf-8
+ Date:
+ - Thu, 15 Sep 2022 08:49:34 GMT
+ Location:
+ - /api/v2/companies/7799660/transactions/85009482781094
+ ServerDuration:
+ - '00:00:00.0875476'
+ Transfer-Encoding:
+ - chunked
+ X-Content-Type-Options:
+ - nosniff
+ api-supported-versions:
+ - '2.0'
+ cache-control:
+ - private, no-cache, no-store
+ referrer-policy:
+ - same-origin
+ strict-transport-security:
+ - max-age=31536000; includeSubdomains
+ x-avalara-uid:
+ - 0e26ad5a-f529-4437-b903-7c7982209764
+ x-correlation-id:
+ - 0e26ad5a-f529-4437-b903-7c7982209764
+ x-frame-options:
+ - sameorigin
+ x-permitted-cross-domain-policies:
+ - none
+ x-xss-protection:
+ - 1; mode=block
+ status:
+ code: 201
+ message: Created
+version: 1
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 3604ae908f..07b914caf4 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -9,6 +9,7 @@ from django.test import override_settings
from prices import Money, TaxedMoney
from requests import RequestException
+from ....account.models import Address
from ....checkout.fetch import (
CheckoutInfo,
fetch_checkout_info,
@@ -33,12 +34,14 @@ from .. import (
AvataxConfiguration,
TransactionType,
_validate_adddress_details,
+ _validate_checkout,
_validate_order,
api_get_request,
api_post_request,
generate_request_data_from_checkout,
get_cached_tax_codes_or_fetch,
get_checkout_lines_data,
+ get_checkout_tax_data,
get_order_lines_data,
get_order_request_data,
get_order_tax_data,
@@ -2614,6 +2617,149 @@ def test_checkout_needs_new_fetch(checkout_with_item, address, shipping_method):
assert taxes_need_new_fetch(checkout_data, None)
+def test_generate_request_data_from_checkout_for_cc(
+ checkout_with_item,
+ address,
+ address_other_country,
+ warehouse,
+):
+ # given
+ warehouse.address = address_other_country
+ warehouse.is_private = False
+ warehouse.save()
+
+ checkout_with_item.shipping_address = address
+ checkout_with_item.collection_point = warehouse
+ checkout_with_item.save()
+
+ config = AvataxConfiguration(
+ username_or_account="wrong_data",
+ password_or_license="wrong_data",
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
+ )
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+
+ # when
+ request_data = generate_request_data_from_checkout(
+ checkout_info, lines, config, tax_included=True
+ )
+
+ # then
+ expected_address_data = address_other_country.as_data()
+ addresses = request_data["createTransactionModel"]["addresses"]
+ assert "shipTo" in addresses
+ assert "shipFrom" in addresses
+ assert addresses["shipTo"] == {
+ "line1": expected_address_data.get("street_address_1"),
+ "line2": expected_address_data.get("street_address_2"),
+ "city": expected_address_data.get("city"),
+ "region": expected_address_data.get("country_area"),
+ "country": expected_address_data.get("country"),
+ "postalCode": expected_address_data.get("postal_code"),
+ }
+
+
+def test_generate_request_data_from_checkout_for_cc_and_single_location(
+ checkout_with_item,
+ address,
+ address_other_country,
+ warehouse,
+):
+ # given
+ warehouse.address = address_other_country
+ warehouse.is_private = False
+ warehouse.save()
+
+ checkout_with_item.shipping_address = address
+ checkout_with_item.collection_point = warehouse
+ checkout_with_item.save()
+
+ address_data = address_other_country.as_data()
+ config = AvataxConfiguration(
+ username_or_account="",
+ password_or_license="",
+ use_sandbox=False,
+ from_street_address=address_data.get("street_address_1"),
+ from_city=address_data.get("city"),
+ from_postal_code=address_data.get("postal_code"),
+ from_country=address_data.get("country"),
+ )
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+
+ # when
+ request_data = generate_request_data_from_checkout(
+ checkout_info, lines, config, tax_included=True
+ )
+
+ # then
+ addresses = request_data["createTransactionModel"]["addresses"]
+ assert "shipTo" not in addresses
+ assert "shipFrom" not in addresses
+ assert addresses["singleLocation"] == {
+ "line1": address_data.get("street_address_1"),
+ "line2": address_data.get("street_address_2"),
+ "city": address_data.get("city"),
+ "region": address_data.get("country_area"),
+ "country": address_data.get("country"),
+ "postalCode": address_data.get("postal_code"),
+ }
+
+
+@patch("saleor.plugins.avatax.cache.set")
+def test_get_checkout_tax_data_with_single_point(
+ mock_cache_set,
+ checkout_with_item,
+ warehouse,
+):
+ # given
+ address = Address.objects.create(
+ street_address_1="4371 Lucas Knoll Apt. 791",
+ city="BENNETTMOUTH",
+ postal_code="53-601",
+ country="PL",
+ )
+ warehouse.address = address
+ warehouse.is_private = False
+ warehouse.save()
+
+ checkout_with_item.collection_point = warehouse
+ checkout_with_item.save()
+
+ address_data = warehouse.address.as_data()
+
+ config = AvataxConfiguration(
+ username_or_account="",
+ password_or_license="",
+ use_sandbox=True,
+ from_street_address=address_data.get("street_address_1"),
+ from_city=address_data.get("city"),
+ from_postal_code=address_data.get("postal_code"),
+ from_country=address_data.get("country"),
+ )
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout_with_item)
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
+
+ # when
+ response = get_checkout_tax_data(
+ checkout_info, lines, tax_included=True, discounts=[], config=config
+ )
+
+ # then
+ assert len(response.get("addresses", [])) == 1
+
+
def test_taxes_need_new_fetch_uses_cached_data(checkout_with_item, address):
checkout_with_item.shipping_address = address
@@ -2667,7 +2813,8 @@ def test_get_checkout_line_tax_rate(
convert_to_shipping_method_data(
delivery_method,
delivery_method.channel_listings.first(),
- )
+ ),
+ address,
),
shipping_address=address,
billing_address=None,
@@ -2799,7 +2946,8 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(
convert_to_shipping_method_data(
delivery_method,
delivery_method.channel_listings.first(),
- )
+ ),
+ address,
),
shipping_address=address,
billing_address=None,
@@ -2828,7 +2976,6 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(
)
for checkout_line_info in lines
]
-
# then
assert tax_rates[0] == Decimal("0.23")
assert tax_rates[1] == Decimal("0.0")
@@ -3021,24 +3168,9 @@ def test_get_checkout_shipping_tax_rate(
checkout_with_item.shipping_address = address
checkout_with_item.shipping_method = shipping_zone.shipping_methods.get()
checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])
- delivery_method = checkout_with_item.shipping_method
lines, _ = fetch_checkout_lines(checkout_with_item)
- checkout_info = CheckoutInfo(
- checkout=checkout_with_item,
- delivery_method_info=get_delivery_method_info(
- convert_to_shipping_method_data(
- delivery_method,
- delivery_method.channel_listings.first(),
- )
- ),
- shipping_address=address,
- billing_address=None,
- channel=checkout_with_item.channel,
- user=None,
- valid_pick_up_points=[],
- all_shipping_methods=[],
- )
+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)
# when
tax_rate = manager.get_checkout_shipping_tax_rate(
@@ -3379,7 +3511,7 @@ def test_order_created(
plugin_conf = plugin_configuration(
from_street_address="Tęczowa 7",
from_city="WROCŁAW",
- from_postal_code="53-601",
+ from_postal_code="53-603",
from_country="PL",
shipping_tax_code="FR00001",
)
@@ -3414,11 +3546,11 @@ def test_order_created(
"addresses": {
"shipFrom": {
"line1": "Tęczowa 7",
- "line2": None,
+ "line2": "",
"city": "WROCŁAW",
"region": "",
"country": "PL",
- "postalCode": "53-601",
+ "postalCode": "53-603",
},
"shipTo": {
"line1": address.street_address_1,
@@ -3634,6 +3766,108 @@ def test_get_order_request_data_checks_when_taxes_are_included_to_price(
assert all([line for line in lines_data if line["taxIncluded"] is True])
+def test_get_order_request_data_uses_correct_address_for_cc(
+ order_with_lines,
+ site_settings,
+ address,
+ address_other_country,
+ warehouse,
+):
+ # given
+ site_settings.include_taxes_in_prices = True
+ site_settings.company_address = address
+ site_settings.save()
+
+ warehouse.is_private = False
+ warehouse.address = address_other_country
+ warehouse.save()
+
+ order_with_lines.collection_point = warehouse
+ order_with_lines.shipping_address = order_with_lines.billing_address.get_copy()
+ order_with_lines.shipping_method_name = None
+ order_with_lines.shipping_method = None
+ order_with_lines.save()
+
+ config = AvataxConfiguration(
+ username_or_account="",
+ password_or_license="",
+ use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
+ )
+
+ # when
+ request_data = get_order_request_data(order_with_lines, config, tax_included=True)
+
+ # then
+ expected_address_data = address_other_country.as_data()
+ addresses = request_data["createTransactionModel"]["addresses"]
+ assert "shipFrom" in addresses
+ assert "shipTo" in addresses
+ assert addresses["shipTo"] == {
+ "line1": expected_address_data.get("street_address_1"),
+ "line2": expected_address_data.get("street_address_2"),
+ "city": expected_address_data.get("city"),
+ "region": expected_address_data.get("country_area"),
+ "country": expected_address_data.get("country"),
+ "postalCode": expected_address_data.get("postal_code"),
+ }
+
+
+def test_get_order_request_data_uses_correct_address_for_cc_with_single_location(
+ order_with_lines,
+ site_settings,
+ address,
+ address_other_country,
+ warehouse,
+):
+ # given
+ site_settings.include_taxes_in_prices = True
+ site_settings.company_address = address
+ site_settings.save()
+
+ warehouse.is_private = False
+ warehouse.address = address_other_country
+ warehouse.save()
+
+ order_with_lines.collection_point = warehouse
+ order_with_lines.shipping_address = order_with_lines.billing_address.get_copy()
+ order_with_lines.shipping_method_name = None
+ order_with_lines.shipping_method = None
+ order_with_lines.save()
+
+ address_data = address_other_country.as_data()
+
+ config = AvataxConfiguration(
+ username_or_account="",
+ password_or_license="",
+ use_sandbox=False,
+ from_street_address=address_data.get("street_address_1"),
+ from_city=address_data.get("city"),
+ from_postal_code=address_data.get("postal_code"),
+ from_country=address_data.get("country"),
+ )
+ # when
+ request_data = get_order_request_data(order_with_lines, config, tax_included=True)
+
+ # then
+ addresses = request_data["createTransactionModel"]["addresses"]
+ assert "shipFrom" not in addresses
+ assert "shipTo" not in addresses
+ assert "singleLocation" in addresses
+ assert addresses["singleLocation"] == {
+ "line1": address_data.get("street_address_1"),
+ "line2": "",
+ "city": address_data.get("city"),
+ "region": address_data.get("country_area"),
+ "country": address_data.get("country"),
+ "postalCode": address_data.get("postal_code"),
+ }
+
+
def test_get_order_request_data_for_line_with_already_included_taxes_in_price(
order_with_lines, shipping_zone, site_settings, address_usa
):
@@ -4041,6 +4275,47 @@ def test_get_order_tax_data(
assert response == return_value
+@patch("saleor.plugins.avatax.cache.set")
+def test_get_order_tax_data_with_single_location(
+ mock_cache_set,
+ order_line,
+ warehouse,
+):
+ # given
+ address = Address.objects.create(
+ street_address_1="4371 Lucas Knoll Apt. 791",
+ city="BENNETTMOUTH",
+ postal_code="53-601",
+ country="PL",
+ )
+ warehouse.address = address
+ warehouse.is_private = False
+ warehouse.save()
+
+ order = order_line.order
+ order.collection_point = warehouse
+ order.save()
+
+ address_data = warehouse.address.as_data()
+
+ config = AvataxConfiguration(
+ username_or_account="",
+ password_or_license="",
+ use_sandbox=True,
+ from_street_address=address_data.get("street_address_1"),
+ from_city=address_data.get("city"),
+ from_postal_code=address_data.get("postal_code"),
+ from_country=address_data.get("country"),
+ )
+
+ # when
+ response = get_order_tax_data(order, config, tax_included=True)
+
+ # then
+ assert len(response.get("addresses", [])) == 1
+
+
def test_get_order_tax_data_empty_data(
order,
plugin_configuration,
@@ -4138,6 +4413,61 @@ def test_validate_order_not_shipping_required_no_shipping_method(order_line, add
assert response is True
+def test_validate_order_click_and_collect(order_line, address, warehouse):
+ # given
+ warehouse.is_private = False
+ warehouse.save(update_fields=["is_private"])
+ order = order_line.order
+ order.collection_point = warehouse
+ order.shipping_method = None
+ order.shipping_address = None
+ order.billing_address = address
+ order.save(
+ update_fields=[
+ "shipping_address",
+ "billing_address",
+ "shipping_method",
+ "collection_point",
+ ]
+ )
+
+ # when
+ response = _validate_order(order)
+
+ # then
+ assert response is True
+
+
+def test_validate_checkout_click_and_collect(
+ user_checkout_with_items_for_cc, address, warehouse
+):
+ # given
+ warehouse.is_private = False
+ warehouse.save(update_fields=["is_private"])
+ user_checkout_with_items_for_cc.collection_point = warehouse
+ user_checkout_with_items_for_cc.shipping_method = None
+ user_checkout_with_items_for_cc.shipping_address = None
+ user_checkout_with_items_for_cc.billing_address = address
+ user_checkout_with_items_for_cc.save(
+ update_fields=[
+ "shipping_address",
+ "billing_address",
+ "shipping_method",
+ "collection_point",
+ ]
+ )
+ lines_info, _ = fetch_checkout_lines(user_checkout_with_items_for_cc)
+ checkout_info = fetch_checkout_info(
+ user_checkout_with_items_for_cc, lines_info, [], get_plugins_manager()
+ )
+
+ # when
+ response = _validate_checkout(checkout_info, lines_info)
+
+ # then
+ assert response is True
+
+
def test_get_checkout_lines_data_sets_different_tax_code_for_zero_amount(
settings, channel_USD, plugin_configuration, checkout_with_item, avatax_config
):