diff --git a/delivery_ups_hibou/__init__.py b/delivery_ups_hibou/__init__.py
new file mode 100644
index 00000000..0650744f
--- /dev/null
+++ b/delivery_ups_hibou/__init__.py
@@ -0,0 +1 @@
+from . import models
diff --git a/delivery_ups_hibou/__manifest__.py b/delivery_ups_hibou/__manifest__.py
new file mode 100644
index 00000000..67931660
--- /dev/null
+++ b/delivery_ups_hibou/__manifest__.py
@@ -0,0 +1,18 @@
+{
+ 'name': 'Hibou UPS Shipping',
+ 'version': '12.0.1.0.0',
+ 'category': 'Stock',
+ 'author': "Hibou Corp.",
+ 'license': 'AGPL-3',
+ 'website': 'https://hibou.io/',
+ 'depends': [
+ 'delivery_ups',
+ 'delivery_hibou',
+ ],
+ 'data': [
+ ],
+ 'demo': [
+ ],
+ 'installable': True,
+ 'application': False,
+ }
diff --git a/delivery_ups_hibou/models/__init__.py b/delivery_ups_hibou/models/__init__.py
new file mode 100644
index 00000000..735db17b
--- /dev/null
+++ b/delivery_ups_hibou/models/__init__.py
@@ -0,0 +1,2 @@
+from . import delivery_ups
+from . import ups_request_patch
diff --git a/delivery_ups_hibou/models/delivery_ups.py b/delivery_ups_hibou/models/delivery_ups.py
new file mode 100644
index 00000000..8285cdd6
--- /dev/null
+++ b/delivery_ups_hibou/models/delivery_ups.py
@@ -0,0 +1,218 @@
+from odoo import api, fields, models, _
+from odoo.exceptions import UserError, ValidationError
+from odoo.addons.delivery_ups.models.ups_request import UPSRequest, Package
+from odoo.tools import pdf
+
+
+class ProviderUPS(models.Model):
+ _inherit = 'delivery.carrier'
+
+ def _get_ups_is_third_party(self, order=None, picking=None):
+ third_party_account = self.get_third_party_account(order=order, picking=picking)
+ if third_party_account:
+ if not third_party_account.delivery_type == 'ups':
+ raise ValidationError('Non-UPS Shipping Account indicated during UPS shipment.')
+ return True
+ if order and self.ups_bill_my_account and order.ups_carrier_account:
+ return True
+ return False
+
+ def _get_ups_account_number(self, order=None, picking=None):
+ """
+ Common hook to customize what UPS Account number to use.
+ :return: UPS Account Number
+ """
+ # Provided by Hibou Odoo Suite `delivery_hibou`
+ third_party_account = self.get_third_party_account(order=order, picking=picking)
+ if third_party_account:
+ if not third_party_account.delivery_type == 'ups':
+ raise ValidationError('Non-UPS Shipping Account indicated during UPS shipment.')
+ return third_party_account.name
+ if order and order.ups_carrier_account:
+ return order.ups_carrier_account
+ if picking and picking.sale_id.ups_carrier_account:
+ return picking.sale_id.ups_carrier_account
+ return self.ups_shipper_number
+
+ def _get_ups_carrier_account(self, picking):
+ # 3rd party billing should return False if not used.
+ account = self._get_ups_account_number(picking=picking)
+ return account if account != self.ups_shipper_number else False
+
+ """
+ Overrides to use Hibou Delivery methods to get shipper etc. and to add 'transit_days' to result.
+ """
+ def ups_rate_shipment(self, order):
+ superself = self.sudo()
+ srm = UPSRequest(self.log_xml, superself.ups_username, superself.ups_passwd, superself.ups_shipper_number, superself.ups_access_number, self.prod_environment)
+ ResCurrency = self.env['res.currency']
+ max_weight = self.ups_default_packaging_id.max_weight
+ packages = []
+ total_qty = 0
+ total_weight = 0
+ for line in order.order_line.filtered(lambda line: not line.is_delivery):
+ total_qty += line.product_uom_qty
+ total_weight += line.product_id.weight * line.product_qty
+
+ if max_weight and total_weight > max_weight:
+ total_package = int(total_weight / max_weight)
+ last_package_weight = total_weight % max_weight
+
+ for seq in range(total_package):
+ packages.append(Package(self, max_weight))
+ if last_package_weight:
+ packages.append(Package(self, last_package_weight))
+ else:
+ packages.append(Package(self, total_weight))
+
+ shipment_info = {
+ 'total_qty': total_qty # required when service type = 'UPS Worldwide Express Freight'
+ }
+
+ if self.ups_cod:
+ cod_info = {
+ 'currency': order.partner_id.country_id.currency_id.name,
+ 'monetary_value': order.amount_total,
+ 'funds_code': self.ups_cod_funds_code,
+ }
+ else:
+ cod_info = None
+
+ # Hibou Delivery
+ shipper_company = self.get_shipper_company(order=order)
+ shipper_warehouse = self.get_shipper_warehouse(order=order)
+ recipient = self.get_recipient(order=order)
+ date_planned = None
+ if self.env.context.get('date_planned'):
+ date_planned = self.env.context.get('date_planned')
+
+ check_value = srm.check_required_value(shipper_company, shipper_warehouse, recipient, order=order)
+ if check_value:
+ return {'success': False,
+ 'price': 0.0,
+ 'error_message': check_value,
+ 'warning_message': False}
+
+ ups_service_type = order.ups_service_type or self.ups_default_service_type
+ result = srm.get_shipping_price(
+ shipment_info=shipment_info, packages=packages, shipper=shipper_company, ship_from=shipper_warehouse,
+ ship_to=recipient, packaging_type=self.ups_default_packaging_id.shipper_package_code, service_type=ups_service_type,
+ saturday_delivery=self.ups_saturday_delivery, cod_info=cod_info, date_planned=date_planned)
+
+ if result.get('error_message'):
+ return {'success': False,
+ 'price': 0.0,
+ 'error_message': _('Error:\n%s') % result['error_message'],
+ 'warning_message': False}
+
+ if order.currency_id.name == result['currency_code']:
+ price = float(result['price'])
+ else:
+ quote_currency = ResCurrency.search([('name', '=', result['currency_code'])], limit=1)
+ price = quote_currency._convert(
+ float(result['price']), order.currency_id, order.company_id, order.date_order or fields.Date.today())
+
+ # Hibou Delivery
+ if self._get_ups_is_third_party(order=order):
+ # Don't show delivery amount, if ups bill my account option is true
+ price = 0.0
+
+ return {'success': True,
+ 'price': price,
+ 'transit_days': result.get('transit_days', 0),
+ 'error_message': False,
+ 'warning_message': False}
+
+ def ups_send_shipping(self, pickings):
+ res = []
+ superself = self.sudo()
+ srm = UPSRequest(self.log_xml, superself.ups_username, superself.ups_passwd, superself.ups_shipper_number, superself.ups_access_number, self.prod_environment)
+ ResCurrency = self.env['res.currency']
+ for picking in pickings:
+ # Hibou Delivery
+ shipper_company = superself.get_shipper_company(picking=picking)
+ shipper_warehouse = superself.get_shipper_warehouse(picking=picking)
+ recipient = superself.get_recipient(picking=picking)
+
+ packages = []
+ package_names = []
+ if picking.package_ids:
+ # Create all packages
+ for package in picking.package_ids:
+ packages.append(Package(self, package.shipping_weight, quant_pack=package.packaging_id, name=package.name))
+ package_names.append(package.name)
+ # Create one package with the rest (the content that is not in a package)
+ if picking.weight_bulk:
+ packages.append(Package(self, picking.weight_bulk))
+
+ invoice_line_total = 0
+ for move in picking.move_lines:
+ invoice_line_total += picking.company_id.currency_id.round(move.product_id.lst_price * move.product_qty)
+
+ shipment_info = {
+ 'description': superself.get_order_name(picking=picking),
+ 'total_qty': sum(sml.qty_done for sml in picking.move_line_ids),
+ 'ilt_monetary_value': '%d' % invoice_line_total,
+ 'itl_currency_code': self.env.user.company_id.currency_id.name,
+ 'phone': recipient.mobile or recipient.phone,
+ }
+ if picking.sale_id and picking.sale_id.carrier_id != picking.carrier_id:
+ ups_service_type = picking.carrier_id.ups_default_service_type or picking.ups_service_type or superself.ups_default_service_type
+ else:
+ ups_service_type = picking.ups_service_type or superself.ups_default_service_type
+
+ # Hibou Delivery
+ ups_carrier_account = superself._get_ups_carrier_account(picking)
+
+ if picking.carrier_id.ups_cod:
+ cod_info = {
+ 'currency': picking.partner_id.country_id.currency_id.name,
+ 'monetary_value': picking.sale_id.amount_total,
+ 'funds_code': superself.ups_cod_funds_code,
+ }
+ else:
+ cod_info = None
+
+ check_value = srm.check_required_value(shipper_company, shipper_warehouse, recipient, picking=picking)
+ if check_value:
+ raise UserError(check_value)
+
+ package_type = picking.package_ids and picking.package_ids[0].packaging_id.shipper_package_code or self.ups_default_packaging_id.shipper_package_code
+ result = srm.send_shipping(
+ shipment_info=shipment_info, packages=packages, shipper=shipper_company, ship_from=shipper_warehouse,
+ ship_to=recipient, packaging_type=package_type, service_type=ups_service_type, label_file_type=self.ups_label_file_type, ups_carrier_account=ups_carrier_account,
+ saturday_delivery=picking.carrier_id.ups_saturday_delivery, cod_info=cod_info)
+ if result.get('error_message'):
+ raise UserError(result['error_message'])
+
+ order = picking.sale_id
+ company = order.company_id or picking.company_id or self.env.user.company_id
+ currency_order = picking.sale_id.currency_id
+ if not currency_order:
+ currency_order = picking.company_id.currency_id
+
+ if currency_order.name == result['currency_code']:
+ price = float(result['price'])
+ else:
+ quote_currency = ResCurrency.search([('name', '=', result['currency_code'])], limit=1)
+ price = quote_currency._convert(
+ float(result['price']), currency_order, company, order.date_order or fields.Date.today())
+
+ package_labels = []
+ for track_number, label_binary_data in result.get('label_binary_data').items():
+ package_labels = package_labels + [(track_number, label_binary_data)]
+
+ carrier_tracking_ref = "+".join([pl[0] for pl in package_labels])
+ logmessage = _("Shipment created into UPS
"
+ "Tracking Numbers: %s
"
+ "Packages: %s") % (carrier_tracking_ref, ','.join(package_names))
+ if superself.ups_label_file_type != 'GIF':
+ attachments = [('LabelUPS-%s.%s' % (pl[0], superself.ups_label_file_type), pl[1]) for pl in package_labels]
+ if superself.ups_label_file_type == 'GIF':
+ attachments = [('LabelUPS.pdf', pdf.merge_pdf([pl[1] for pl in package_labels]))]
+ picking.message_post(body=logmessage, attachments=attachments)
+ shipping_data = {
+ 'exact_price': price,
+ 'tracking_number': carrier_tracking_ref}
+ res = res + [shipping_data]
+ return res
diff --git a/delivery_ups_hibou/models/ups_request_patch.py b/delivery_ups_hibou/models/ups_request_patch.py
new file mode 100644
index 00000000..3104662e
--- /dev/null
+++ b/delivery_ups_hibou/models/ups_request_patch.py
@@ -0,0 +1,112 @@
+import suds
+from odoo.addons.delivery_ups.models.ups_request import UPSRequest
+
+SUDS_VERSION = suds.__version__
+
+
+def patched_get_shipping_price(self, shipment_info, packages, shipper, ship_from, ship_to, packaging_type, service_type,
+ saturday_delivery, cod_info, date_planned=False):
+ client = self._set_client(self.rate_wsdl, 'Rate', 'RateRequest')
+
+ request = client.factory.create('ns0:RequestType')
+ request.RequestOption = 'Rate'
+
+ classification = client.factory.create('ns2:CodeDescriptionType')
+ classification.Code = '00' # Get rates for the shipper account
+ classification.Description = 'Get rates for the shipper account'
+
+ namespace = 'ns2'
+ shipment = client.factory.create('{}:ShipmentType'.format(namespace))
+
+ # Hibou Delivery
+ if date_planned:
+ if not isinstance(date_planned, str):
+ date_planned = str(date_planned)
+ shipment.DeliveryTimeInformation = client.factory.create('{}:TimeInTransitRequestType'.format(namespace))
+ shipment.DeliveryTimeInformation.Pickup = client.factory.create('{}:PickupType'.format(namespace))
+ shipment.DeliveryTimeInformation.Pickup.Date = date_planned.split(' ')[0]
+ # End
+
+ for package in self.set_package_detail(client, packages, packaging_type, namespace, ship_from, ship_to, cod_info):
+ shipment.Package.append(package)
+
+ shipment.Shipper.Name = shipper.name or ''
+ shipment.Shipper.Address.AddressLine = [shipper.street or '', shipper.street2 or '']
+ shipment.Shipper.Address.City = shipper.city or ''
+ shipment.Shipper.Address.PostalCode = shipper.zip or ''
+ shipment.Shipper.Address.CountryCode = shipper.country_id.code or ''
+ if shipper.country_id.code in ('US', 'CA', 'IE'):
+ shipment.Shipper.Address.StateProvinceCode = shipper.state_id.code or ''
+ shipment.Shipper.ShipperNumber = self.shipper_number or ''
+ # shipment.Shipper.Phone.Number = shipper.phone or ''
+
+ shipment.ShipFrom.Name = ship_from.name or ''
+ shipment.ShipFrom.Address.AddressLine = [ship_from.street or '', ship_from.street2 or '']
+ shipment.ShipFrom.Address.City = ship_from.city or ''
+ shipment.ShipFrom.Address.PostalCode = ship_from.zip or ''
+ shipment.ShipFrom.Address.CountryCode = ship_from.country_id.code or ''
+ if ship_from.country_id.code in ('US', 'CA', 'IE'):
+ shipment.ShipFrom.Address.StateProvinceCode = ship_from.state_id.code or ''
+ # shipment.ShipFrom.Phone.Number = ship_from.phone or ''
+
+ shipment.ShipTo.Name = ship_to.name or ''
+ shipment.ShipTo.Address.AddressLine = [ship_to.street or '', ship_to.street2 or '']
+ shipment.ShipTo.Address.City = ship_to.city or ''
+ shipment.ShipTo.Address.PostalCode = ship_to.zip or ''
+ shipment.ShipTo.Address.CountryCode = ship_to.country_id.code or ''
+ if ship_to.country_id.code in ('US', 'CA', 'IE'):
+ shipment.ShipTo.Address.StateProvinceCode = ship_to.state_id.code or ''
+ # shipment.ShipTo.Phone.Number = ship_to.phone or ''
+ if not ship_to.commercial_partner_id.is_company:
+ shipment.ShipTo.Address.ResidentialAddressIndicator = suds.null()
+
+ shipment.Service.Code = service_type or ''
+ shipment.Service.Description = 'Service Code'
+ if service_type == "96":
+ shipment.NumOfPieces = int(shipment_info.get('total_qty'))
+
+ if saturday_delivery:
+ shipment.ShipmentServiceOptions.SaturdayDeliveryIndicator = saturday_delivery
+ else:
+ shipment.ShipmentServiceOptions = ''
+
+ shipment.ShipmentRatingOptions.NegotiatedRatesIndicator = 1
+
+ try:
+ # Get rate using for provided detail
+ response = client.service.ProcessRate(Request=request, CustomerClassification=classification, Shipment=shipment)
+
+ # Check if ProcessRate is not success then return reason for that
+ if response.Response.ResponseStatus.Code != "1":
+ return self.get_error_message(response.Response.ResponseStatus.Code,
+ response.Response.ResponseStatus.Description)
+
+ result = {}
+ result['currency_code'] = response.RatedShipment[0].TotalCharges.CurrencyCode
+
+ # Some users are qualified to receive negotiated rates
+ negotiated_rate = 'NegotiatedRateCharges' in response.RatedShipment[0] and response.RatedShipment[
+ 0].NegotiatedRateCharges.TotalCharge.MonetaryValue or None
+
+ result['price'] = negotiated_rate or response.RatedShipment[0].TotalCharges.MonetaryValue
+
+ # Hibou Delivery
+ if hasattr(response.RatedShipment[0], 'GuaranteedDelivery') and hasattr(response.RatedShipment[0].GuaranteedDelivery, 'BusinessDaysInTransit'):
+ result['transit_days'] = int(response.RatedShipment[0].GuaranteedDelivery.BusinessDaysInTransit)
+ # End
+
+ return result
+
+ except suds.WebFault as e:
+ # childAtPath behaviour is changing at version 0.6
+ prefix = ''
+ if SUDS_VERSION >= "0.6":
+ prefix = '/Envelope/Body/Fault'
+ return self.get_error_message(
+ e.document.childAtPath(prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Code').getText(),
+ e.document.childAtPath(prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Description').getText())
+ except IOError as e:
+ return self.get_error_message('0', 'UPS Server Not Found:\n%s' % e)
+
+
+UPSRequest.get_shipping_price = patched_get_shipping_price