format($format);
}
if ($value === null || $value === '') {
return '—';
}
$timestamp = strtotime((string) $value);
if ($timestamp === false) {
return '—';
}
return date($format, $timestamp);
}
function calculate_net_weight($scaleWeight, $grossWeight)
{
if (!is_numeric($scaleWeight) || !is_numeric($grossWeight)) {
return 0.0;
}
$scale = (float) $scaleWeight;
$gross = (float) $grossWeight;
if ($scale > 100000 && $scale > $gross) {
return $scale - $gross;
}
return 0.0;
}
function parse_boolean_value($value)
{
if (is_bool($value)) {
return $value;
}
if (is_numeric($value)) {
return ((int) $value) === 1;
}
if (is_string($value)) {
$normalized = strtolower(trim($value));
return in_array($normalized, array('1', 'true', 'yes', 'y'), true);
}
return false;
}
function capture_metric_from_include($path)
{
if (!file_exists($path)) {
return null;
}
ob_start();
$result = @include $path;
$output = trim(ob_get_clean());
if ($result === false || $output === '') {
return null;
}
if (!preg_match('/-?\d+(?:\.\d+)?/', $output, $matches)) {
return null;
}
return (float) $matches[0];
}
function fetch_factory_metrics($rootDir)
{
$metrics = array(
'current_rate' => null,
'avg_15_min' => null,
'tons_today' => null,
'tons_prev' => null,
'run_hours_today' => null,
'run_hours_prev' => null,
'updated_at_raw' => null,
'error' => null
);
if (!class_exists('mysqli')) {
$metrics['error'] = 'Factory data currently unavailable.';
return $metrics;
}
$itemsPath = $rootDir . '/inc/items.php';
if (!file_exists($itemsPath)) {
$metrics['error'] = 'Factory data currently unavailable.';
return $metrics;
}
$value = array();
$rounded = array();
$time = array();
require $itemsPath;
$hasTonsToday = false;
$tonsToday = 0.0;
if (isset($value['CANETOT'])) {
$tonsToday += (float) $value['CANETOT'];
$hasTonsToday = true;
}
if (isset($value['W TONS GROUND'])) {
$tonsToday += (float) $value['W TONS GROUND'];
$hasTonsToday = true;
}
$metrics['tons_today'] = $hasTonsToday ? $tonsToday : null;
$hasTonsPrev = false;
$tonsPrev = 0.0;
if (isset($value['PREVTONS'])) {
$tonsPrev += (float) $value['PREVTONS'];
$hasTonsPrev = true;
}
if (isset($value['WPREVGROUND'])) {
$tonsPrev += (float) $value['WPREVGROUND'];
$hasTonsPrev = true;
}
$metrics['tons_prev'] = $hasTonsPrev ? $tonsPrev : null;
if (isset($rounded['RUNHRSTODAY'])) {
$metrics['run_hours_today'] = (float) $rounded['RUNHRSTODAY'];
}
if (isset($value['PREVTIME'])) {
$metrics['run_hours_prev'] = (float) $value['PREVTIME'];
}
$timestampCandidates = array('CANETOT', 'RUNHRSTODAY', 'PREVTONS', 'PREVTIME');
foreach ($timestampCandidates as $candidate) {
if (isset($time[$candidate]) && $time[$candidate] !== null && $time[$candidate] !== '') {
$metrics['updated_at_raw'] = $time[$candidate];
break;
}
}
$stableratePath = $rootDir . '/inc/stablerate30.php';
$metrics['current_rate'] = capture_metric_from_include($stableratePath);
$avgPath = $rootDir . '/inc/east15minavg.php';
$metrics['avg_15_min'] = capture_metric_from_include($avgPath);
if ($metrics['current_rate'] === null) {
$hasRate = false;
$rateSum = 0.0;
if (isset($value['E TONS PER HOUR'])) {
$rateSum += (float) $value['E TONS PER HOUR'];
$hasRate = true;
}
if (isset($value['W RATE'])) {
$rateSum += (float) $value['W RATE'];
$hasRate = true;
}
if ($hasRate) {
$metrics['current_rate'] = $rateSum;
}
}
if ($metrics['avg_15_min'] === null) {
$hasAvg = false;
$avgSum = 0.0;
if (isset($rounded['E 15 MIN AVG'])) {
$avgSum += (float) $rounded['E 15 MIN AVG'];
$hasAvg = true;
}
if (isset($rounded['W 15 MIN AVG'])) {
$avgSum += (float) $rounded['W 15 MIN AVG'];
$hasAvg = true;
}
if ($hasAvg) {
$metrics['avg_15_min'] = $avgSum;
}
}
if ($metrics['current_rate'] === null &&
$metrics['avg_15_min'] === null &&
$metrics['tons_today'] === null &&
$metrics['run_hours_today'] === null) {
$metrics['error'] = 'Factory data currently unavailable.';
}
return $metrics;
}
function connect_scale_db()
{
if (!function_exists('sqlsrv_connect')) {
return null;
}
$server = lasuca_env('SQLSRV_HOST', 'CBM2K12\\SQLEXPRESS');
$database = lasuca_env('SQLSRV_DATABASE', 'SugarCaneScale');
$user = lasuca_env('SQLSRV_USERNAME', 'cbmclient');
$password = lasuca_env('SQLSRV_PASSWORD', 'ascbm2k');
$connectionInfo = array(
'Database' => $database,
'UID' => $user,
'PWD' => $password,
'ReturnDatesAsStrings' => true,
'CharacterSet' => 'UTF-8'
);
$link = @call_user_func('sqlsrv_connect', $server, $connectionInfo);
if ($link === false) {
return null;
}
return $link;
}
function fetch_today_load_summary($connection, $growerId)
{
if (!function_exists('sqlsrv_query')) {
return array();
}
$sql = "SELECT COUNT(*) AS load_count,
SUM(Tons) AS total_tons,
SUM(GrossWt) AS total_gross,
SUM(TareWt) AS total_tare,
SUM(CASE WHEN ScaleWt > 100000 AND ScaleWt > GrossWt THEN ScaleWt - GrossWt ELSE 0 END) AS total_net,
MAX(DateOut) AS last_load_time
FROM LoadData
WHERE FarmerId_Fk = ? AND CONVERT(date, DateOut) = CONVERT(date, GETDATE())";
$params = array((int) $growerId);
$stmt = call_user_func('sqlsrv_query', $connection, $sql, $params);
if ($stmt === false) {
return array();
}
$fetchAssoc = defined('SQLSRV_FETCH_ASSOC') ? constant('SQLSRV_FETCH_ASSOC') : 2;
$row = call_user_func('sqlsrv_fetch_array', $stmt, $fetchAssoc);
if (function_exists('sqlsrv_free_stmt')) {
call_user_func('sqlsrv_free_stmt', $stmt);
}
if (!$row) {
return array();
}
$loadCount = isset($row['load_count']) ? (int) $row['load_count'] : 0;
$summary = array(
'load_count' => $loadCount,
'total_tons' => isset($row['total_tons']) ? (float) $row['total_tons'] : 0.0,
'total_gross' => isset($row['total_gross']) ? (float) $row['total_gross'] : 0.0,
'total_tare' => isset($row['total_tare']) ? (float) $row['total_tare'] : 0.0,
'total_net' => isset($row['total_net']) ? (float) $row['total_net'] : 0.0,
'last_load_time' => isset($row['last_load_time']) ? $row['last_load_time'] : null
);
if ($loadCount > 0) {
$summary['avg_tons'] = $summary['total_tons'] / $loadCount;
$summary['avg_gross'] = $summary['total_gross'] / $loadCount;
$summary['avg_tare'] = $summary['total_tare'] / $loadCount;
$summary['avg_net'] = $summary['total_net'] / $loadCount;
} else {
$summary['avg_tons'] = 0.0;
$summary['avg_gross'] = 0.0;
$summary['avg_tare'] = 0.0;
$summary['avg_net'] = 0.0;
}
return $summary;
}
function fetch_today_loads($connection, $growerId, $limit = 25)
{
if (!function_exists('sqlsrv_query')) {
return array();
}
$limit = max(1, (int) $limit);
$sql = "SELECT TOP {$limit}
LoadId_Pk,
VehicleId_Fk,
TractId_Fk,
Tons,
TareWt,
GrossWt,
ScaleWt,
Parked,
DateOut
FROM LoadData
WHERE FarmerId_Fk = ? AND CONVERT(date, DateOut) = CONVERT(date, GETDATE())
ORDER BY DateOut DESC, LoadId_Pk DESC";
$params = array((int) $growerId);
$stmt = call_user_func('sqlsrv_query', $connection, $sql, $params);
if ($stmt === false) {
return array();
}
$loads = array();
$fetchAssoc = defined('SQLSRV_FETCH_ASSOC') ? constant('SQLSRV_FETCH_ASSOC') : 2;
while ($row = call_user_func('sqlsrv_fetch_array', $stmt, $fetchAssoc)) {
$loads[] = array(
'load_id' => isset($row['LoadId_Pk']) ? (int) $row['LoadId_Pk'] : null,
'vehicle' => isset($row['VehicleId_Fk']) ? (string) $row['VehicleId_Fk'] : '',
'tract' => isset($row['TractId_Fk']) ? (string) $row['TractId_Fk'] : '',
'tons' => isset($row['Tons']) ? (float) $row['Tons'] : null,
'tare_weight' => isset($row['TareWt']) ? (float) $row['TareWt'] : null,
'gross_weight' => isset($row['GrossWt']) ? (float) $row['GrossWt'] : null,
'net_weight' => calculate_net_weight(isset($row['ScaleWt']) ? $row['ScaleWt'] : null, isset($row['GrossWt']) ? $row['GrossWt'] : null),
'date_out' => isset($row['DateOut']) ? $row['DateOut'] : null,
'parked' => parse_boolean_value(isset($row['Parked']) ? $row['Parked'] : null)
);
}
if (function_exists('sqlsrv_free_stmt')) {
call_user_func('sqlsrv_free_stmt', $stmt);
}
return $loads;
}
$username = isset($_SESSION['myusername']) ? $_SESSION['myusername'] : '';
$growerId = isset($_SESSION['growerid']) ? (string) $_SESSION['growerid'] : '';
if ($growerId !== (string) $requiredGrowerId) {
header('Location: /grower-login.php');
exit();
}
$member = auth_find_member($username);
$memberData = grower_member_defaults($member);
$recentFiles = grower_recent_files($username, 5);
$displayName = '';
if (is_array($member)) {
$first = isset($member['firstname']) ? trim((string) $member['firstname']) : '';
$last = isset($member['lastname']) ? trim((string) $member['lastname']) : '';
$displayName = trim($first . ' ' . $last);
if ($displayName === '' && isset($member['growername'])) {
$displayName = trim((string) $member['growername']);
}
}
if ($displayName === '') {
$displayName = 'Grower ' . (string) $growerId;
}
$factoryMetrics = fetch_factory_metrics($rootDir);
$scaleConnection = connect_scale_db();
$todayLoadSummary = array();
$todayLoads = array();
if ($scaleConnection) {
$todayLoadSummary = fetch_today_load_summary($scaleConnection, $growerId);
$todayLoads = fetch_today_loads($scaleConnection, $growerId, 25);
if (function_exists('sqlsrv_close')) {
call_user_func('sqlsrv_close', $scaleConnection);
}
}
require_once $rootDir . '/inc/closedb.php';
$loadSummaryCount = isset($todayLoadSummary['load_count']) ? (int) $todayLoadSummary['load_count'] : 0;
if ($loadSummaryCount > 0) {
$totalTonsText = number_or_dash(isset($todayLoadSummary['total_tons']) ? $todayLoadSummary['total_tons'] : null, 1);
if ($totalTonsText === '—') {
$heroSummaryText = sprintf(
'We\'ve logged %s %s today. Keep scrolling for mill stats and the live load list.',
number_format($loadSummaryCount),
$loadSummaryCount === 1 ? 'load' : 'loads'
);
} else {
$heroSummaryText = sprintf(
'We\'ve logged %s %s so far today totaling %s tons. Keep scrolling for mill stats and the live load list.',
number_format($loadSummaryCount),
$loadSummaryCount === 1 ? 'load' : 'loads',
$totalTonsText
);
}
} else {
$heroSummaryText = 'Your loads will appear below as soon as the first ticket clears the scale today. In the meantime, check your recent PDFs and mill performance snapshots.';
}
$heroFootnoteParts = array();
if (empty($factoryMetrics['error'])) {
$factoryUpdatedLabel = format_datetime_label(isset($factoryMetrics['updated_at_raw']) ? $factoryMetrics['updated_at_raw'] : null, 'g:i A');
if ($factoryUpdatedLabel !== '—') {
$heroFootnoteParts[] = 'Factory snapshot updated ' . $factoryUpdatedLabel;
}
} else {
$factoryUpdatedLabel = '—';
}
if ($loadSummaryCount > 0) {
$lastLoadSource = isset($todayLoadSummary['last_load_time']) ? $todayLoadSummary['last_load_time'] : null;
if ($lastLoadSource === null && !empty($todayLoads)) {
$lastLoadSource = $todayLoads[0]['date_out'];
}
$lastLoadLabel = format_datetime_label($lastLoadSource, 'g:i A');
if ($lastLoadLabel !== '—') {
$heroFootnoteParts[] = 'Last load recorded at ' . $lastLoadLabel;
}
} else {
$lastLoadLabel = '';
}
$lastLoginLabel = grower_format_datetime($memberData['last_login_at']);
if ($lastLoginLabel !== 'Never') {
$heroFootnoteParts[] = 'Last login ' . $lastLoginLabel;
}
$heroFootnote = '';
if (!empty($heroFootnoteParts)) {
$heroFootnote = implode(' · ', $heroFootnoteParts);
}
if (empty($factoryMetrics['error']) && (!isset($factoryUpdatedLabel) || $factoryUpdatedLabel === '—')) {
$factoryUpdatedLabel = 'Live reading';
}
$heroFootnoteText = $heroFootnote !== '' ? $heroFootnote : 'Data refreshes every few minutes · Last check ' . date('g:i A');
?>
Grower Dashboard
Welcome back,
Today’s field and factory pulse.
Today's Data
Grower ID
Loads today
Tons today
Avg tons/load
Last load
Last login
Factory Data
Mill metrics are offline right now. Please check back shortly.
-
Current grinding rate
-
15-minute average
-
Tons ground today
-
Previous day tons
-
Run hours today
-
Previous day hours
Recent files
We haven’t spotted any recent files in your folder yet.
Open file browser
Daily report links
Jump straight to your most common folders. These links open in a new tab.
Today’s loads
Showing up to 25 of your most recent tickets. Full history lives in the load data view.
Open full load history
| Load |
Vehicle |
Tract |
Tons |
Gross |
Tare |
Net |
Parked |
Time out |
|
|
|
|
|
|
|
Yes' : 'No'; ?> |
|
No loads have been recorded today yet. Once the first ticket clears the scale you’ll see it here instantly.
}