passerelle-imio-extra-fees/passerelle_imio_extra_fees/models.py

57 lines
2.1 KiB
Python

# passerelle-imio-extra-fees - compute basket extra fees
# Copyright (C) 2017 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from passerelle.base.models import BaseResource
from passerelle.utils.api import endpoint
class ExtraFees(BaseResource):
category = _('Misc')
class Meta:
verbose_name = _('Extra Fees')
@classmethod
def get_connector_slug(cls):
return 'extra-fees'
@endpoint(methods=['post'])
def compute(self, request, **kwargs):
data = json.loads(request.body)
nb_documents = 0
# Balaie chaque elem du panier.
for basket_item in data['data']:
nb_letter = 0
postage_fee = Decimal('0.74')
max_doc_in_letter = 5
try:
nb_documents += int(basket_item['request_data']['nb_documents'])
if Decimal(basket_item['request_data']['country_price']) > postage_fee:
postage_fee = Decimal(basket_item['request_data']['country_price'])
except KeyError:
# basket item not associated with any document, no fee
pass
nb_letter = int(nb_documents / max_doc_in_letter) + (((nb_documents % max_doc_in_letter) > 0) and 1 or 0)
# compute fee
postage_fee = nb_letter * postage_fee
return {'data': [{'subject': force_text(_('Postage')), 'amount': str(postage_fee)}]}