I sistemi ERP sono il cuore dello sviluppo Delphi: clienti, ordini, fatture, livelli di magazzino, cicli di produzione. La logica di business è già in Object Pascal. Il database è configurato. I report funzionano. Ciò che spesso manca è un dashboard accessibile da browser che il management possa aprire su un tablet senza installare nulla. Questo articolo mostra come costruire esattamente questo con sgcHTML, partendo da uno scenario realistico: un ERP vendite con ricavi live, una griglia fatture, una board Kanban per le consegne e push in tempo reale quando arrivano nuovi ordini.
Tutto il codice compila in Delphi 10.4 Sydney e versioni successive. Il risultato finale è un unico .exe che serve il dashboard sulla porta 8080, con stile Bootstrap 5, un layout responsive e aggiornamenti live via WebSocket, senza alcun file JavaScript da distribuire insieme al binario.
Configurazione del server
sgcHTML racchiude un TsgcWSHTTPServer di sgcWebSockets. Posiziona TsgcHTMLEngine_Server nel data module accanto al server HTTP e collegali tra loro. Il motore intercetta automaticamente le richieste di risorse statiche (Bootstrap CSS/JS, Chart.js, htmx); tutto il resto va al tuo gestore OnCommandGet.
uses
sgcWebSocket_Server, sgcHTML_Engine_Server,
sgcHTML_Template_Bootstrap, sgcHTML_Page;
type
TERP_Server = class(TDataModule)
HTTPServer: TsgcWSHTTPServer;
HTMLEngine: TsgcHTMLEngine_Server;
private
procedure HandleGet(AContext: TIdContext;
AReq: TIdHTTPRequestInfo; AResp: TIdHTTPResponseInfo);
public
procedure Start(aPort: Integer);
end;
procedure TERP_Server.Start(aPort: Integer);
begin
HTTPServer.Port := aPort;
HTMLEngine.Server := HTTPServer;
HTTPServer.OnCommandGet := HandleGet;
HTTPServer.Active := True;
end;
procedure TERP_Server.HandleGet(AContext: TIdContext;
AReq: TIdHTTPRequestInfo; AResp: TIdHTTPResponseInfo);
begin
if AReq.Document = '/' then
ServeDashboard(AResp)
else if AReq.Document = '/invoices' then
ServeInvoices(AResp)
else if AReq.Document = '/kanban' then
ServeKanban(AResp)
else
AResp.ResponseNo := 404;
end;
Schede KPI
La riga superiore del dashboard mostra quattro schede KPI: ricavi totali, fatture aperte, numero di scaduti e tasso di consegna puntuale. TsgcHTMLComponent_StatCard gestisce l'intera parte visiva: sfumatura di sfondo, titolo, valore grande, freccia di tendenza ed etichetta a piè di pagina opzionale.
uses
sgcHTML_Component_StatCard;
procedure TERP_Server.BuildKPIRow(aPage: TsgcHTMLPage; aDB: TFDConnection);
function MakeCard(aPage: TsgcHTMLPage; const aTitle, aValue: string;
aColor: TsgcHTMLStatColor; aTrend: TsgcHTMLStatTrend;
const aTrendValue, aFooter: string; aOrder: Integer): TsgcHTMLComponent_StatCard;
begin
Result := TsgcHTMLComponent_StatCard.Create(nil);
Result.PageBuilder := aPage.PageBuilder;
Result.Section := 'kpi';
Result.SectionOrder := aOrder;
Result.ColumnWidth := cw3;
Result.Title := aTitle;
Result.Value := aValue;
Result.Color := aColor;
Result.Trend := aTrend;
Result.TrendValue := aTrendValue;
Result.FooterText := aFooter;
Result.Gradient := sgBlueViolet;
end;
var
oQ: TFDQuery;
begin
oQ := TFDQuery.Create(nil);
try
oQ.Connection := aDB;
oQ.SQL.Text := 'SELECT SUM(total) FROM invoices WHERE YEAR(issued)=YEAR(NOW())';
oQ.Open;
MakeCard(aPage, 'YTD Revenue', FormatCurr('$#,##0', oQ.Fields[0].AsFloat),
scPrimary, stUp, '+14%', 'vs last year', 1);
oQ.Close;
oQ.SQL.Text := 'SELECT COUNT(*) FROM invoices WHERE status=''open''';
oQ.Open;
MakeCard(aPage, 'Open Invoices', oQ.Fields[0].AsString,
scInfo, stNeutral, '', 'awaiting payment', 2);
oQ.Close;
oQ.SQL.Text := 'SELECT COUNT(*) FROM invoices WHERE status=''overdue''';
oQ.Open;
MakeCard(aPage, 'Overdue', oQ.Fields[0].AsString,
scDanger, stDown, '-3', 'vs last month', 3);
oQ.Close;
oQ.SQL.Text := 'SELECT ROUND(100.0*SUM(on_time)/COUNT(*),1) FROM deliveries';
oQ.Open;
MakeCard(aPage, 'On-Time Delivery', oQ.Fields[0].AsString + '%',
scSuccess, stUp, '+2pp', 'last 30 days', 4);
oQ.Close;
finally
oQ.Free;
end;
end;
Grafico dell'andamento dei ricavi
Il grafico dei ricavi occupa la seconda riga. TsgcHTMLComponent_Chart accetta array di etichette e dataset con colori di bordo e di riempimento. LoadFromDataSet mappa il risultato di una query ai dati del grafico con una singola chiamata: passa il dataset, il campo etichetta (nome del mese) e uno o più campi valore (ricavi, costi).
uses
sgcHTML_Component_Chart;
procedure TERP_Server.BuildRevenueChart(aPage: TsgcHTMLPage; aDB: TFDConnection);
var
oChart: TsgcHTMLComponent_Chart;
oQ: TFDQuery;
begin
oChart := TsgcHTMLComponent_Chart.Create(nil);
oChart.PageBuilder := aPage.PageBuilder;
oChart.Section := 'charts';
oChart.SectionTitle := 'Revenue';
oChart.SectionOrder := 1;
oChart.ColumnWidth := cw8;
oChart.ChartType := ctBar;
oChart.Title := 'Monthly Revenue vs Cost (last 12 months)';
oChart.ShowLegend := True;
oChart.Stacked := False;
oChart.Responsive := True;
oQ := TFDQuery.Create(nil);
try
oQ.Connection := aDB;
oQ.SQL.Text :=
'SELECT DATE_FORMAT(issued,''%b'') AS month, ' +
' SUM(total) AS revenue, ' +
' SUM(cost) AS cost ' +
'FROM invoices ' +
'WHERE issued >= DATE_SUB(NOW(), INTERVAL 12 MONTH) ' +
'GROUP BY YEAR(issued), MONTH(issued) ' +
'ORDER BY YEAR(issued), MONTH(issued)';
oQ.Open;
// One call maps the query to labels + two datasets
oChart.LoadFromDataSet(oQ, 'month', ['revenue', 'cost']);
finally
oQ.Free;
end;
end;
Tabella fatture paginata
TsgcHTMLComponent_DataTable compone un TsgcHTMLComponent_Grid e un TsgcHTMLComponent_Pagination in un unico widget con casella di ricerca integrata, etichetta del conteggio righe, pulsante di esportazione opzionale e dimensioni di pagina configurabili. LoadFromDataSet legge automaticamente i nomi e i tipi delle colonne; è possibile sovrascrivere le intestazioni e le larghezze delle colonne in seguito tramite Grid.Columns.
uses
sgcHTML_Component_DataTable;
procedure TERP_Server.BuildInvoiceTable(aPage: TsgcHTMLPage; aDB: TFDConnection);
var
oTable: TsgcHTMLComponent_DataTable;
oQ: TFDQuery;
begin
oTable := TsgcHTMLComponent_DataTable.Create(nil);
oTable.PageBuilder := aPage.PageBuilder;
oTable.Section := 'invoices';
oTable.SectionTitle := 'Invoices';
oTable.SectionOrder := 1;
oTable.ColumnWidth := cw12;
oTable.Title := 'Recent Invoices';
oTable.ShowSearch := True;
oTable.ShowExport := True;
oTable.ShowPageSize := True;
oTable.PageSizes := '10,25,50';
oQ := TFDQuery.Create(nil);
try
oQ.Connection := aDB;
oQ.SQL.Text :=
'SELECT number, customer, issued, due, total, status ' +
'FROM invoices ' +
'ORDER BY issued DESC ' +
'LIMIT 200';
oQ.Open;
oTable.LoadFromDataSet(oQ, 20);
finally
oQ.Free;
end;
end;
Board Kanban per l'evasione degli ordini
TsgcHTMLComponent_KanbanBoard rappresenta una board multi-colonna con trascinamento. Ogni colonna contiene una raccolta di schede; ogni scheda ha un titolo, una descrizione opzionale, un assegnatario, un tag e un colore. In un contesto ERP le colonne si mappano naturalmente agli stati degli ordini: Ricevuto, Prelievo, Imballato, Spedito.
uses
sgcHTML_Component_KanbanBoard;
procedure TERP_Server.BuildKanban(aPage: TsgcHTMLPage; aDB: TFDConnection);
var
oBoard: TsgcHTMLComponent_KanbanBoard;
oCol: TsgcHTMLKanbanColumn;
oQ: TFDQuery;
vStatus: string;
begin
oBoard := TsgcHTMLComponent_KanbanBoard.Create(nil);
oBoard.PageBuilder := aPage.PageBuilder;
oBoard.Section := 'kanban';
oBoard.SectionTitle := 'Order Fulfilment';
oBoard.SectionOrder := 1;
oBoard.ColumnWidth := cw12;
// Create the four columns
for vStatus in ['Received', 'Picking', 'Packed', 'Shipped'] do
begin
oCol := oBoard.Columns.Add;
oCol.Title := vStatus;
oCol.Color := hcLight;
end;
oQ := TFDQuery.Create(nil);
try
oQ.Connection := aDB;
oQ.SQL.Text :=
'SELECT order_no, customer, qty_total, assigned_to, status ' +
'FROM orders ' +
'WHERE status IN (''Received'',''Picking'',''Packed'',''Shipped'') ' +
'ORDER BY created DESC LIMIT 100';
oQ.Open;
while not oQ.Eof do
begin
// Find the column whose title matches the order status
oCol := oBoard.Columns.FindByTitle(oQ.FieldByName('status').AsString);
if Assigned(oCol) then
oCol.AddCard(
oQ.FieldByName('order_no').AsString,
oQ.FieldByName('customer').AsString + ' — ' +
oQ.FieldByName('qty_total').AsString + ' items',
hcLight,
oQ.FieldByName('assigned_to').AsString
);
oQ.Next;
end;
finally
oQ.Free;
end;
end;
Assemblaggio della pagina completa
Le quattro sezioni vengono assemblate da un'unica procedura ServeDashboard che crea una pagina, chiama ciascun builder, racchiude il risultato in un template Bootstrap e lo scrive nella risposta:
procedure TERP_Server.ServeDashboard(AResp: TIdHTTPResponseInfo);
var
oPage: TsgcHTMLPage;
oTemplate: TsgcHTMLTemplate_Bootstrap;
begin
oPage := TsgcHTMLPage.Create(nil);
oTemplate := TsgcHTMLTemplate_Bootstrap.Create(nil);
try
BuildKPIRow(oPage, FDB);
BuildRevenueChart(oPage, FDB);
BuildInvoiceTable(oPage, FDB);
BuildKanban(oPage, FDB);
oTemplate.Title := 'ERP Dashboard';
oTemplate.Page := oPage;
oTemplate.DarkMode := False;
oTemplate.BodyClass := 'bg-light';
AResp.ContentType := 'text/html; charset=utf-8';
AResp.ContentText := oTemplate.GetHTML;
AResp.ResponseNo := 200;
finally
oPage.Free;
oTemplate.Free;
end;
end;
Aggiornamenti live via WebSocket
Il dashboard sarebbe statico senza dati live. sgcHTML si trova sopra sgcWebSockets, quindi inviare un aggiornamento di frammento quando viene inserito un nuovo ordine è una singola chiamata broadcast. Sul lato client la scheda stat porta un attributo id e l'estensione WebSocket di htmx sostituisce il suo contenuto quando arriva un messaggio.
// Called from the order-processing thread when a new order is saved
procedure TERP_Server.OnNewOrderSaved(aOrder: TERPOrder);
var
oCard: TsgcHTMLComponent_StatCard;
begin
// Rebuild the "Open Invoices" KPI card with the updated count
oCard := TsgcHTMLComponent_StatCard.Create(nil);
try
oCard.CardID := 'kpi-open-invoices';
oCard.Title := 'Open Invoices';
oCard.Value := IntToStr(FDB.OpenInvoiceCount);
oCard.Color := scInfo;
oCard.Trend := stUp;
// Broadcast the new card HTML to all connected dashboard clients
HTTPServer.Broadcast(oCard.HTML, '/dashboard');
finally
oCard.Free;
end;
end;
Il frammento sostituisce la scheda corrispondente nel browser immediatamente, senza ricaricare la pagina e senza che l'utente debba fare clic su nulla. Ogni client connesso vede l'aggiornamento entro pochi millisecondi.
Il risultato finale
L'esempio completo è una singola unit Delphi e un data module. Compila ed esegui: sulla porta configurata appare un dashboard ERP accessibile da browser con quattro schede KPI, un grafico a barre ricavi/costi su 12 mesi, una tabella fatture ricercabile e paginata e una board Kanban multi-colonna per l'evasione degli ordini. Quando vengono inseriti nuovi ordini, le schede KPI si aggiornano in tempo reale in ogni scheda del browser connessa. Righe di codice front-end scritte: zero.
Lo stesso schema funziona per qualsiasi applicazione business Delphi: gestione del magazzino, pianificazione della produzione, sistemi HR, monitoraggio flotte. Se i dati sono in un TDataSet, possono essere su un dashboard web live in mezza giornata.
Scarica la versione di prova gratuita di sgcHTML da esegece.com/products/sgchtml/download e sfoglia le applicazioni demo incluse ERP Demo, Admin Console, Live Monitor e Customer Portal per un esempio completo e funzionante.
Domande? Contattaci. Riceverai una risposta direttamente dalle persone che hanno scritto il codice.
