feat(mobile): update notifications and more error handling added
All checks were successful
Build and Push LST Docker Image / docker (push) Successful in 1m24s

This commit is contained in:
2026-04-30 17:02:21 -05:00
parent bb6155c969
commit 30ffd843c7
24 changed files with 2784 additions and 200 deletions

View File

@@ -0,0 +1,20 @@
import { jsonb, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import type z from "zod";
export const scanLog = pgTable("scan_log", {
id: uuid("id").defaultRandom().primaryKey(),
scannerId: text("scanner_id"),
message: text("message").notNull(),
prompt: text("prompt"),
commandDescription: text("command_description"),
status: text("status"),
lines: jsonb("lines").default([]),
add_Date: timestamp("add_Date").defaultNow(),
});
export const scanLogSchema = createSelectSchema(scanLog);
export const newScanLogSchema = createInsertSchema(scanLog);
export type Printer = z.infer<typeof scanLogSchema>;
export type NewPrinter = z.infer<typeof newScanLogSchema>;

View File

@@ -56,7 +56,7 @@ const servers: NewServerData[] = [
name: "Dayton", name: "Dayton",
server: "usday1VMS006", server: "usday1VMS006",
plantToken: "usday1", plantToken: "usday1",
idAddress: "10.44.0.56", idAddress: "10.44.0.56", // 3000 opened and working
greatPlainsPlantCode: "80", greatPlainsPlantCode: "80",
contactEmail: "", contactEmail: "",
contactPhone: "", contactPhone: "",
@@ -140,6 +140,28 @@ const servers: NewServerData[] = [
serverLoc: "D$\\LST_V3", serverLoc: "D$\\LST_V3",
buildNumber: 1, buildNumber: 1,
}, },
{
name: "Bowling Green 1",
server: "USBOW1VMS006",
plantToken: "usbow1",
idAddress: "10.25.0.26", // 3000 is open REQ0236527
greatPlainsPlantCode: "55",
contactEmail: "",
contactPhone: "",
serverLoc: "D$\\LST_V3",
buildNumber: 1,
},
{
name: "Bethlehem",
server: "USBET1VMS006",
plantToken: "usbet1",
idAddress: "10.25.0.26",
greatPlainsPlantCode: "75",
contactEmail: "",
contactPhone: "",
serverLoc: "D$\\LST_V3",
buildNumber: 1,
},
]; ];
// notes here for when it comes time to pull in all the server address info [test1_AlplaPROD2.0_Read].[masterData].[Plant] has everything from every server :D // notes here for when it comes time to pull in all the server address info [test1_AlplaPROD2.0_Read].[masterData].[Plant] has everything from every server :D

View File

@@ -2,6 +2,9 @@ import fs from "node:fs";
import { Router } from "express"; import { Router } from "express";
import path from "path"; import path from "path";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
import { db } from "../db/db.controller.js";
import { scanLog } from "../db/schema/scanlog.schema.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
const router = Router(); const router = Router();
@@ -12,27 +15,23 @@ const downloadDir = path.resolve(__dirname, "../../downloads/mobile");
const projectRoot = path.resolve("./lstMobile"); // adjust as needed const projectRoot = path.resolve("./lstMobile"); // adjust as needed
const appJsonPath = path.join(projectRoot, "app.json"); const appJsonPath = path.join(projectRoot, "app.json");
const raw = fs.readFileSync(appJsonPath, "utf-8");
const config = JSON.parse(raw);
const exp = config.expo;
const currentApk = { const currentApk = {
packageName: exp.android?.package,
versionName: exp.version,
versionCode: exp.android?.versionCode,
minSupportedVersionCode: 1, // keep this custom if needed
fileName: "lst-mobile.apk", fileName: "lst-mobile.apk",
}; };
router.get("/version", async (req, res) => { router.get("/version", async (req, res) => {
const baseUrl = `${req.protocol}://${req.get("host")}`; const baseUrl = `${req.protocol}://${req.get("host")}`;
const raw = fs.readFileSync(appJsonPath, "utf-8");
const config = JSON.parse(raw);
const exp = config.expo;
res.json({ res.json({
packageName: currentApk.packageName, packageName: exp.android?.package,
versionName: currentApk.versionName, versionName: exp.version,
versionCode: currentApk.versionCode, versionCode: exp.android?.versionCode,
minSupportedVersionCode: currentApk.minSupportedVersionCode, minSupportedVersionCode: exp?.android?.minSupportedVersionCode ?? 0,
downloadUrl: `${baseUrl}/lst/api/mobile/apk/latest`, downloadUrl: `${baseUrl}/lst/api/mobile/apk/latest`,
}); });
}); });
@@ -66,4 +65,29 @@ router.get("/apk/ehs", (_, res) => {
return res.sendFile(apkPath); return res.sendFile(apkPath);
}); });
router.post("/logs", async (req, res) => {
const body = req.body;
const newLog = await db
.insert(scanLog)
.values({
scannerId: body.data.scannerId,
message: body.data.message,
prompt: body.data.prompt,
commandDescription: body.data.commandDescription,
status: body.data.status,
lines: body.data.lines,
})
.returning();
return apiReturn(res, {
success: true,
level: "info",
module: "mobile",
subModule: "scan logs",
message: `New log from ${body.data.scannerId}`,
data: newLog,
status: 200,
});
});
export default router; export default router;

View File

@@ -15,7 +15,8 @@ export interface ReturnHelper<T = unknown[]> {
| "purchase" | "purchase"
| "tcp" | "tcp"
| "logistics" | "logistics"
| "admin"; | "admin"
| "mobile";
subModule: string; subModule: string;
level: "info" | "error" | "debug" | "fatal" | "warn"; level: "info" | "error" | "debug" | "fatal" | "warn";

View File

@@ -15,8 +15,8 @@
"foregroundImage": "./assets/adaptive-icon-white.png", "foregroundImage": "./assets/adaptive-icon-white.png",
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
}, },
"versionCode": 10, "versionCode": 21,
"minSupportedVersionCode": 5, "minSupportedVersionCode": 21,
"predictiveBackGestureEnabled": false, "predictiveBackGestureEnabled": false,
"package": "net.alpla.lst.mobile" "package": "net.alpla.lst.mobile"
}, },
@@ -44,7 +44,15 @@
} }
} }
], ],
"expo-audio" "expo-audio",
[
"expo-build-properties",
{
"android": {
"usesCleartextTraffic": true
}
}
]
], ],
"experiments": { "experiments": {
"typedRoutes": true, "typedRoutes": true,

View File

@@ -13,6 +13,7 @@
"@react-navigation/elements": "^2.9.10", "@react-navigation/elements": "^2.9.10",
"@react-navigation/native": "^7.1.33", "@react-navigation/native": "^7.1.33",
"@rn-primitives/portal": "^1.4.0", "@rn-primitives/portal": "^1.4.0",
"@rn-primitives/separator": "^1.4.0",
"@rn-primitives/slot": "^1.4.0", "@rn-primitives/slot": "^1.4.0",
"@tanstack/react-query": "^5.99.0", "@tanstack/react-query": "^5.99.0",
"axios": "^1.15.0", "axios": "^1.15.0",
@@ -24,6 +25,7 @@
"expo-application": "~55.0.14", "expo-application": "~55.0.14",
"expo-audio": "~55.0.14", "expo-audio": "~55.0.14",
"expo-av": "^16.0.8", "expo-av": "^16.0.8",
"expo-build-properties": "~55.0.13",
"expo-constants": "~55.0.14", "expo-constants": "~55.0.14",
"expo-device": "~55.0.15", "expo-device": "~55.0.15",
"expo-font": "~55.0.6", "expo-font": "~55.0.6",
@@ -3974,6 +3976,76 @@
} }
} }
}, },
"node_modules/@rn-primitives/separator": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@rn-primitives/separator/-/separator-1.4.0.tgz",
"integrity": "sha512-Wv6miGxrqf/yYWIUDbk1l7NHU8ZCYJJkygQ8LbD6AwiVOiMJHF8q+Dfuq/Eoe3T09a+e/ctb1E4dFKfN/K/btw==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-separator": "^1.1.8",
"@rn-primitives/slot": "1.4.0",
"@rn-primitives/types": "1.4.0"
},
"peerDependencies": {
"react": "*",
"react-native": "*",
"react-native-web": "*"
},
"peerDependenciesMeta": {
"react-native": {
"optional": true
},
"react-native-web": {
"optional": true
}
}
},
"node_modules/@rn-primitives/separator/node_modules/@radix-ui/react-separator": {
"version": "1.1.8",
"resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.8.tgz",
"integrity": "sha512-sDvqVY4itsKwwSMEe0jtKgfTh+72Sy3gPmQpjqcQneqQ4PFmr/1I0YA+2/puilhggCe2gJcx5EBAYFkWkdpa5g==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-primitive": "2.1.4"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@rn-primitives/separator/node_modules/@radix-ui/react-separator/node_modules/@radix-ui/react-primitive": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.4.tgz",
"integrity": "sha512-9hQc4+GNVtJAIEPEqlYqW5RiYdrr8ea5XQ0ZOnD6fgru+83kqT15mq2OCcbe8KnjRZl5vF3ks69AKz3kh1jrhg==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-slot": "1.2.4"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@rn-primitives/slot": { "node_modules/@rn-primitives/slot": {
"version": "1.4.0", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/@rn-primitives/slot/-/slot-1.4.0.tgz", "resolved": "https://registry.npmjs.org/@rn-primitives/slot/-/slot-1.4.0.tgz",
@@ -3993,6 +4065,25 @@
} }
} }
}, },
"node_modules/@rn-primitives/types": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@rn-primitives/types/-/types-1.4.0.tgz",
"integrity": "sha512-U7El2BbYXZG8WZrOIV4y1wpxH8aJA/sKH3SL2tZTL153ENj8aOpZ9QwyUoAU2t+sKVPDejrKjo89HeNuIuwPGQ==",
"license": "MIT",
"peerDependencies": {
"react": "*",
"react-native": "*",
"react-native-web": "*"
},
"peerDependenciesMeta": {
"react-native": {
"optional": true
},
"react-native-web": {
"optional": true
}
}
},
"node_modules/@segment/ajv-human-errors": { "node_modules/@segment/ajv-human-errors": {
"version": "2.16.0", "version": "2.16.0",
"resolved": "https://registry.npmjs.org/@segment/ajv-human-errors/-/ajv-human-errors-2.16.0.tgz", "resolved": "https://registry.npmjs.org/@segment/ajv-human-errors/-/ajv-human-errors-2.16.0.tgz",
@@ -7639,6 +7730,32 @@
} }
} }
}, },
"node_modules/expo-build-properties": {
"version": "55.0.13",
"resolved": "https://registry.npmjs.org/expo-build-properties/-/expo-build-properties-55.0.13.tgz",
"integrity": "sha512-UYZhUKyh7YQhbJdkBvo68WUQ7fOtZeSV7F8kfYkjEiN/ADRHG0WfEIiddvGfi9cH/5iwpptv/+Lu5cx6uvfegA==",
"license": "MIT",
"dependencies": {
"@expo/schema-utils": "^55.0.3",
"resolve-from": "^5.0.0",
"semver": "^7.6.0"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-build-properties/node_modules/semver": {
"version": "7.7.4",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/expo-constants": { "node_modules/expo-constants": {
"version": "55.0.14", "version": "55.0.14",
"resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-55.0.14.tgz", "resolved": "https://registry.npmjs.org/expo-constants/-/expo-constants-55.0.14.tgz",

View File

@@ -11,8 +11,11 @@
"lint": "expo lint", "lint": "expo lint",
"build:apk:clean": "expo prebuild --clean && cd android && gradlew.bat assembleRelease && npm run copy:apk", "build:apk:clean": "expo prebuild --clean && cd android && gradlew.bat assembleRelease && npm run copy:apk",
"build:apk": "expo prebuild && cd android && gradlew.bat assembleRelease && npm run copy:apk", "build:apk": "expo prebuild && cd android && gradlew.bat assembleRelease && npm run copy:apk",
"build:mobile": "cd scripts && node runBuild.ts",
"build:mobile:bump": "cd scripts && node runBuild.ts --bump",
"copy:apk": "cd android && copy /Y app\\build\\outputs\\apk\\release\\app-release.apk ..\\..\\downloads\\mobile\\lst-mobile.apk", "copy:apk": "cd android && copy /Y app\\build\\outputs\\apk\\release\\app-release.apk ..\\..\\downloads\\mobile\\lst-mobile.apk",
"update": "adb install android/app/build/outputs/apk/release/app-release.apk" "update": "adb install android/app/build/outputs/apk/release/app-release.apk",
"checklogs": "adb logcat -v time -s ReactNativeJS"
}, },
"dependencies": { "dependencies": {
"@react-native-async-storage/async-storage": "2.2.0", "@react-native-async-storage/async-storage": "2.2.0",
@@ -20,6 +23,7 @@
"@react-navigation/elements": "^2.9.10", "@react-navigation/elements": "^2.9.10",
"@react-navigation/native": "^7.1.33", "@react-navigation/native": "^7.1.33",
"@rn-primitives/portal": "^1.4.0", "@rn-primitives/portal": "^1.4.0",
"@rn-primitives/separator": "^1.4.0",
"@rn-primitives/slot": "^1.4.0", "@rn-primitives/slot": "^1.4.0",
"@tanstack/react-query": "^5.99.0", "@tanstack/react-query": "^5.99.0",
"axios": "^1.15.0", "axios": "^1.15.0",
@@ -31,6 +35,7 @@
"expo-application": "~55.0.14", "expo-application": "~55.0.14",
"expo-audio": "~55.0.14", "expo-audio": "~55.0.14",
"expo-av": "^16.0.8", "expo-av": "^16.0.8",
"expo-build-properties": "~55.0.13",
"expo-constants": "~55.0.14", "expo-constants": "~55.0.14",
"expo-device": "~55.0.15", "expo-device": "~55.0.15",
"expo-font": "~55.0.6", "expo-font": "~55.0.6",

View File

@@ -149,22 +149,27 @@ class ZebraScannerModule(
putString("PLUGIN_NAME", "BARCODE") putString("PLUGIN_NAME", "BARCODE")
putString("RESET_CONFIG", "true") putString("RESET_CONFIG", "true")
val isLegacyTc8000 =
android.os.Build.MODEL.contains("TC8000", ignoreCase = true)
val props = Bundle().apply { val props = Bundle().apply {
putString("scanner_input_enabled", "true") putString("scanner_input_enabled", "true")
// Auto-select internal scanner // Baseline that should be safe on old and new Zebra devices
putString("scanner_selection", "auto") putString("scanner_selection", "auto")
if (!isLegacyTc8000) {
// Newer Zebra devices
putString("scanner_selection_by_identifier", "AUTO") putString("scanner_selection_by_identifier", "AUTO")
// Hardware trigger behavior
putString("hardware_trigger_enabled", "true") putString("hardware_trigger_enabled", "true")
putString("trigger_mode", "2") // 2 = HARD trigger putString("trigger_mode", "2") // HARD trigger
// Disable Zebra's loud initial decode feedback
putString("decode_audio_feedback_uri", "") putString("decode_audio_feedback_uri", "")
putString("decode_haptic_feedback", "false") putString("decode_haptic_feedback", "false")
putString("decode_led_feedback", "false") putString("decode_led_feedback", "false")
} }
}
putBundle("PARAM_LIST", props) putBundle("PARAM_LIST", props)
} }

View File

@@ -0,0 +1,57 @@
import { execSync } from "child_process";
import fs from "fs";
import path from "path";
const appJsonPath = path.resolve("../app.json");
// detect flags
const args = process.argv.slice(2);
const shouldBumpMin = args.includes("--bump");
try {
// 📖 read file
const raw = fs.readFileSync(appJsonPath, "utf-8");
const json = JSON.parse(raw);
const expo = json.expo ?? json; // supports both formats
if (!expo.android) {
throw new Error("No android config found in app.json");
}
// 🔢 current values
const currentVersionCode = expo.android.versionCode ?? 1;
const currentMin = expo.android.minSupportedVersionCode ?? 1;
// 🚀 increment version
const newVersionCode = currentVersionCode + 1;
expo.android.versionCode = newVersionCode;
if (shouldBumpMin) {
expo.android.minSupportedVersionCode = newVersionCode;
} else {
// keep existing min if not bumping
expo.android.minSupportedVersionCode = currentMin;
}
// 💾 write back
fs.writeFileSync(appJsonPath, JSON.stringify(json, null, 2));
console.log("✅ app.json updated:");
console.log(" versionCode:", newVersionCode);
console.log(
" minSupportedVersionCode:",
expo.android.minSupportedVersionCode,
);
// 🏗 run build
console.log("\n🚧 Running build:apk...\n");
execSync("npm run build:apk", { stdio: "inherit" });
console.log("\n🎉 Build complete!");
} catch (err) {
console.error("❌ Build script failed:");
console.error(err);
process.exit(1);
}

View File

@@ -15,6 +15,15 @@ export default function TabsLayout() {
options={{ options={{
title: "Scan", title: "Scan",
tabBarIcon: ({ color, size }) => <Home size={size} color={color} />, tabBarIcon: ({ color, size }) => <Home size={size} color={color} />,
// header: ({ route }) => {
// const version = serverVersion?.versionCode;
// const hasUpdate = version && version > build;
// if (!hasUpdate) return null; // 👈 hides header completely
// return <GlobalHeader title={route.name} />;
// },
}} }}
/> />
<Tabs.Screen <Tabs.Screen

View File

@@ -2,6 +2,7 @@ import { Stack } from "expo-router";
import { StatusBar } from "expo-status-bar"; import { StatusBar } from "expo-status-bar";
import "../../global.css"; import "../../global.css";
import { PortalHost } from "@rn-primitives/portal"; import { PortalHost } from "@rn-primitives/portal";
import { View } from "react-native";
export default function RootLayout() { export default function RootLayout() {
return ( return (
@@ -9,7 +10,17 @@ export default function RootLayout() {
<StatusBar style="dark" /> <StatusBar style="dark" />
<Stack screenOptions={{ headerShown: false }}> <Stack screenOptions={{ headerShown: false }}>
<Stack.Screen name="index" /> <Stack.Screen name="index" />
{/* <Stack.Screen name="(tabs)" /> */} <View className="items-center">
<Stack.Screen
name="(tabs)"
options={{
title: "Pending update",
headerStyle: {
backgroundColor: "lightblue",
},
}}
/>
</View>
</Stack> </Stack>
<PortalHost /> <PortalHost />
</> </>

View File

@@ -1,18 +1,22 @@
import axios from "axios"; import axios from "axios";
import Constants from "expo-constants";
import { Redirect, useRouter } from "expo-router"; import { Redirect, useRouter } from "expo-router";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { ActivityIndicator, Text, View } from "react-native"; import { ActivityIndicator, Text, View } from "react-native";
import { useAppStore } from "../hooks/useAppStore"; import { useAppStore } from "../hooks/useAppStore";
import { useServerStore } from "../hooks/useServerCheck";
import { devDelay } from "../lib/devMode"; import { devDelay } from "../lib/devMode";
export default function Index() { export default function Index() {
const router = useRouter(); const router = useRouter();
const [message, setMessage] = useState(<Text>Starting app...</Text>); const [message, setMessage] = useState(<Text>Starting app...</Text>);
const [ready, setReady] = useState(false); const [ready, setReady] = useState(false);
const setServerVersion = useServerStore((s) => s.setServerVersion);
const hasHydrated = useAppStore((s) => s.hasHydrated); const hasHydrated = useAppStore((s) => s.hasHydrated);
const serverPort = useAppStore((s) => s.serverPort); const serverPort = useAppStore((s) => s.serverPort);
const serverIp = useAppStore((s) => s.serverIp); const serverIp = useAppStore((s) => s.serverIp);
const build = Constants.expoConfig?.android?.versionCode ?? 1;
const hasValidSetup = useAppStore((s) => s.hasValidSetup); const hasValidSetup = useAppStore((s) => s.hasValidSetup);
useEffect(() => { useEffect(() => {
@@ -46,6 +50,18 @@ export default function Index() {
); );
console.log(res.data); console.log(res.data);
// if the build version dose not match the latest server version force update
if (res.status === 200) {
setServerVersion(res.data);
}
// TODO: change the header to show orange and theres a new version
// console.log(build < res.data.minSupportedVersionCode);
// if (build < res.data.minSupportedVersionCode) {
// router.replace("/updateScreen");
// return;
// }
} catch (error) { } catch (error) {
console.log("Error: ", error); console.log("Error: ", error);
} }
@@ -79,7 +95,14 @@ export default function Index() {
}; };
startup(); startup();
}, [hasHydrated, hasValidSetup, serverPort, serverIp, router]); }, [
hasHydrated,
hasValidSetup,
serverPort,
serverIp,
router,
setServerVersion,
]);
if (ready) { if (ready) {
return <Redirect href="/(tabs)/scanner" />; return <Redirect href="/(tabs)/scanner" />;

View File

@@ -3,6 +3,7 @@ import { useRouter } from "expo-router";
import { useState } from "react"; import { useState } from "react";
import { Alert, Button, Text, TextInput, View } from "react-native"; import { Alert, Button, Text, TextInput, View } from "react-native";
import { useAppStore } from "../hooks/useAppStore"; import { useAppStore } from "../hooks/useAppStore";
import { useServerStore } from "../hooks/useServerCheck";
export default function Setup() { export default function Setup() {
const router = useRouter(); const router = useRouter();
@@ -22,6 +23,8 @@ export default function Setup() {
const [serverPort, setLocalServerPort] = useState(serverPortFromStore); const [serverPort, setLocalServerPort] = useState(serverPortFromStore);
const [scannerId, setScannerId] = useState(scannerIdFromStore); const [scannerId, setScannerId] = useState(scannerIdFromStore);
const server = useServerStore((s) => s.serverVersion);
const authCheck = () => { const authCheck = () => {
if (pin === "6971") { if (pin === "6971") {
setAuth(true); setAuth(true);
@@ -151,8 +154,11 @@ export default function Setup() {
marginBottom: 12, marginBottom: 12,
}} }}
> >
<Text style={{ fontSize: 12, color: "#666" }}> <Text className="text-[12] color-#666">
LST Scanner v{version}-{build} App v{version}-{build}
</Text>
<Text className="text-[12] color-#666">
Server version - v{server?.versionName}-{server?.versionCode}
</Text> </Text>
</View> </View>
</View> </View>

View File

@@ -1,9 +1,47 @@
import Constants from "expo-constants";
import { Link } from "expo-router";
import { Text, View } from "react-native"; import { Text, View } from "react-native";
import {
Card,
CardContent,
CardFooter,
CardHeader,
} from "../components/ui/card";
import { Separator } from "../components/ui/separator";
import { useServerStore } from "../hooks/useServerCheck";
export default function blocked() { export default function Update() {
const version = Constants.expoConfig?.version;
const build = Constants.expoConfig?.android?.versionCode ?? 1;
const server = useServerStore((s) => s.serverVersion);
return ( return (
<View> <View className="flex-1 mt-5 p-5">
<Text>Blocked</Text> <Card>
<CardHeader>
<Text className="text-center underline">Update Required</Text>
</CardHeader>
<CardContent>
<Text>Your app is out of date and needs to be updated</Text>
<Separator className="mt-5 mb-5" />
<Text>
App version - v{version}-{build}
</Text>
<Text>
Server version - v{server?.versionName}-{server?.versionCode}
</Text>
<Separator className="mt-5 mb-5" />
<Text>
To update the app please head go to a computer and open LST.
</Text>
<Text>Then head to Scan.</Text>
<Text>Click update Then follow the instructions on screen</Text>
</CardContent>
</Card>
{server && server?.versionCode >= build && (
<Link href={"/"}>
<Text className="text-center underline">Home</Text>
</Link>
)}
</View> </View>
); );
} }

View File

@@ -1,3 +1,4 @@
import axios from "axios";
import { format } from "date-fns-tz"; import { format } from "date-fns-tz";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { Text, View } from "react-native"; import { Text, View } from "react-native";
@@ -7,6 +8,8 @@ import { scannerFeedback } from "../lib/feedbackScan";
import { sendTcpMessage } from "../lib/tcpScan"; import { sendTcpMessage } from "../lib/tcpScan";
import { type ZebraScanResult, zebraScanner } from "../lib/ZebraScanner"; import { type ZebraScanResult, zebraScanner } from "../lib/ZebraScanner";
import { ScannedLabelBox } from "./ScannedLabels"; import { ScannedLabelBox } from "./ScannedLabels";
import { GlobalFooter } from "./UpdateFooter";
import { Separator } from "./ui/separator";
const STX = "\x02"; const STX = "\x02";
const ETX = "\x03"; const ETX = "\x03";
@@ -23,12 +26,6 @@ export default function ProdScanner() {
const handleScan = useCallback( const handleScan = useCallback(
async (scan: ZebraScanResult) => { async (scan: ZebraScanResult) => {
let commandToSend = `${STX}${scannerIdFromStore}@${scan.data}${ETX}`; let commandToSend = `${STX}${scannerIdFromStore}@${scan.data}${ETX}`;
await scannerFeedback({
type: "good",
sound: true,
vibrate: true,
led: true,
});
// if we are sscc we need to scan like this .... <STX>98@]C100090087710038712256<ETX> // if we are sscc we need to scan like this .... <STX>98@]C100090087710038712256<ETX>
if (scan.data.startsWith("000")) { if (scan.data.startsWith("000")) {
@@ -42,41 +39,54 @@ export default function ProdScanner() {
]); ]);
} }
// if we change commands we want to zero out the last scanned labels
if (/^[a-zA-Z]/.test(scan.data)) {
setTagScans([]);
}
const scanned = (await sendTcpMessage( const scanned = (await sendTcpMessage(
commandToSend, commandToSend,
serverIp, serverIp,
parseInt(serverPort || "0", 10), parseInt(serverPort || "0", 10),
)) as any; )) as any;
// Later this is where your TCP send goes. // send the logs to lst but allow it to time out if it dose not exist just bc.
try {
await axios.post(
`http://${serverIp.trim()}:3000/lst/api/mobile/logs`,
scanned,
);
} catch (error) {
console.log(error);
}
// const response = await sendTcpMessage(tcpMessage); // const response = await sendTcpMessage(tcpMessage);
console.log(scanned); console.log(scanned.data);
if (scanned.data.status !== "error") {
await scannerFeedback({ await scannerFeedback({
type: scanned.data[0]?.type === "error" ? "bad" : "good", type: "good",
sound: true, sound: true,
vibrate: true, vibrate: true,
led: true, led: true,
}); });
if (scanned.data[0]?.type !== "error") {
setBGColor("bg-green-500"); setBGColor("bg-green-500");
setTimeout(() => { setTimeout(() => {
setBGColor(null); setBGColor(null);
}, 1 * 1000); }, 1 * 1000);
} }
if (scanned.data[0]?.type === "error") { if (scanned.data.status === "error") {
await scannerFeedback({
type: scanned.data.status === "error" ? "bad" : "good",
sound: true,
vibrate: true,
led: true,
});
setBGColor("bg-red-500"); setBGColor("bg-red-500");
setTimeout(() => { setTimeout(() => {
setBGColor(null); setBGColor(null);
}, 1 * 1000); }, 1 * 1000);
} }
setLastScan(scanned.data[0]); setLastScan(scanned.data);
//console.log("TCP response:", something);
// if we change commands we want to zero out the last scanned labels
if (/^[a-zA-Z]/.test(scan.data)) {
setTagScans([]);
}
}, },
[scannerIdFromStore, serverIp, serverPort, setLastScan], [scannerIdFromStore, serverIp, serverPort, setLastScan],
); );
@@ -85,7 +95,7 @@ export default function ProdScanner() {
setTagScans([]); setTagScans([]);
}; };
console.log(lastScan); //console.log(lastScan);
useEffect(() => { useEffect(() => {
zebraScanner.ensureProfile(); zebraScanner.ensureProfile();
@@ -109,6 +119,7 @@ export default function ProdScanner() {
Scanner ID: {parseInt(scannerIdFromStore || "0", 10)} Scanner ID: {parseInt(scannerIdFromStore || "0", 10)}
</Text> </Text>
</View> </View>
<Separator />
{!lastScan ? ( {!lastScan ? (
<View style={{ marginTop: 10, alignItems: "center" }}> <View style={{ marginTop: 10, alignItems: "center" }}>
<Text className="text-xl font-bold">Ready to scan</Text> <Text className="text-xl font-bold">Ready to scan</Text>
@@ -121,18 +132,19 @@ export default function ProdScanner() {
alignItems: "center", alignItems: "center",
}} }}
> >
<View style={{ marginTop: 10, alignItems: "center" }}> {lastScan.lines
<Text style={{ fontSize: 20, fontWeight: "600" }}> ?.filter((line) => !/^\d+@$/.test(line))
{lastScan.action} .map((i) => {
</Text> return (
<View style={{ marginTop: 10, alignItems: "center" }} key={i}>
<Text style={{ fontSize: 20, fontWeight: "600" }}> <Text style={{ fontSize: 20, fontWeight: "600" }}>{i}</Text>
{lastScan.message}
</Text>
</View> </View>
);
})}
</View> </View>
)} )}
</View> </View>
<Separator className="m-2" />
<View className="flex-1 w-full px-4"> <View className="flex-1 w-full px-4">
<ScannedLabelBox <ScannedLabelBox
labels={tagScans} labels={tagScans}
@@ -140,6 +152,9 @@ export default function ProdScanner() {
clearScan={clearScans} clearScan={clearScans}
/> />
</View> </View>
<View>
<GlobalFooter />
</View>
</View> </View>
); );
} }

View File

@@ -2,6 +2,7 @@ import { ScrollView, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context"; import { SafeAreaView } from "react-native-safe-area-context";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Text } from "@/components/ui/text"; import { Text } from "@/components/ui/text";
import { Card } from "./ui/card";
type ScannedLabel = { type ScannedLabel = {
label: string; label: string;
@@ -29,27 +30,29 @@ export function ScannedLabelBox({
<ScrollView className="w-full flex-1"> <ScrollView className="w-full flex-1">
{labels.length === 0 ? ( {labels.length === 0 ? (
<Text className="text-center">No labels scanned yet</Text> <Text className="text-center">
pending new labels to be scanned...
</Text>
) : ( ) : (
<View className="flex items-center gap-2 w-full"> <View className="flex items-center gap-2 w-full">
{labels.map((i, index) => ( {labels.map((i, index) => (
<View <Card
key={`${i.label}-${index}`} key={`${i.label}-${index}`}
className={`p-2 border rounded items-center ${color ?? ""}`} className={`p-2 border rounded items-center ${color ?? ""} w-full`}
> >
<Text style={{ fontSize: 18, fontWeight: "700" }}> <Text style={{ fontSize: 18, fontWeight: "700" }}>
{i.label} - {i.date.toString()} {i.label} - {i.date.toString()}
</Text> </Text>
</View> </Card>
))} ))}
</View> </View>
)} )}
</ScrollView> </ScrollView>
{labels.length !== 0 && ( {/* {labels.length !== 0 && (
<Button onPress={clearScan} variant="secondary"> <Button onPress={clearScan} variant="secondary">
<Text>Clear Scans</Text> <Text>Clear Scans</Text>
</Button> </Button>
)} )} */}
</SafeAreaView> </SafeAreaView>
); );
} }

View File

@@ -0,0 +1,40 @@
import Constants from "expo-constants";
import { Link } from "expo-router";
import { Text, View } from "react-native";
import { useServerStore } from "../hooks/useServerCheck";
export function GlobalFooter() {
const build = Constants.expoConfig?.android?.versionCode ?? 1;
const serverVersion = useServerStore((s) => s.serverVersion);
const hasUpdate =
serverVersion && serverVersion?.minSupportedVersionCode > build;
const shouldUpdate = serverVersion && serverVersion?.versionCode > build;
if (serverVersion && serverVersion?.versionCode <= build) return;
return (
<View>
<View>
{hasUpdate && (
<View className="items-center h-[75px] bg-[#EB091A]">
<Link href={"/updateScreen"}>
<Text className="h-[75px] font-medium text-base text-wrap text-center">
Critical updates pending, once you are completed with your task
please click me for instructions to update
</Text>
</Link>
</View>
)}
{!hasUpdate && shouldUpdate && (
<View className="bg-[#FDBA74]">
<Link href={"/updateScreen"}>
<Text className="h-[32] font-medium text-lg text-wrap text-center">
There is an update click me for instructions
</Text>
</Link>
</View>
)}
</View>
</View>
);
}

View File

@@ -0,0 +1,24 @@
import { cn } from '@/lib/utils';
import * as SeparatorPrimitive from '@rn-primitives/separator';
function Separator({
className,
orientation = 'horizontal',
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
decorative={decorative}
orientation={orientation}
className={cn(
'bg-border shrink-0',
orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]',
className
)}
{...props}
/>
);
}
export { Separator };

View File

@@ -1,10 +1,12 @@
import { create } from "zustand"; import { create } from "zustand";
type LastScan = { type LastScan = {
action?: string; terminalId?: string;
type?: "success" | "error" | string; screen?: string;
prompt?: string; prompt?: string;
message?: string; message?: string;
status: "success" | "error" | "location" | "unknown";
lines?: string[];
timestamp?: number; timestamp?: number;
}; };

View File

@@ -0,0 +1,29 @@
import { create } from "zustand";
type ServerVersion = {
packageName: string;
versionName: string;
versionCode: number;
minSupportedVersionCode: number;
downloadUrl: string;
};
type AppState = {
serverVersion: ServerVersion | null;
setServerVersion: (data: ServerVersion) => void;
};
export const useServerStore = create<AppState>((set, get) => ({
serverVersion: null,
hasUpdate: () => {
const v = get().serverVersion;
if (!v) return false;
return v.versionCode < v.minSupportedVersionCode;
},
setServerVersion: (data) =>
set(() => ({
serverVersion: data,
})),
}));

View File

@@ -9,136 +9,217 @@ type TcpResponse = {
data: string[]; data: string[];
}; };
function parseErpResponse(buffer: Buffer) { type ScannerEvent = {
const text = buffer scannerId?: string;
.toString("utf8") commandDescription?: string;
.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|#[0-9A-Za-z])/g, "") prompt?: string;
.replace(/\x02/g, "") message?: string;
.replace(/\x03/g, "") status: "success" | "error" | "location" | "unknown" | "scan";
.trim(); lines?: string[];
};
const noHeader = text.replace(/^\d+@/, ""); // const ERROR_MESSAGES = [
console.log(text); // "Invalid barcode",
if (!noHeader.includes("Scan:")) { // "Already scanned",
return { // "Not on stock",
raw: text, // "Article tolerance for consolidation not satisfied.",
type: "error", // ];
message: noHeader.trim(),
lines: [noHeader.trim()],
};
}
const [actionPart, scanPart = ""] = noHeader.split("Scan:"); const ERROR_KEYWORDS = [
const action = actionPart.trim(); "invalid barcode",
const scanClean = scanPart.trim(); "already",
"not on stock",
"article tolerance",
"unloaded",
"delivered",
"blocked",
];
const successMatch = scanClean.match(/^(.*?)\s+V$/); // function parseErpResponse(buffer: Buffer) {
// const text = buffer
// .toString("utf8")
// .replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|#[0-9A-Za-z])/g, "")
// .replace(/\x02/g, "")
// .replace(/\x03/g, "")
// .trim();
if (successMatch) { // const noHeader = text.replace(/^\d+@/, "");
const prompt = successMatch[1].trim(); // console.log(text);
// if (!noHeader.includes("Scan:")) {
// return {
// raw: text,
// type: "error",
// message: noHeader.trim(),
// lines: [noHeader.trim()],
// };
// }
return { // const [actionPart, scanPart = ""] = noHeader.split("Scan:");
raw: text, // const action = actionPart.trim();
type: "success", // const scanClean = scanPart.trim();
action,
prompt,
status: "V",
lines: [action, prompt, "V"],
};
}
// // Handles: "Production lotInvalid barcode" // const successMatch = scanClean.match(/^(.*?)\s+V$/);
// const knownErrors = [
// "Invalid barcode",
// "Invalid machine",
// "Not on stock",
// "Article tolerance for consolidation not satisfied",
// ].sort((a, b) => b.length - a.length);
// const foundError = knownErrors.find((err) => scanClean.includes(err)); // if (successMatch) {
// const prompt = successMatch[1].trim();
// if (foundError) { // return {
// const prompt = scanClean.replace(foundError, "").trim(); // raw: text,
// type: "success",
// action,
// prompt,
// status: "V",
// lines: [action, prompt, "V"],
// };
// }
// return { // // // Handles: "Production lotInvalid barcode"
// raw: text, // // const knownErrors = [
// type: "error", // // "Invalid barcode",
// action, // // "Invalid machine",
// prompt, // // "Not on stock",
// message: foundError, // // "Article tolerance for consolidation not satisfied",
// lines: [action, prompt, foundError].filter(Boolean), // // ].sort((a, b) => b.length - a.length);
// };
// }
// return { // // const foundError = knownErrors.find((err) => scanClean.includes(err));
// raw: text,
// type: "pending",
// action,
// prompt: scanClean,
// lines: [action, scanClean].filter(Boolean),
// };
const unitMatch = scanClean.match(/^(Unit\s+\d+\/\d+)(.*)$/); // // if (foundError) {
// // const prompt = scanClean.replace(foundError, "").trim();
if (unitMatch) { // // return {
const prompt = unitMatch[1].trim(); // "Unit 1/4" // // raw: text,
const remainder = unitMatch[2].trim(); // everything after // // type: "error",
// // action,
// // prompt,
// // message: foundError,
// // lines: [action, prompt, foundError].filter(Boolean),
// // };
// // }
// SUCCESS // // return {
if (remainder === "V") { // // raw: text,
return { // // type: "pending",
raw: text, // // action,
type: "success", // // prompt: scanClean,
action, // // lines: [action, scanClean].filter(Boolean),
prompt, // // };
status: "V",
lines: [action, prompt, "V"],
};
}
// Known ERP errors // const unitMatch = scanClean.match(/^(Unit\s+\d+\/\d+)(.*)$/);
const knownErrors = [
"Invalid barcode",
"Invalid machine",
"Not on stock",
"Article tolerance for consolidation not satisfied",
];
const foundError = knownErrors.find((err) => // if (unitMatch) {
remainder.toLowerCase().includes(err.toLowerCase()), // const prompt = unitMatch[1].trim(); // "Unit 1/4"
// const remainder = unitMatch[2].trim(); // everything after
// // SUCCESS
// if (remainder === "V") {
// return {
// raw: text,
// type: "success",
// action,
// prompt,
// status: "V",
// lines: [action, prompt, "V"],
// };
// }
// // Known ERP errors
// const knownErrors = [
// "Invalid barcode",
// "Invalid machine",
// "Not on stock",
// "Article tolerance for consolidation not satisfied",
// ];
// const foundError = knownErrors.find((err) =>
// remainder.toLowerCase().includes(err.toLowerCase()),
// );
// if (foundError) {
// return {
// raw: text,
// type: "error",
// action,
// prompt,
// message: foundError,
// lines: [action, prompt, foundError],
// };
// }
// if (remainder) {
// return {
// raw: text,
// type: "prompt",
// action,
// prompt,
// message: remainder,
// lines: [action, prompt, remainder],
// };
// }
// return {
// raw: text,
// type: "pending",
// action,
// prompt,
// lines: [action, prompt],
// };
// }
// }
const parseScannerText = (buffer: Buffer) => {
const text = buffer.toString("utf8");
return (
text
// remove cursor movement like ESC[122C, ESC[2;1H, ESC[8q
.replace(/\x1B\[[0-9;]*[A-Za-z]/g, "\n")
// remove other ANSI sequences like ESC#5
.replace(/\x1B#[0-9]/g, "\n")
// normalize carriage returns
.replace(/\r/g, "\n")
// split into clean lines
.split(/\n+/)
// clean each line
.map((line) => line.trim())
// remove blanks
.filter(Boolean)
); );
};
if (foundError) { const parseScannerEvent = (lines: string[]): ScannerEvent => {
return { const scannerId = lines[0];
raw: text, const messageLines = lines.slice(1);
type: "error", const message = messageLines.at(-1);
action,
prompt,
message: foundError,
lines: [action, prompt, foundError],
};
}
if (remainder) { const commandDescription = messageLines.find((x) => /^\d+\s+/.test(x));
return { const prompt = messageLines.find((x) => /^Scan:/i.test(x));
raw: text,
type: "prompt",
action,
prompt,
message: remainder,
lines: [action, prompt, remainder],
};
}
let status: ScannerEvent["status"] = "unknown";
const msg = message?.toLowerCase() ?? "";
if (msg === "v") status = "success";
else if (msg && ERROR_KEYWORDS.some((keyword) => msg.includes(keyword)))
status = "error";
else if (msg?.includes("scan")) status = "success";
// everything else will just be a location
else if (commandDescription?.includes("Relocate")) status = "location";
// TODO: split command description and use the command id next to description for sorting.
return { return {
raw: text, scannerId,
type: "pending", commandDescription,
action,
prompt, prompt,
lines: [action, prompt], message,
status,
lines,
}; };
} };
}
/** /**
* Sends a Zebra-style TCP message: * Sends a Zebra-style TCP message:
@@ -154,7 +235,7 @@ export async function sendTcpMessage(
const responses: any = []; const responses: any = [];
const client = TcpSocket.createConnection({ host, port }, () => { const client = TcpSocket.createConnection({ host, port }, () => {
console.log("Sending TCP (visible):", `${command}`); //console.log("Sending TCP (visible):", `${command}`);
client.write(command); client.write(command);
}); });
@@ -170,16 +251,20 @@ export async function sendTcpMessage(
}, timeoutMs); }, timeoutMs);
client.on("data", (data) => { client.on("data", (data) => {
//const text = data.toString();
//console.log("TCP received:", text); //console.log("TCP received:", text);
const parsed = parseErpResponse(data); const parsed = parseScannerText(data);
//console.log("scanned:", parsed);
responses.push(parsed); //responses.push(parsed);
const cleaned = parseScannerEvent(parsed);
//console.log(responses);
clearTimeout(timeout); clearTimeout(timeout);
resolve({ resolve({
success: true, success: true,
message: "TCP Response", message: "TCP Response",
data: responses, data: cleaned as any,
}); });
}); });
@@ -190,7 +275,7 @@ export async function sendTcpMessage(
resolve({ resolve({
success: false, success: false,
message: err.message, message: err.message,
data: responses, data: ["Error", "Please try again"],
}); });
}); });
@@ -200,7 +285,7 @@ export async function sendTcpMessage(
resolve({ resolve({
success: true, success: true,
message: "TCP complete", message: "TCP complete",
data: responses, data: ["Error", "Please try again"],
}); });
}); });
}); });

View File

@@ -0,0 +1,10 @@
CREATE TABLE "scan_log" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"scanner_id" text,
"message" text NOT NULL,
"prompt" text,
"command_description" text,
"status" text,
"lines" jsonb DEFAULT '[]'::jsonb,
"add_Date" timestamp DEFAULT now()
);

File diff suppressed because it is too large Load Diff

View File

@@ -288,6 +288,13 @@
"when": 1776770845947, "when": 1776770845947,
"tag": "0040_rainy_white_tiger", "tag": "0040_rainy_white_tiger",
"breakpoints": true "breakpoints": true
},
{
"idx": 41,
"version": "7",
"when": 1777509638464,
"tag": "0041_bright_tempest",
"breakpoints": true
} }
] ]
} }