HEX
Server: Microsoft-IIS/10.0
System: Windows NT ITPWINWEBSVR22 10.0 build 20348 (Windows Server 2022) AMD64
User: www.conferencesearch.co.uk (0)
PHP: 8.3.30
Disabled: NONE
Upload Files
File: D:/web/hyperflight/inxpress/inxpress-v2.asp
<%@ Language="VBScript" %>
<%
Option Explicit

'========================
' Helper functions
'========================
Function IIf(expr, truePart, falsePart)
    If expr Then IIf = truePart Else IIf = falsePart
End Function

Function FmtNum(val)
    Dim n
    If IsNull(val) Or Trim(val & "") = "" Then
        FmtNum = ""
        Exit Function
    End If
    On Error Resume Next
    n = CDbl(val)
    If Err.Number <> 0 Then
        Err.Clear
        On Error GoTo 0
        FmtNum = ""
        Exit Function
    End If
    On Error GoTo 0
    If n = 0 Then
        FmtNum = ""
    Else
        FmtNum = FormatNumber(n, 2, -1, 0, -1)
    End If
End Function

Function NumVal(v)
    If IsNull(v) Or Trim(v & "") = "" Then
        NumVal = 0
    Else
        On Error Resume Next
        NumVal = CDbl(v)
        If Err.Number <> 0 Then
            NumVal = 0
            Err.Clear
        End If
        On Error GoTo 0
    End If
End Function

' SAFE HTML 2.0:
' Always coerce variant -> string first with Trim(var & "")
' Then HTML-encode.
Function SafeHTML(val)
    Dim tmp
    tmp = Trim(val & "")
    SafeHTML = Server.HTMLEncode(tmp)
End Function

Function CleanServiceType(txt)
    Dim s
    s = Trim(txt & "")
    If Right(s, 10) = " - Package" Then
        s = Left(s, Len(s) - 10)
    End If
    CleanServiceType = Server.HTMLEncode(s)
End Function

Function CountryFlag(code)
    Dim c
    c = Trim(code & "")
    If c = "" Then
        CountryFlag = ""
        Exit Function
    End If
    c = UCase(c)
    CountryFlag = "<img src='/common/geoip/flags/" & c & ".svg' alt='" & c & _
        "' style='width:20px;height:14px;border:1px solid #ccc;margin-right:4px;vertical-align:middle;'>"
End Function

Response.Expires = -1
Response.Buffer = True

'========================
' Config / DB connection
'========================
Const PAGE_SIZE = 10000
Const DSN = "MySQL_hyperflight"

Dim conn : Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "DSN=" & DSN

'========================
' Filters / sorting
'========================
Dim searchText, carrierSel, invoiceSel, countrySel
Dim sortField, sortDir
Dim missingOrders, duplicateRefs

searchText    = Trim(Request("search"))
carrierSel    = Trim(Request("carrier"))
invoiceSel    = Trim(Request("invoice"))
countrySel    = Trim(Request("country"))
sortField     = Trim(Request("sort"))
sortDir       = UCase(Trim(Request("dir")))
missingOrders = (Request("missingorders") = "1")
duplicateRefs = (Request("duplicates") = "1")

If sortField = "" Then sortField = "shipment_id"
If sortDir <> "DESC" Then sortDir = "ASC"

'========================
' WHERE clause
'========================
Dim whereSQL : whereSQL = " WHERE 1=1"

If searchText <> "" Then
    whereSQL = whereSQL & " AND (s.Reference LIKE '%" & Replace(searchText,"'","''") & _
        "%' OR s.ReceiverName LIKE '%" & Replace(searchText,"'","''") & "%')"
End If

If carrierSel <> "" Then
    whereSQL = whereSQL & " AND s.Carrier='" & Replace(carrierSel,"'","''") & "'"
End If

If invoiceSel <> "" Then
    whereSQL = whereSQL & " AND s.InvoiceNumber='" & Replace(invoiceSel,"'","''") & "'"
End If

If countrySel <> "" Then
    whereSQL = whereSQL & " AND s.DestCountry='" & Replace(countrySel,"'","''") & "'"
End If

If missingOrders Then
    whereSQL = whereSQL & " AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.OrderNo = s.Reference)"
End If

If duplicateRefs Then
    whereSQL = whereSQL & _
      " AND s.Reference<>'' AND s.Reference IN (" & _
      "SELECT Reference FROM inxpress_shipments_parsed " & _
      "WHERE Reference<>'' GROUP BY Reference HAVING COUNT(*)>1)"
End If

'========================
' Main SQL (JOIN to inxpress_shipments)
'========================
Dim sql
sql = "SELECT s.*, " & _
      "d.ShipmentDetails AS ShipmentDetails, " & _
      "d.ReceiverAddress AS ReceiverAddress, " & _
      "d.PiecesWeightDimensionsZone AS PiecesWeightDimensionsZone, " & _
      "d.Charges AS DetailCharges, " & _
      "d.Total AS DetailTotal, " & _
      "d.invoice_number AS DetailInvoice " & _
      "FROM inxpress_shipments_parsed s " & _
      "LEFT JOIN inxpress_shipments d ON s.shipment_id = d.shipment_id " & _
      whereSQL & " ORDER BY s." & sortField & " " & sortDir & " LIMIT " & PAGE_SIZE

Dim rs : Set rs = conn.Execute(sql)

Dim totalCount
totalCount = conn.Execute("SELECT COUNT(*) FROM inxpress_shipments_parsed s" & whereSQL)(0)

' dropdown data
Dim rsC, rsI, rsCn
Set rsC  = conn.Execute("SELECT DISTINCT Carrier FROM inxpress_shipments_parsed ORDER BY Carrier")
Set rsI  = conn.Execute("SELECT DISTINCT InvoiceNumber FROM inxpress_shipments_parsed ORDER BY InvoiceNumber DESC")
Set rsCn = conn.Execute("SELECT DISTINCT DestCountry FROM inxpress_shipments_parsed ORDER BY DestCountry")

'========================
' Build dictionary of reference counts (for duplicate highlight)
'========================
Dim refCount : Set refCount = Server.CreateObject("Scripting.Dictionary")
If Not rs.EOF Then
    rs.MoveFirst
    Do Until rs.EOF
        Dim r
        r = Trim(rs("Reference") & "")
        If r <> "" Then
            If Not refCount.Exists(r) Then
                refCount.Add r, 1
            Else
                refCount(r) = refCount(r) + 1
            End If
        End If
        rs.MoveNext
    Loop
    rs.MoveFirst
End If

'========================
' Totals init
'========================
Dim totalBase, totalFuel, totalOther, totalNet, totalVAT, totalGrand
totalBase  = 0
totalFuel  = 0
totalOther = 0
totalNet   = 0
totalVAT   = 0
totalGrand = 0
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>InXpress Shipments</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body{padding:20px;}
.table-responsive{max-height:85vh;overflow-y:auto;}
.table thead th{position:sticky;top:0;background:#f8f9fa;z-index:10;}
.table-sm th,.table-sm td{padding:0.4rem 0.5rem;}
tfoot tr{position:sticky;bottom:0;background:#e9f7ef;z-index:5;}
tfoot td{font-weight:bold;border-top:2px solid #999;}
td.num,th.num{text-align:right;}
td.total,th.total{font-weight:bold;background:#f9f9f9;}
tr.duplicate-row td{background-color:#fff6c9!important;}
th a.sort{text-decoration:none;color:inherit;}
th.active-sort{background:#e0f0ff!important;color:#004085;}
th.active-sort.asc a.sort::after{content:" ▲";font-size:0.8em;}
th.active-sort.desc a.sort::after{content:" ▼";font-size:0.8em;}
.modal-lg{max-width:900px;width:90%;}
pre.modal-block{white-space:pre-wrap;font-family:inherit;margin-bottom:1rem;}
</style>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
function autoSubmitFilters(){
    document.getElementById('filterForm').submit();
}

function decodeAttr(str){
    if(!str) return "";
    return str.replace(/&#10;/g,"\n").trim();
}

function formatForModal(str){
    if(!str) return "";
    return str.replace(/;/g,"\n").replace(/\n{2,}/g,"\n").trim();
}

function showShipment(btn){
  const d = btn.dataset;

  const shipdet = decodeAttr(d.shipdet || "");
  const recv    = decodeAttr(d.recv    || "");
  const pieces  = decodeAttr(d.pieces  || "");
  const charges = decodeAttr(d.charges || "");

  document.getElementById('m_id').textContent       = d.id || "";
  document.getElementById('m_invoice').textContent  = d.invoice || "";
  document.getElementById('m_shipdet').textContent  = formatForModal(shipdet);
  document.getElementById('m_recv').textContent     = formatForModal(recv);
  document.getElementById('m_pieces').textContent   = formatForModal(pieces);
  document.getElementById('m_charges').textContent  = formatForModal(charges);
  document.getElementById('m_total').textContent    = d.total || "";

  var modal = new bootstrap.Modal(document.getElementById('shipmentModal'));
  modal.show();
}
</script>
</head>
<body>

<div class="container-fluid">
<h3 class="mb-3">InXpress Shipments</h3>

<form id="filterForm" class="row row-cols-lg-auto g-2 align-items-center mb-3" method="get">
  <div class="col">
    <input type="text" name="search" value="<%=SafeHTML(searchText)%>"
           class="form-control" placeholder="Search Reference or Receiver">
  </div>

  <div class="col">
    <select name="carrier" class="form-select" onchange="autoSubmitFilters()">
      <option value="">All Carriers</option>
      <%
      Do Until rsC.EOF
        Response.Write "<option value='" & SafeHTML(rsC("Carrier")) & "'"
        If carrierSel=rsC("Carrier") Then Response.Write " selected"
        Response.Write ">" & SafeHTML(rsC("Carrier")) & "</option>"
        rsC.MoveNext
      Loop
      rsC.Close
      %>
    </select>
  </div>

  <div class="col">
    <select name="invoice" class="form-select" onchange="autoSubmitFilters()">
      <option value="">All Invoices</option>
      <%
      Do Until rsI.EOF
        Response.Write "<option value='" & SafeHTML(rsI("InvoiceNumber")) & "'"
        If invoiceSel=rsI("InvoiceNumber") Then Response.Write " selected"
        Response.Write ">" & SafeHTML(rsI("InvoiceNumber")) & "</option>"
        rsI.MoveNext
      Loop
      rsI.Close
      %>
    </select>
  </div>

  <div class="col">
    <select name="country" class="form-select" onchange="autoSubmitFilters()">
      <option value="">All Countries</option>
      <%
      Do Until rsCn.EOF
        Response.Write "<option value='" & SafeHTML(rsCn("DestCountry")) & "'"
        If countrySel=rsCn("DestCountry") Then Response.Write " selected"
        Response.Write ">" & SafeHTML(rsCn("DestCountry")) & "</option>"
        rsCn.MoveNext
      Loop
      rsCn.Close
      %>
    </select>
  </div>

  <div class="col form-check">
    <input class="form-check-input" type="checkbox"
           name="missingorders" value="1" id="missingorders"
           onchange="autoSubmitFilters()"
           <%=IIf(missingOrders,"checked","")%>>
    <label class="form-check-label" for="missingorders">Missing Orders</label>
  </div>

  <div class="col form-check">
    <input class="form-check-input" type="checkbox"
           name="duplicates" value="1" id="duplicates"
           onchange="autoSubmitFilters()"
           <%=IIf(duplicateRefs,"checked","")%>>
    <label class="form-check-label" for="duplicates">Duplicate References</label>
  </div>

  <div class="col">
    <button class="btn btn-primary btn-sm">Filter</button>
    <a href="inxpress.asp" class="btn btn-secondary btn-sm">Reset</a>
  </div>
</form>

<div class="table-responsive">
<table class="table table-sm table-striped table-bordered align-middle">
  <thead class="table-light">
    <tr>
    <%
    Dim cols, headers
    cols    = Array("shipment_id","Carrier","ShipDate","Reference","ReceiverName","DestCountry","ServiceType","WeightKg","Length","BaseCharge","FuelSurcharge","OtherCharges","NetAmount","VATAmount","Total")
    headers = Array("ID","Carrier","Ship Date","Reference","Receiver","Country","Service Type","Weight","Length","Base (£)","Fuel (£)","Other (£)","Net (£)","VAT (£)","Total (£)")

    Dim i, fieldName, headerName, sortClass, numClass
    Dim linkDir, linkExtra, linkURL

    For i = 0 To UBound(cols)
        fieldName  = cols(i)
        headerName = headers(i)

        sortClass = ""
        If sortField = fieldName Then
            sortClass = "active-sort " & LCase(sortDir)
        End If

        numClass = ""
        If InStr(headerName,"£")>0 _
           Or fieldName="WeightKg" _
           Or fieldName="Length" _
           Or fieldName="shipment_id" Then
            numClass = "num"
        End If
        If fieldName = "Total" Then
            numClass = numClass & " total"
        End If

        If sortDir = "ASC" Then
            linkDir = "DESC"
        Else
            linkDir = "ASC"
        End If

        linkExtra = ""
        If missingOrders Then linkExtra = linkExtra & "&missingorders=1"
        If duplicateRefs Then linkExtra = linkExtra & "&duplicates=1"

        linkURL = "?sort=" & fieldName & _
                  "&dir=" & linkDir & _
                  "&search=" & Server.URLEncode(searchText) & _
                  "&carrier=" & Server.URLEncode(carrierSel) & _
                  "&invoice=" & Server.URLEncode(invoiceSel) & _
                  "&country=" & Server.URLEncode(countrySel) & _
                  linkExtra

        Response.Write "<th class='" & sortClass & " " & numClass & "'>"
        Response.Write "<a class='sort' href='" & linkURL & "'>" & headerName & "</a></th>"
    Next
    %>
    </tr>
  </thead>

  <tbody>
  <%
  If Not rs.EOF Then rs.MoveFirst
  Do Until rs.EOF

      ' "Other (£)" = Handling+Insurance+AreaSurcharge+ProcessingFee+ResidentialFee+OtherCharges
      Dim otherTotal
      otherTotal = NumVal(rs("Handling")) + _
                   NumVal(rs("Insurance")) + _
                   NumVal(rs("AreaSurcharge")) + _
                   NumVal(rs("ProcessingFee")) + _
                   NumVal(rs("ResidentialFee")) + _
                   NumVal(rs("OtherCharges"))

      ' running totals
      totalBase  = totalBase  + NumVal(rs("BaseCharge"))
      totalFuel  = totalFuel  + NumVal(rs("FuelSurcharge"))
      totalOther = totalOther + otherTotal
      totalNet   = totalNet   + NumVal(rs("NetAmount"))
      totalVAT   = totalVAT   + NumVal(rs("VATAmount"))
      totalGrand = totalGrand + NumVal(rs("Total"))

      ' duplicate highlighting (if not already filtered to just duplicates)
      Dim rowClass, thisRef
      thisRef = Trim(rs("Reference") & "")
      rowClass = ""
      If (Not duplicateRefs) Then
          If thisRef <> "" Then
              If refCount.Exists(thisRef) Then
                  If refCount(thisRef) > 1 Then
                      rowClass = " class=""duplicate-row"""
                  End If
              End If
          End If
      End If

      ' prep multiline modal data safely:
      Dim shipdet, recv, pieces, charges
      shipdet = SafeHTML(rs("ShipmentDetails"))
      shipdet = Replace(shipdet, """", "&quot;")
      shipdet = Replace(shipdet, vbCrLf, "&#10;")
      shipdet = Replace(shipdet, vbLf, "&#10;")

      recv = SafeHTML(rs("ReceiverAddress"))
      recv = Replace(recv, """", "&quot;")
      recv = Replace(recv, vbCrLf, "&#10;")
      recv = Replace(recv, vbLf, "&#10;")

      pieces = SafeHTML(rs("PiecesWeightDimensionsZone"))
      pieces = Replace(pieces, """", "&quot;")
      pieces = Replace(pieces, vbCrLf, "&#10;")
      pieces = Replace(pieces, vbLf, "&#10;")

      charges = SafeHTML(rs("DetailCharges"))
      charges = Replace(charges, """", "&quot;")
      charges = Replace(charges, vbCrLf, "&#10;")
      charges = Replace(charges, vbLf, "&#10;")

  %>
    <tr<%=rowClass%>>
      <td class="num">
        <button type="button"
                class="btn btn-link p-0 m-0"
                onclick="showShipment(this)"
                data-id="<%=rs("shipment_id")%>"
                data-invoice="<%=SafeHTML(rs("DetailInvoice"))%>"
                data-shipdet="<%=shipdet%>"
                data-recv="<%=recv%>"
                data-pieces="<%=pieces%>"
                data-charges="<%=charges%>"
                data-total="<%=FmtNum(rs("DetailTotal"))%>">
          <%=rs("shipment_id")%>
        </button>
      </td>

      <td><%=SafeHTML(rs("Carrier"))%></td>

      <td>
        <%
        If IsNull(rs("ShipDate")) Then
            Response.Write ""
        Else
            Response.Write Right("0" & Day(rs("ShipDate")),2) & "/" & _
                            Right("0" & Month(rs("ShipDate")),2) & "/" & _
                            Year(rs("ShipDate"))
        End If
        %>
      </td>

      <td><%=SafeHTML(rs("Reference"))%></td>
      <td><%=SafeHTML(rs("ReceiverName"))%></td>

      <td><%=CountryFlag(rs("DestCountry")) & SafeHTML(rs("DestCountry"))%></td>

      <td><%=CleanServiceType(rs("ServiceType"))%></td>

      <td class="num"><%=SafeHTML(rs("WeightKg"))%></td>
      <td class="num"><%=SafeHTML(rs("Length"))%></td>

      <td class="num"><%=FmtNum(rs("BaseCharge"))%></td>
      <td class="num"><%=FmtNum(rs("FuelSurcharge"))%></td>
      <td class="num"><%=FmtNum(otherTotal)%></td>
      <td class="num"><%=FmtNum(rs("NetAmount"))%></td>
      <td class="num"><%=FmtNum(rs("VATAmount"))%></td>
      <td class="num total"><%=FmtNum(rs("Total"))%></td>
    </tr>
  <%
    rs.MoveNext
  Loop
  %>
  </tbody>

  <tfoot>
    <tr>
      <td colspan="9" class="text-end">Totals:</td>
      <td class="num"><%=FmtNum(totalBase)%></td>
      <td class="num"><%=FmtNum(totalFuel)%></td>
      <td class="num"><%=FmtNum(totalOther)%></td>
      <td class="num"><%=FmtNum(totalNet)%></td>
      <td class="num"><%=FmtNum(totalVAT)%></td>
      <td class="num total"><%=FmtNum(totalGrand)%></td>
    </tr>
  </tfoot>

</table>
</div>

<p class="text-muted mt-2">Total records: <%=totalCount%></p>
</div>

<!-- Shipment Details Modal -->
<div class="modal fade" id="shipmentModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">

      <div class="modal-header">
        <h5 class="modal-title">Shipment Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <p><strong>ID:</strong> <span id="m_id"></span></p>
        <p><strong>Invoice:</strong> <span id="m_invoice"></span></p>

        <p><strong>Shipment Details:</strong>
        <pre class="modal-block" id="m_shipdet"></pre></p>

        <p><strong>Receiver Address:</strong>
        <pre class="modal-block" id="m_recv"></pre></p>

        <p><strong>Pieces / Weight / Dimensions / Zone:</strong>
        <pre class="modal-block" id="m_pieces"></pre></p>

        <p><strong>Charges:</strong>
        <pre class="modal-block" id="m_charges"></pre></p>

        <p><strong>Total:</strong> £<span id="m_total"></span></p>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>

    </div>
  </div>
</div>

</body>
</html>
<%
' Cleanup
rs.Close : Set rs = Nothing
conn.Close : Set conn = Nothing
%>