%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2025 Best Practical Solutions, LLC
%#                                          <sales@bestpractical.com>
%#
%# (Except where explicitly superseded by other copyright notices)
%#
%#
%# LICENSE:
%#
%# This work is made available to you under the terms of Version 2 of
%# the GNU General Public License. A copy of that license should have
%# been provided with this software, but in any event can be snarfed
%# from www.gnu.org.
%#
%# This work 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
%# General Public License for more details.
%#
%# You should have received a copy of the GNU General Public License
%# along with this program; if not, write to the Free Software
%# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
%# 02110-1301 or visit their web page on the internet at
%# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
%#
%#
%# CONTRIBUTION SUBMISSION POLICY:
%#
%# (The following paragraph is not intended to limit the rights granted
%# to you to modify and distribute this software under the terms of
%# the GNU General Public License and is only of importance to you if
%# you choose to contribute your changes and enhancements to the
%# community by submitting them to Best Practical Solutions, LLC.)
%#
%# By intentionally submitting any modifications, corrections or
%# derivatives to this work, or any other work intended for use with
%# Request Tracker, to Best Practical Solutions, LLC, you confirm that
%# you are the copyright holder for those contributions and you grant
%# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
%# royalty-free, perpetual, license to use, copy, create derivative
%# works based on those contributions, and sublicense and distribute
%# those contributions and any derivatives thereof.
%#
%# END BPS TAGGED BLOCK }}}
<%args>
$Ticket
$ShowRelatedTickets => 10
$HTMXLoad => 0
</%args>
<%init>
my $target_assets = $Ticket->Links("Base")->Clone;
$target_assets->Limit(
    FIELD    => "Target",
    OPERATOR => "STARTSWITH",
    VALUE    => RT::URI::asset->LocalURIPrefix,
);
my $base_assets = $Ticket->Links("Target")->Clone;
$base_assets->Limit(
    FIELD    => "Base",
    OPERATOR => "STARTSWITH",
    VALUE    => RT::URI::asset->LocalURIPrefix,
);

my @linked_assets;
push @linked_assets, grep { defined } map { $_->TargetURI->IsLocal }
    @{ $target_assets->ItemsArrayRef };
push @linked_assets, grep { defined } map { $_->BaseURI->IsLocal }
    @{ $base_assets->ItemsArrayRef };

my $asset_queue;
if (RT->Config->Get('AssetQueues')) {
    $asset_queue = 1 if grep {$_ eq $Ticket->QueueObj->__Value('Name')} @{RT->Config->Get('AssetQueues')}
} else {
    $asset_queue = 0;
}
return unless @linked_assets or ($Ticket->CurrentUserHasRight("ModifyTicket")
                                     and $asset_queue);

my $assets = RT::Assets->new( $session{CurrentUser} );
$assets->OrderBy( FIELD => "Name", ORDER => "ASC" );
if ( @linked_assets ) {
    $assets->Limit(
        FIELD       => "id",
        OPERATOR    => "IN",
        VALUE       => \@linked_assets,
    );
}

my $Format = RT->Config->Get("AssetSummaryFormat") || q[
    '<a href="__WebHomePath__/Asset/Display.html?id=__id__">__Name__</a>/TITLE:Name',
    Description,
    Status,
    Catalog,
];

$m->callback(
    CallbackName    => 'ModifyCollection',
    Ticket          => $Ticket,
    Assets          => $assets,
    Format          => \$Format,
);


</%init>
<&| /Widgets/TitleBox,
    title => loc('Assets'),
    class => 'ticket-assets',
    title_class => "inverse",
    htmx_load => $HTMXLoad,
    &>

<form hx-post="<% RT->Config->Get("WebPath") %>/Helpers/TicketUpdate" hx-swap="none" enctype="multipart/form-data">
  <input type="hidden" name="id" value="<% $Ticket->id %>">

% $m->callback( CallbackName => "Start", Ticket => $Ticket, Assets => $assets );

  <div id="assets-accordion" class="rt-accordion accordion accordion-flush">
% my $display_path = $session{'CurrentUser'}->Privileged ? 'Asset' : 'SelfService/Asset';

% while (my $asset = $assets->Next) {
    <div class="accordion-item">
      <span class="accordion-title collapsed toggle" data-bs-toggle="collapse" data-bs-target="#accordion-asset-<% $asset->id %>" aria-expanded="false" aria-controls="accordion-asset-<% $asset->id %>" id="accordion-asset-<% $asset->id %>-title" >
        <a href="<% RT->Config->Get('WebPath') %>/<% $display_path %>/Display.html?id=<% $asset->id %>"><&|/l, $asset->id, $asset->Name &>#[_1]: [_2]</&></a>


%# show asset actions menu
% my $request_path = $HTML::Mason::Commands::r->path_info;
% $request_path =~ s!/{2,}!/!g;
% my $page = RT::Interface::Web::Menu->new();
% require RT::Interface::Web::MenuBuilder;
% RT::Interface::Web::MenuBuilder::_BuildAssetMenuActionSubmenu( $request_path, PageWidgets(), $page, Asset => $asset );
% $m->callback( CallbackName => "ActionsMenu", Ticket => $Ticket, Asset => $asset, Menu => $page );

        <& /Elements/Menu, menu => $page, id => 'asset-'.$asset->id.'-actions-menu', parent_id => 'asset-'.$asset->id &>
<%perl>
if ($Ticket->CurrentUserHasRight("ModifyTicket")) {
    my $targets = $asset->Links("Target")->Clone;
    $targets->Limit(
        FIELD   => "LocalBase",
        VALUE   => $Ticket->id,
    );
    my $bases = $asset->Links("Base")->Clone;
    $bases->Limit(
        FIELD   => "LocalTarget",
        VALUE   => $Ticket->id,
    );

    my %params;
    $params{join("-", "DeleteLink", "", $_->Type, $_->Target)} = 1
        for @{ $targets->ItemsArrayRef };
    $params{join("-", "DeleteLink", $_->Base, $_->Type, "")} = 1
        for @{ $bases->ItemsArrayRef };

    my $delete_url = RT->Config->Get("WebPath")
        . "/Helpers/TicketUpdate?"
        . $m->comp("/Elements/QueryString", id => $Ticket->id, %params);
</%perl>

            <div class="unlink-asset">
              <a href="#" hx-post="<% $delete_url %>" hx-trigger="click" hx-swap="none" class="unlink-asset btn btn-primary"><% loc('Unlink') %></a>
            </div>

% }

      </span>
      <div id="accordion-asset-<% $asset->id %>" class="accordion-content collapse" aria-labelledby="accordion-asset-<% $asset->id %>-title">
        <& /Elements/ShowRecord,
            Object      => $asset,
            Format      => $Format,
            TrustFormat => 1,
            &>
% $m->callback( CallbackName => "BeforeTickets", Ticket => $Ticket, Asset => $asset );
<%perl>
if ($ShowRelatedTickets) {
    my %search = (
        Query   => "id != '@{[$Ticket->id]}' AND LinkedTo = 'asset:@{[$asset->id]}'",
        OrderBy => "LastUpdated",
        Order   => "DESC",
    );
    my $url = RT->Config->Get("WebPath")
            . "/Search/Results.html?"
            . $m->comp("/Elements/QueryString", %search);
</%perl>

        <div class="related-tickets row mt-2">
          <div class="label col-3">
            <a href="<% $url %>">
              <&|/l, $ShowRelatedTickets &>[_1] most recently updated related tickets</&>
            </a>
          </div>
          <div class="value col-9">
            <& /Elements/CollectionList,
                %search,
                Class             => "RT::Tickets",
                Format            => RT->Config->Get("AssetSummaryRelatedTicketsFormat"),
                Rows              => $ShowRelatedTickets,
                ShowHeader        => 0,
                AllowSorting      => 0,
                ShowNavigation    => 0,
                InlineEdit        => 0,
            &>
          </div>
        </div>
% }

% $m->callback( CallbackName => "PerAsset", Ticket => $Ticket, Asset => $asset );

      </div>
    </div>
% }
  </div>

% if ($Ticket->CurrentUserHasRight("ModifyTicket")) {
  <div class="add-asset">
    <label><&|/l&>Add an asset to this ticket:</&></label>
    <div class="row mt-2">
      <div class="col ms-3">
        <input data-autocomplete="Assets" class="form-control mb-2" size="10" name="<% $Ticket->id %>-RefersTo" placeholder="<&|/l&>Asset #</&>" data-autocomplete-exclude="<% join(',', @linked_assets) |n %>" type="text">
      </div>
      <div class="col">
        <button type="submit" name="AddAsset" value="Add" class="btn btn-primary mb-2">Add</button>
      </div>
    </div>
  </div>
% }

% $m->callback( CallbackName => "End", Ticket => $Ticket, Assets => $assets );

</form>

</&>

<%attr>
directly_accessible => 1
</%attr>
