# Copyright 2026 Stéphan Sainléger (Elabore) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, http from odoo.exceptions import AccessError, MissingError from odoo.http import request from odoo.addons.portal.controllers.portal import CustomerPortal from odoo.addons.portal.controllers.portal import pager as portal_pager PAGE_NAME = "Subscriptions" SESSION_HISTORY_KEY = "my_subscriptions_history" class PortalSubscription(CustomerPortal): """Expose ``sale.subscription`` records as read-only portal documents.""" def _prepare_home_portal_values(self, counters): """Add the subscription counter displayed on the portal home page. :param counters: list of counter names requested by the portal home. :return: the portal home values, with ``subscription_count`` added when it was requested. The count is ``0`` for users without read access so that the home entry stays hidden instead of raising. """ values = super()._prepare_home_portal_values(counters) if "subscription_count" in counters: subscription_model = request.env["sale.subscription"] values["subscription_count"] = ( subscription_model.search_count([]) if subscription_model.has_access("read") else 0 ) return values def _subscription_portal_invoices(self, subscription_sudo): """Return the subscription invoices the current visitor may read. Subscription invoices are created in ``sudo`` by ``subscription_oca``, so nothing guarantees the customer is allowed to read them: the portal rule of ``account.move`` requires a posted move the partner follows. Browsing the moves with the visitor's own environment and filtering on the effective access right keeps the detail page free of dead links. :param subscription_sudo: ``sale.subscription`` singleton, in sudo. :return: an ``account.move`` recordset, possibly empty, readable by the current user and restricted to posted moves. """ subscription_sudo.ensure_one() posted_invoices = subscription_sudo.invoice_ids.filtered( lambda move: move.state == "posted" ) return ( request.env["account.move"] .browse(posted_invoices.ids) ._filtered_access("read") ) def _subscription_get_page_view_values( self, subscription_sudo, access_token, **kwargs ): """Build the rendering values of the subscription detail page. :param subscription_sudo: ``sale.subscription`` singleton, in sudo. :param access_token: share token used to reach the page, or ``None``. :param kwargs: extra values forwarded to ``_get_page_view_values``. :return: dict of QWeb values, including the prev/next record browsing keys computed by the portal from the session history. """ values = { "page_name": PAGE_NAME, "subscription": subscription_sudo, "invoices": self._subscription_portal_invoices(subscription_sudo), } return self._get_page_view_values( subscription_sudo, access_token, values, SESSION_HISTORY_KEY, False, **kwargs, ) @http.route( ["/my/subscriptions", "/my/subscriptions/page/"], type="http", auth="user", website=True, ) def portal_my_subscriptions(self, page=1, sortby=None, **kw): """Render the paginated list of the current user's subscriptions. Record-level filtering is delegated to the portal ``ir.rule``, so the search domain stays empty on purpose. :param page: 1-based page number. :param sortby: key of ``searchbar_sortings``; defaults to the start date. :param kw: extra query string arguments, ignored. :return: the rendered list page, or a redirect to ``/my`` when the user has no read access on subscriptions. :raise KeyError: if ``sortby`` is not a known sorting key. """ subscription_model = request.env["sale.subscription"] if not subscription_model.has_access("read"): return request.redirect("/my") values = self._prepare_portal_layout_values() searchbar_sortings = { "date_start": {"label": _("Start Date"), "order": "date_start desc"}, "recurring_next_date": { "label": _("Next Invoice Date"), "order": "recurring_next_date desc", }, "code": {"label": _("Reference"), "order": "code desc"}, } if not sortby: sortby = "date_start" order = searchbar_sortings[sortby]["order"] subscription_count = subscription_model.search_count([]) pager = portal_pager( url="/my/subscriptions", url_args={"sortby": sortby}, total=subscription_count, page=page, step=self._items_per_page, ) subscriptions = subscription_model.search( [], order=order, limit=self._items_per_page, offset=pager["offset"] ) request.session[SESSION_HISTORY_KEY] = subscriptions.ids[:100] values.update( { "subscriptions": subscriptions, "page_name": PAGE_NAME, "pager": pager, "default_url": "/my/subscriptions", "searchbar_sortings": searchbar_sortings, "sortby": sortby, } ) return request.render("subscription_oca_portal.portal_my_subscriptions", values) @http.route( ["/my/subscriptions/"], type="http", auth="public", website=True, ) def portal_my_subscription_detail(self, subscription_id, access_token=None, **kw): """Render one subscription, by ownership or by share token. :param subscription_id: database id of the subscription. :param access_token: share token allowing access without ownership. :param kw: extra query string arguments forwarded to the view values. :return: the rendered detail page, or a redirect to ``/my`` when the record is missing or not accessible. """ try: subscription_sudo = self._document_check_access( "sale.subscription", subscription_id, access_token ) except (AccessError, MissingError): return request.redirect("/my") values = self._subscription_get_page_view_values( subscription_sudo, access_token, **kw ) return request.render( "subscription_oca_portal.portal_subscription_page", values )