INIT
This commit is contained in:
+34
@@ -0,0 +1,34 @@
|
||||
# dependencies (bun install)
|
||||
node_modules
|
||||
|
||||
# output
|
||||
out
|
||||
dist
|
||||
*.tgz
|
||||
|
||||
# code coverage
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# logs
|
||||
logs
|
||||
_.log
|
||||
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# caches
|
||||
.eslintcache
|
||||
.cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# IntelliJ based IDEs
|
||||
.idea
|
||||
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
@@ -0,0 +1,58 @@
|
||||
# Session Changelog - December 11-12, 2025
|
||||
|
||||
## Summary of Changes
|
||||
|
||||
### 1. Fixed Decimal Number Sorting
|
||||
- **Issue**: Job numbers with decimals (e.g., 3887.2) were sorting incorrectly, appearing before higher whole numbers (e.g., 4735)
|
||||
- **Solution**: Replaced parseInt with parseFloat and used regex `/[0-9]+\.?[0-9]*/` to correctly extract and compare decimal job numbers
|
||||
- **File**: Frontend/index.html
|
||||
- **Function**: `jobNumberValue()`
|
||||
|
||||
### 2. Removed Premature Initial Render
|
||||
- **Issue**: Cards were flashing with incorrect order during initial page load, then updating after full load completed
|
||||
- **Solution**: Removed the `initialRendered` flag and early `applyFiltersAndRender()` call during the fetch loop
|
||||
- **Result**: Cards no longer render until data is properly sorted and ready
|
||||
|
||||
### 3. Implemented Server-Side Sorting
|
||||
- **Change**: Added `&sort=-Job_Number` parameter to PocketBase API query
|
||||
- **Benefit**: Data arrives pre-sorted in descending order, eliminating client-side sort overhead
|
||||
- **File**: Frontend/index.html
|
||||
- **Function**: `fetchAllJobs()`
|
||||
|
||||
### 4. Implemented Progressive Loading (2-Phase)
|
||||
- **Phase 1**: First 40 cards display immediately after first batch loads (~50 records from perPage=50)
|
||||
- **Phase 2**: Remaining cards load in background and full list renders when complete
|
||||
- **Benefit**: Users see meaningful content within 1-2 seconds instead of waiting for full dataset
|
||||
- **File**: Frontend/index.html
|
||||
- **Functions**:
|
||||
- `fetchAllJobs()` - triggers render at 40 cards
|
||||
- `renderInitialBatch()` - renders first 40 cards immediately
|
||||
- `applyFiltersAndRender()` - renders complete sorted list after all data loaded
|
||||
|
||||
### 5. Expanded Cards Viewing Area
|
||||
- **Change**: Converted layout to flexbox with `height:100vh` on body
|
||||
- **Result**: Cards area now extends to bottom of screen, leaving only version footer visible
|
||||
- **Improvements**:
|
||||
- Better use of screen real estate
|
||||
- More cards visible without scrolling
|
||||
- Cleaner full-screen experience
|
||||
- **Files Modified**: Frontend/index.html
|
||||
- **CSS Changes**:
|
||||
- `body`: Added `height:100vh`, `display:flex`, `flex-direction:column`, `overflow:hidden`
|
||||
- `.wrap`: Changed to `display:flex`, `flex-direction:column`, `flex:1`, `overflow:hidden`, removed margin
|
||||
- `#results`: Changed `max-height:56vh` to `flex:1` for dynamic expansion
|
||||
|
||||
## Performance Improvements
|
||||
- **Perceived Load Time**: ~1-2 seconds for first 40 cards (was waiting for full load)
|
||||
- **Search/Filter Responsiveness**: Now uses server-side sort, reducing client-side computation
|
||||
- **Memory**: Progressive loading means full dataset isn't necessarily all rendered at once
|
||||
|
||||
## Files Modified
|
||||
- Frontend/index.html (primary changes)
|
||||
- No backend or configuration changes required
|
||||
|
||||
## Testing Notes
|
||||
- Decimal job numbers (e.g., 3887.2, 4735) now sort correctly in descending order
|
||||
- Initial page load shows first 40 cards immediately
|
||||
- Remaining pages load in background with progress bar indication
|
||||
- Full list renders with all filters/search applied once complete
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Hono } from 'hono';
|
||||
import { serveStatic } from 'hono/bun';
|
||||
import fs from 'fs';
|
||||
// @ts-ignore Bun project may not have dotenv types configured
|
||||
import { config } from 'dotenv';
|
||||
|
||||
config();
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
// Minimal log helpers
|
||||
const logLine = (path: string, line: string) => {
|
||||
try {
|
||||
fs.appendFileSync(path, `${new Date().toISOString()} ${line}\n`);
|
||||
} catch (err) {
|
||||
console.error('Failed to write log:', err);
|
||||
}
|
||||
};
|
||||
|
||||
// Serve static files from the frontend directory
|
||||
app.use('/*', serveStatic({ root: './frontend' }));
|
||||
|
||||
// Error handler
|
||||
app.onError((err, c) => {
|
||||
logLine('logs/error.log', `Unhandled error: ${err?.message || err}`);
|
||||
return c.text('Internal Server Error', 500);
|
||||
});
|
||||
|
||||
// Mutation logging endpoint
|
||||
app.post('/log-change', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const { action = 'unknown', user = 'unknown', target = '', detail = '' } = body || {};
|
||||
const payload = JSON.stringify({ action, user, target, detail });
|
||||
logLine('logs/changes.log', payload);
|
||||
return c.json({ status: 'ok' });
|
||||
} catch (err) {
|
||||
logLine('logs/error.log', `log-change error: ${(err as Error)?.message || String(err)}`);
|
||||
return c.text('Bad Request', 400);
|
||||
}
|
||||
});
|
||||
|
||||
const PORT = Number(process.env.PORT || 3000);
|
||||
|
||||
logLine('logs/server.log', `Starting frontend server on port ${PORT}`);
|
||||
|
||||
// Graceful shutdown logging
|
||||
const shutdown = (signal: string) => {
|
||||
logLine('logs/server.log', `Shutting down due to ${signal}`);
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||
|
||||
export default {
|
||||
port: PORT,
|
||||
fetch: app.fetch,
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"lockfileVersion": 1,
|
||||
"configVersion": 0,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "job-info",
|
||||
"dependencies": {
|
||||
"@microsoft/microsoft-graph-client": "^3.0.7",
|
||||
"dotenv": "^17.2.3",
|
||||
"hono": "^4.10.8",
|
||||
"pocketbase": "^0.26.5",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest",
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@babel/runtime": ["@babel/runtime@7.28.4", "", {}, "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ=="],
|
||||
|
||||
"@microsoft/microsoft-graph-client": ["@microsoft/microsoft-graph-client@3.0.7", "", { "dependencies": { "@babel/runtime": "^7.12.5", "tslib": "^2.2.0" } }, "sha512-/AazAV/F+HK4LIywF9C+NYHcJo038zEnWkteilcxC1FM/uK/4NVGDKGrxx7nNq1ybspAroRKT4I1FHfxQzxkUw=="],
|
||||
|
||||
"@types/bun": ["@types/bun@1.3.2", "", { "dependencies": { "bun-types": "1.3.2" } }, "sha512-t15P7k5UIgHKkxwnMNkJbWlh/617rkDGEdSsDbu+qNHTaz9SKf7aC8fiIlUdD5RPpH6GEkP0cK7WlvmrEBRtWg=="],
|
||||
|
||||
"@types/node": ["@types/node@24.10.1", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ=="],
|
||||
|
||||
"@types/react": ["@types/react@19.2.4", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-tBFxBp9Nfyy5rsmefN+WXc1JeW/j2BpBHFdLZbEVfs9wn3E3NRFxwV0pJg8M1qQAexFpvz73hJXFofV0ZAu92A=="],
|
||||
|
||||
"bun-types": ["bun-types@1.3.2", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-i/Gln4tbzKNuxP70OWhJRZz1MRfvqExowP7U6JKoI8cntFrtxg7RJK3jvz7wQW54UuvNC8tbKHHri5fy74FVqg=="],
|
||||
|
||||
"csstype": ["csstype@3.2.0", "", {}, "sha512-si++xzRAY9iPp60roQiFta7OFbhrgvcthrhlNAGeQptSY25uJjkfUV8OArC3KLocB8JT8ohz+qgxWCmz8RhjIg=="],
|
||||
|
||||
"dotenv": ["dotenv@17.2.3", "", {}, "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w=="],
|
||||
|
||||
"hono": ["hono@4.10.8", "", {}, "sha512-DDT0A0r6wzhe8zCGoYOmMeuGu3dyTAE40HHjwUsWFTEy5WxK1x2WDSsBPlEXgPbRIFY6miDualuUDbasPogIww=="],
|
||||
|
||||
"pocketbase": ["pocketbase@0.26.5", "", {}, "sha512-SXcq+sRvVpNxfLxPB1C+8eRatL7ZY4o3EVl/0OdE3MeR9fhPyZt0nmmxLqYmkLvXCN9qp3lXWV/0EUYb3MmMXQ=="],
|
||||
|
||||
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
|
||||
|
||||
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
|
||||
|
||||
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// PocketBase auth bootstrap shared by pages
|
||||
(function (global) {
|
||||
const pb = new PocketBase('https://pocketbase.ccllc.pro');
|
||||
|
||||
function authHeaders() {
|
||||
if (pb.authStore.isValid && pb.authStore.token) {
|
||||
return { Authorization: `Bearer ${pb.authStore.token}` };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
function getDisplayName() {
|
||||
const model = pb.authStore.model || {};
|
||||
return (
|
||||
model.display_name ||
|
||||
model.name ||
|
||||
model.email ||
|
||||
model.username ||
|
||||
'Unknown'
|
||||
);
|
||||
}
|
||||
|
||||
async function ensureAuth() {
|
||||
if (pb.authStore.isValid) return true;
|
||||
const path = new URL(window.location.href).pathname;
|
||||
if (!path.endsWith('signin.html')) {
|
||||
window.location.href = 'signin.html';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
global.Auth = { pb, authHeaders, ensureAuth, getDisplayName };
|
||||
})(window);
|
||||
@@ -0,0 +1,459 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" maximum-scale="1" />
|
||||
<title>Job Info — Vanilla JS</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/pocketbase@0.26.5/dist/pocketbase.umd.js"></script>
|
||||
<script src="auth.js"></script>
|
||||
<style>
|
||||
|
||||
/* Basic layout */
|
||||
:root { --accent:#0d6efd; --muted:#6b7280; --card-bg:#ffffff; --card-border:#d1e7ff; }
|
||||
body{font-family:Inter,Arial,Helvetica,sans-serif;background:#f3f4f6;margin:0;color:#111; overflow:hidden; touch-action: pan-y; height:100vh; display:flex; flex-direction:column;}
|
||||
.wrap{max-width:100%;box-sizing:border-box;margin:0;padding:16px;font-size:17px;display:flex;flex-direction:column;flex:1;overflow:hidden;}
|
||||
h1{margin:0 0 12px;text-align:center;color:var(--accent);font-size:33px;font-weight:700;}
|
||||
|
||||
/* Progress */
|
||||
.progress-wrap{width:100%;background:#e6edf7;height:6px;border-radius:4px;overflow:hidden;margin-bottom:12px;}
|
||||
.progress-bar{height:100%;width:0;background:var(--accent);transition:width 0.3s ease-out;}
|
||||
|
||||
/* Search + filter toggle */
|
||||
#searchBox{width:100%;padding:10px;border-radius:8px;border:1px solid #d1d5db;margin-bottom:8px;box-sizing:border-box;font-size: 18px;}
|
||||
#searchBox::placeholder{color:#9ca3af;}
|
||||
#filterToggle{background:var(--accent);color:#fff;padding:8px 10px;border-radius:8px;border:none;cursor:pointer;margin-bottom:8px;display:inline-block;}
|
||||
|
||||
/* Filters panel */
|
||||
#filtersPanel{display:none;background:#fff;border:1px solid #e5e7eb;border-radius:8px;padding:10px;margin-bottom:10px;}
|
||||
.filter-group{margin-bottom:8px;font-size:14px;}
|
||||
.filter-group label{margin-right:8px;cursor:pointer;color:var(--muted);}
|
||||
|
||||
/* Results/cards */
|
||||
#results{display:flex;flex-direction:column;gap:12px;flex:1;overflow:auto;padding:0;}
|
||||
.card{background:var(--card-bg);border-radius:10px;padding:10px;border:1px solid #e6f0ff;box-shadow:0 6px 14px rgba(14,30,37,0.04);cursor:pointer;position:relative;display:flex;flex-direction:column;justify-content:center;box-sizing:border-box;gap:4px;}
|
||||
.card-row{display:flex;align-items:center;gap:8px;font-size:18px;line-height:1.2;margin-bottom:2px;}
|
||||
.card-label{font-weight:700;color:#374151;min-width:72px;white-space:nowrap;}
|
||||
.card-info{color:#111;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;}
|
||||
.active-dot{position:absolute;top:10px;right:10px;width:14px;height:14px;border-radius:999px;border:2px solid #fff;box-shadow:0 1px 2px rgba(0,0,0,0.12);}
|
||||
|
||||
/* Modal */
|
||||
#detailModal{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.45);align-items:flex-start;justify-content:center;padding-top:2vh;z-index:999;}
|
||||
#detailBox{margin-block-start:0;margin-block-end:0;background:#fff;border-radius:10px;padding:2px 12px 6px 10px;max-width:380px;width:92%;max-height:84vh;overflow:auto;box-sizing:border-box;}
|
||||
.h2{margin-top:0; margin-bottom:2px;margin-block-end:0;}
|
||||
.detail-table{margin-top: 0;width:100%;border-collapse:collapse;margin-bottom:4px;}
|
||||
.detail-table td{border:1px solid #eef2ff;padding:0px 6px 6px 6px;font-size:13px;vertical-align:top;}
|
||||
.detail-table td.label{width:40%;background:#fbfdff;font-weight:700;color:#374151;}
|
||||
#jobFolderLink{margin-bottom:10px;font-size:13px;}
|
||||
#jobFolderLink a, #jobFolderLink span{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||
|
||||
/* Notes */
|
||||
#jobNotes{min-height:120px;max-height:200px;overflow:auto;padding:4px;border:1px solid #e6e9ef;border-radius:4px;font-size:11px;background:transparent;white-space:pre-wrap;word-wrap:break-word;}
|
||||
#newNote{min-height:56px;max-height:120px;overflow:auto;padding:8px;border:1px solid #d7dbe3;border-radius:8px;font-size:16px;background:transparent;margin-top:6px;}
|
||||
.toolbar{display:flex;flex-wrap:wrap;margin-bottom:3px;margin-top:5px} /* small space below toolbar */
|
||||
.toolbar button{
|
||||
height:28px;
|
||||
width:32px;
|
||||
font-size:12px;
|
||||
padding:0 4px;
|
||||
border-radius:6px;
|
||||
border:1px solid #ccc;
|
||||
background:#ccc;
|
||||
color:#111;
|
||||
cursor:pointer;
|
||||
display:flex;
|
||||
align-items:center;
|
||||
justify-content:center;
|
||||
margin: 1px;
|
||||
}
|
||||
.toolbar button#tbClear{
|
||||
width:auto;
|
||||
padding:4px 8px;
|
||||
background:#9ca3af; /* slightly darker gray */
|
||||
color:#fff;
|
||||
}
|
||||
.toolbar button.active{
|
||||
background:#d1e7ff;
|
||||
color:#111;
|
||||
border-color:#0d6efd;
|
||||
}
|
||||
|
||||
.modal-actions{display:flex;gap:8px;margin-top:6px;margin-bottom:50px;}
|
||||
.btn{padding:8px 10px;border-radius:8px;border:none;color:#fff;cursor:pointer;}
|
||||
.btn.green{background:#16a34a;} .btn.gray{background:#6b7280;} .btn.red{background:#dc2626;}
|
||||
|
||||
/* Footer */
|
||||
.footer{text-align:right;font-size:12px;color:var(--muted);margin-top:20px;padding-top:12px;border-top:1px solid #e5e7eb;}
|
||||
|
||||
/* responsive small */
|
||||
@media (max-width:380px){ .wrap{padding:12px;} .card{height:98px;} }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<h1>Job Info</h1>
|
||||
|
||||
<div class="progress-wrap">
|
||||
<div id="progressBar" class="progress-bar"></div>
|
||||
</div>
|
||||
|
||||
<input id="searchBox" placeholder="Search jobs (just start typing)">
|
||||
|
||||
<button id="filterToggle">Show Filters</button>
|
||||
|
||||
<div id="filtersPanel">
|
||||
<div class="filter-group">
|
||||
<strong>Division</strong><br/>
|
||||
<label><input type="checkbox" class="filter-division" value="C#"> Commercial</label>
|
||||
<label><input type="checkbox" class="filter-division" value="R#"> Residential</label>
|
||||
<label><input type="checkbox" class="filter-division" value="S#"> Small Jobs</label>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<strong>Active</strong><br/>
|
||||
<label><input type="checkbox" class="filter-active" value="Yes"> Yes</label>
|
||||
<label><input type="checkbox" class="filter-active" value="No"> No</label>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<strong>Estimator</strong><br/>
|
||||
<label><input type="checkbox" class="filter-estimator" value="Steve Brewer"> Steve</label>
|
||||
<label><input type="checkbox" class="filter-estimator" value="Beth Cardoza"> Beth</label>
|
||||
</div>
|
||||
|
||||
<div class="filter-group">
|
||||
<strong>Status</strong><br/>
|
||||
<label><input type="checkbox" class="filter-status" value="Estimating"> Estimating</label>
|
||||
<label><input type="checkbox" class="filter-status" value="In Progress"> In Progress</label>
|
||||
<label><input type="checkbox" class="filter-status" value="Awarded"> Awarded</label>
|
||||
<label><input type="checkbox" class="filter-status" value="Billed (In Progress)"> Billed (In Progress)</label>
|
||||
<label><input type="checkbox" class="filter-status" value="Not Bidding"> Not Bidding</label>
|
||||
<label><input type="checkbox" class="filter-status" value="Est Sent"> Est Sent</label>
|
||||
<label><input type="checkbox" class="filter-status" value="Not Awarded"> Not Awarded</label>
|
||||
</div>
|
||||
<button id="clearFilters" style="background:#6b7280;color:white;padding:8px;border-radius:8px;border:none;">Clear Filters</button>
|
||||
</div>
|
||||
|
||||
<div id="results" aria-live="polite"></div>
|
||||
<div class="footer">v1.0.0-beta2</div>
|
||||
</div>
|
||||
|
||||
<!-- Detail Modal -->
|
||||
<div id="detailModal" role="dialog" aria-modal="true">
|
||||
<div id="detailBox">
|
||||
<h2 style="margin-top:0;color:var(--accent)">Job Detail</h2>
|
||||
|
||||
<table class="detail-table" id="detailTable"></table>
|
||||
|
||||
<div id="jobFolderLink"><strong>Job Folder Link</strong><div><span id="jobFolderAnchor">No Link Available</span></div></div>
|
||||
|
||||
<h3 style="margin:8px 0 6px 0">Notes</h3>
|
||||
<div id="jobNotes"></div>
|
||||
|
||||
<div class="toolbar" id="toolbar">
|
||||
<button data-cmd="bold" id="tbBold"><strong>B</strong></button>
|
||||
<button data-cmd="italic" id="tbItalic"><em>I</em></button>
|
||||
<button data-cmd="underline" id="tbUnderline"><u>U</u></button>
|
||||
<button data-cmd="foreColor" data-val="#ff0000" id="tbRed" style="color:#ef4444">A</button>
|
||||
<button data-cmd="foreColor" data-val="#0000ff" id="tbBlue" style="color:#2563eb">A</button>
|
||||
<button data-cmd="foreColor" data-val="#000000" id="tbBlack" style="color:#000">A</button>
|
||||
<button data-cmd="removeFormat" id="tbClear">Reset</button>
|
||||
</div>
|
||||
|
||||
<div id="newNote" contenteditable="true" aria-label="New note"></div>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button class="btn green" id="btnSubmit">Submit</button>
|
||||
<button class="btn gray" id="btnClearNote">Clear</button>
|
||||
<button class="btn red" id="btnClose">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(async function() {
|
||||
const { pb, authHeaders, ensureAuth, getDisplayName } = window.Auth;
|
||||
const authed = await ensureAuth();
|
||||
if (!authed) return;
|
||||
|
||||
// --- Utility ---
|
||||
const fetchNoCache = (url, options={}) => {
|
||||
const headers = { ...(options.headers||{}), ...authHeaders() };
|
||||
return fetch(url + `&_ts=${Date.now()}`, { ...options, headers });
|
||||
};
|
||||
const PB_COLLECTION_URL = "https://pocketbase.ccllc.pro/api/collections/pbc_1431294567/records";
|
||||
const NOTES_COLLECTION_URL = "https://pocketbase.ccllc.pro/api/collections/notes/records";
|
||||
const perPage = 50;
|
||||
|
||||
let jobsCache = [], visibleJobs = [], currentJob = null;
|
||||
|
||||
const progressBar = document.getElementById('progressBar');
|
||||
const searchBox = document.getElementById('searchBox');
|
||||
const resultsEl = document.getElementById('results');
|
||||
const filtersPanel = document.getElementById('filtersPanel');
|
||||
const filterToggle = document.getElementById('filterToggle');
|
||||
|
||||
const detailModal = document.getElementById('detailModal');
|
||||
const detailTable = document.getElementById('detailTable');
|
||||
const jobFolderAnchor = document.getElementById('jobFolderAnchor');
|
||||
const jobNotes = document.getElementById('jobNotes');
|
||||
const newNote = document.getElementById('newNote');
|
||||
|
||||
const toolbar = document.getElementById('toolbar');
|
||||
const tbButtons = Array.from(toolbar.querySelectorAll('button'));
|
||||
|
||||
const safeLower = v => (v||'').toString().trim().toLowerCase();
|
||||
|
||||
let progTimer=null;
|
||||
function startProgress(){
|
||||
progressBar.style.width='0%';
|
||||
if(progTimer) clearInterval(progTimer);
|
||||
let simulatedProg=0;
|
||||
progTimer=setInterval(()=>{
|
||||
if(simulatedProg<65){ simulatedProg+=0.8; progressBar.style.width=Math.min(65,simulatedProg).toFixed(1)+'%'; }
|
||||
},150);
|
||||
}
|
||||
function finishProgress(){ if(progTimer) clearInterval(progTimer); progressBar.style.width='100%'; setTimeout(()=>{progressBar.parentElement.style.display='none';},400); }
|
||||
|
||||
// --- Fetch all jobs ---
|
||||
async function fetchAllJobs(){
|
||||
startProgress(); jobsCache=[]; visibleJobs=[]; resultsEl.innerHTML = '<div style="padding:8px;color:#475569;background:#fff;border-radius:8px;border:1px solid #e6eefc">Loading…</div>';
|
||||
let page=1, totalItems=0; let firstBatchRendered=false;
|
||||
try{
|
||||
while(true){
|
||||
const url = `${PB_COLLECTION_URL}?page=${page}&perPage=${perPage}&sort=-Job_Number`;
|
||||
const res = await fetchNoCache(url);
|
||||
if(!res.ok) throw new Error(`Fetch failed: ${res.status}`);
|
||||
const data = await res.json();
|
||||
const items = data.items || [];
|
||||
jobsCache.push(...items);
|
||||
totalItems = data.totalItems || (items.length + ((page-1)*perPage));
|
||||
|
||||
// Render first 40 immediately
|
||||
if(!firstBatchRendered && jobsCache.length >= 40){
|
||||
firstBatchRendered=true;
|
||||
renderInitialBatch(jobsCache.slice(0,40));
|
||||
}
|
||||
|
||||
if(progTimer) clearInterval(progTimer);
|
||||
const realProg=Math.min(95, Math.floor((jobsCache.length / Math.max(1,totalItems)) * 95));
|
||||
progressBar.style.width=realProg+'%';
|
||||
if(jobsCache.length >= totalItems || items.length===0) break;
|
||||
page++;
|
||||
}
|
||||
finishProgress();
|
||||
applyFiltersAndRender();
|
||||
}catch(err){ finishProgress(); alert('Failed to fetch jobs: '+err.message); console.error(err);}
|
||||
}
|
||||
|
||||
function renderInitialBatch(jobs){
|
||||
resultsEl.innerHTML='';
|
||||
for(const job of jobs){
|
||||
const card=document.createElement('div'); card.className='card';
|
||||
card.innerHTML=`
|
||||
<div class="card-row"><div class="card-label">Job #:</div><div class="card-info">${escapeHtml(job.Job_Number||'')}</div></div>
|
||||
<div class="card-row"><div class="card-label">Job Name:</div><div class="card-info">${escapeHtml(job.Job_Full_Name||'')}</div></div>
|
||||
<div class="card-row"><div class="card-label">Contact:</div><div class="card-info">${escapeHtml(job.Contact_Person||'')}</div></div>
|
||||
`;
|
||||
const dot=document.createElement('div'); dot.className='active-dot';
|
||||
dot.style.background=(String(job.Active||'').toLowerCase()==='yes')?'green':((String(job.Active||'').toLowerCase()==='no')?'red':'#cbd5e1');
|
||||
card.appendChild(dot);
|
||||
card.addEventListener('click',()=>openDetail(job));
|
||||
resultsEl.appendChild(card);
|
||||
}
|
||||
}
|
||||
|
||||
function jobNumberValue(job){
|
||||
const raw = String(job.Job_Number||'');
|
||||
const match = raw.match(/[0-9]+\.?[0-9]*/);
|
||||
if(!match) return null;
|
||||
const num = parseFloat(match[0]);
|
||||
return isNaN(num) ? null : num;
|
||||
}
|
||||
|
||||
function sortJobsDescending(jobs){
|
||||
return jobs.sort((a,b)=>{
|
||||
const na = jobNumberValue(a);
|
||||
const nb = jobNumberValue(b);
|
||||
if(nb!==null && na!==null){ return nb - na; }
|
||||
if(nb!==null) return 1;
|
||||
if(na!==null) return -1;
|
||||
return String(b.Job_Number||'').localeCompare(String(a.Job_Number||''));
|
||||
});
|
||||
}
|
||||
|
||||
function applyFiltersAndRender(){
|
||||
const q = safeLower(searchBox.value||'');
|
||||
const divisionVals = Array.from(document.querySelectorAll('.filter-division:checked')).map(i=>i.value);
|
||||
const activeVals = Array.from(document.querySelectorAll('.filter-active:checked')).map(i=>i.value);
|
||||
const statusVals = Array.from(document.querySelectorAll('.filter-status:checked')).map(i=>i.value);
|
||||
const estimatorVals = Array.from(document.querySelectorAll('.filter-estimator:checked')).map(i=>i.value);
|
||||
|
||||
visibleJobs = jobsCache.filter(job=>{
|
||||
const searchable = [job.Job_Number, job.Job_Full_Name, job.Job_Address, job.Contact_Person, job.Company_Client, job.Notes].join(' ').toLowerCase();
|
||||
if(q && !searchable.includes(q)) return false;
|
||||
if(divisionVals.length && !divisionVals.includes(job.Job_Division)) return false;
|
||||
if(activeVals.length && !activeVals.includes(job.Active)) return false;
|
||||
if(statusVals.length && !statusVals.includes(job.Job_Status||'')) return false;
|
||||
if(estimatorVals.length && !estimatorVals.includes(job.Estimator||'')) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
// Data already sorted from PocketBase, only re-sort if filters applied
|
||||
if(q || divisionVals.length || activeVals.length || statusVals.length || estimatorVals.length){
|
||||
sortJobsDescending(visibleJobs);
|
||||
}
|
||||
renderCards(visibleJobs);
|
||||
}
|
||||
|
||||
function renderCards(list){
|
||||
resultsEl.innerHTML='';
|
||||
if(!list.length){ resultsEl.innerHTML = `<div style="padding:8px;color:#475569;background:#fff;border-radius:8px;border:1px solid #e6eefc">No results</div>`; return; }
|
||||
|
||||
const firstChunk = list.slice(0,20);
|
||||
const remaining = list.slice(20);
|
||||
|
||||
for(const job of firstChunk){
|
||||
const card=document.createElement('div'); card.className='card';
|
||||
card.innerHTML=`
|
||||
<div class="card-row"><div class="card-label">Job #:</div><div class="card-info">${escapeHtml(job.Job_Number||'')}</div></div>
|
||||
<div class="card-row"><div class="card-label">Job Name:</div><div class="card-info">${escapeHtml(job.Job_Full_Name||'')}</div></div>
|
||||
<div class="card-row"><div class="card-label">Contact:</div><div class="card-info">${escapeHtml(job.Contact_Person||'')}</div></div>
|
||||
`;
|
||||
const dot=document.createElement('div'); dot.className='active-dot';
|
||||
dot.style.background=(String(job.Active||'').toLowerCase()==='yes')?'green':((String(job.Active||'').toLowerCase()==='no')?'red':'#cbd5e1');
|
||||
card.appendChild(dot);
|
||||
card.addEventListener('click',()=>openDetail(job));
|
||||
resultsEl.appendChild(card);
|
||||
}
|
||||
|
||||
if(remaining.length){
|
||||
setTimeout(()=>{
|
||||
for(const job of remaining){
|
||||
const card=document.createElement('div'); card.className='card';
|
||||
card.innerHTML=`
|
||||
<div class="card-row"><div class="card-label">Job #:</div><div class="card-info">${escapeHtml(job.Job_Number||'')}</div></div>
|
||||
<div class="card-row"><div class="card-label">Job Name:</div><div class="card-info">${escapeHtml(job.Job_Full_Name||'')}</div></div>
|
||||
<div class="card-row"><div class="card-label">Contact:</div><div class="card-info">${escapeHtml(job.Contact_Person||'')}</div></div>
|
||||
`;
|
||||
const dot=document.createElement('div'); dot.className='active-dot';
|
||||
dot.style.background=(String(job.Active||'').toLowerCase()==='yes')?'green':((String(job.Active||'').toLowerCase()==='no')?'red':'#cbd5e1');
|
||||
card.appendChild(dot);
|
||||
card.addEventListener('click',()=>openDetail(job));
|
||||
resultsEl.appendChild(card);
|
||||
}
|
||||
}, 50);
|
||||
}
|
||||
}
|
||||
function escapeHtml(str){ return String(str).replaceAll('&','&').replaceAll('<','<').replaceAll('>','>'); }
|
||||
|
||||
// --- Filters ---
|
||||
filterToggle.addEventListener('click',()=>{ filtersPanel.style.display = filtersPanel.style.display==='block'?'none':'block'; filterToggle.textContent = filtersPanel.style.display==='block'?'Hide Filters':'Show Filters'; });
|
||||
searchBox.addEventListener('input',()=>applyFiltersAndRender());
|
||||
document.querySelectorAll('.filter-division').forEach(cb=>cb.addEventListener('change',()=>applyFiltersAndRender()));
|
||||
document.querySelectorAll('.filter-active').forEach(cb=>{ cb.addEventListener('change',()=>{
|
||||
if(cb.checked) document.querySelectorAll('.filter-active').forEach(o=>{if(o!==cb)o.checked=false;}); applyFiltersAndRender();
|
||||
});});
|
||||
document.querySelectorAll('.filter-estimator').forEach(cb=>{ cb.addEventListener('change',()=>{
|
||||
if(cb.checked) document.querySelectorAll('.filter-estimator').forEach(o=>{if(o!==cb)o.checked=false;}); applyFiltersAndRender();
|
||||
});});
|
||||
document.querySelectorAll('.filter-status').forEach(cb=>cb.addEventListener('change',()=>applyFiltersAndRender()));
|
||||
document.getElementById('clearFilters').addEventListener('click',()=>{
|
||||
document.querySelectorAll('.filter-division, .filter-active, .filter-status, .filter-estimator').forEach(cb=>cb.checked=false);
|
||||
applyFiltersAndRender();
|
||||
});
|
||||
|
||||
// --- Modal & Notes ---
|
||||
function openDetail(job){
|
||||
currentJob = job;
|
||||
detailTable.innerHTML = '';
|
||||
const fields = ["Job_Full_Name","Job_Number","Company_Client","Manager","Contact_Person","Phone_Number","Job_Address","Start_Date","Tax_Exempt","Job_Status"];
|
||||
for(const f of fields){
|
||||
const tr = document.createElement('tr');
|
||||
const tdLabel = document.createElement('td'); tdLabel.className='label'; tdLabel.textContent=f.replace(/_/g,' ');
|
||||
const tdVal = document.createElement('td'); tdVal.textContent=job[f]||'';
|
||||
tr.appendChild(tdLabel); tr.appendChild(tdVal); detailTable.appendChild(tr);
|
||||
}
|
||||
|
||||
// Job folder link
|
||||
jobFolderAnchor.innerHTML = '';
|
||||
if(job.Job_Folder_Link && String(job.Job_Folder_Link).trim()!==''){
|
||||
try{ const url=new URL(job.Job_Folder_Link); const a=document.createElement('a'); a.href=url.href; a.target='_blank'; a.rel='noopener noreferrer'; a.textContent=url.href; a.style.color='#0d6efd'; a.style.textDecoration='underline'; jobFolderAnchor.appendChild(a);
|
||||
}catch(e){ jobFolderAnchor.textContent='No Link Available'; jobFolderAnchor.style.color='#374151'; jobFolderAnchor.style.textDecoration='none'; }
|
||||
} else { jobFolderAnchor.textContent='No Link Available'; jobFolderAnchor.style.color='#374151'; jobFolderAnchor.style.textDecoration='none'; }
|
||||
|
||||
jobNotes.innerHTML = job.Notes || '';
|
||||
newNote.innerHTML = '';
|
||||
tbButtons.forEach(b=>b.classList.remove('active'));
|
||||
detailModal.style.display='flex';
|
||||
}
|
||||
document.getElementById('btnClose').addEventListener('click',()=>{detailModal.style.display='none';});
|
||||
|
||||
// --- Toolbar ---
|
||||
let savedSelection = null;
|
||||
function saveSelection(){ const sel=window.getSelection(); if(sel.rangeCount>0)savedSelection=sel.getRangeAt(0);}
|
||||
function restoreSelection(){ const sel=window.getSelection(); if(savedSelection){ sel.removeAllRanges(); sel.addRange(savedSelection);}}
|
||||
newNote.addEventListener('mouseup',saveSelection); newNote.addEventListener('keyup',saveSelection); newNote.addEventListener('focus',saveSelection);
|
||||
tbButtons.forEach(btn=>{
|
||||
btn.addEventListener('mousedown', e=>{
|
||||
e.preventDefault();
|
||||
restoreSelection();
|
||||
const cmd = btn.dataset.cmd;
|
||||
if(!cmd) return;
|
||||
if(cmd==='foreColor'){ const val=btn.dataset.val; document.execCommand(cmd,false,val); tbButtons.forEach(b=>{if(b.dataset.cmd==='foreColor'&&b!==btn)b.classList.remove('active');}); btn.classList.toggle('active'); }
|
||||
else if(cmd==='removeFormat'){ restoreSelection(); const sel=window.getSelection(); if(sel.rangeCount>0){ const range=sel.getRangeAt(0); let content=range.toString(); range.deleteContents(); range.insertNode(document.createTextNode(content)); range.setStartAfter(range.startContainer); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } tbButtons.forEach(b=>b.classList.remove('active')); }
|
||||
else{ document.execCommand(cmd,false,null); btn.classList.toggle('active'); }
|
||||
newNote.focus(); saveSelection();
|
||||
});
|
||||
});
|
||||
|
||||
// --- Submit Note ---
|
||||
document.getElementById('btnSubmit').addEventListener('click', async()=>{
|
||||
const html=newNote.innerHTML.trim(); if(!html){alert('Enter note text'); return;}
|
||||
const now = new Date();
|
||||
const timestamp = now.toLocaleString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: true });
|
||||
const currentUserName = getDisplayName();
|
||||
const formatted=`[${currentUserName} - ${timestamp}] [Job #${currentJob?.Job_Number||'N/A'}] ${html}\n\n`;
|
||||
const updatedNotes = formatted + (currentJob.Notes||'');
|
||||
try{
|
||||
const payloadNote = {
|
||||
Note: formatted.trim(),
|
||||
Job_Number: currentJob?.Job_Number || '', // text value
|
||||
Job_Number_Id: currentJob?.id || '' // id value
|
||||
};
|
||||
const userId = pb.authStore?.record?.id || pb.authStore?.model?.id;
|
||||
if (userId) payloadNote.user = userId;
|
||||
|
||||
const [resJob, resNote] = await Promise.all([
|
||||
fetch(`${PB_COLLECTION_URL}/${currentJob.id}`,{
|
||||
method:'PATCH',
|
||||
headers:{'Content-Type':'application/json', ...authHeaders()},
|
||||
body:JSON.stringify({Notes:updatedNotes})
|
||||
}),
|
||||
fetch(`${NOTES_COLLECTION_URL}`,{
|
||||
method:'POST',
|
||||
headers:{'Content-Type':'application/json', ...authHeaders()},
|
||||
body:JSON.stringify(payloadNote)
|
||||
})
|
||||
]);
|
||||
|
||||
if(!resJob.ok) throw new Error('Job_Info update failed: '+resJob.status);
|
||||
if(!resNote.ok){
|
||||
const errText = await resNote.text().catch(()=> '');
|
||||
throw new Error('Notes create failed: '+resNote.status+' '+errText);
|
||||
}
|
||||
|
||||
const updated=await resJob.json();
|
||||
const idx=jobsCache.findIndex(j=>j.id===currentJob.id); if(idx>=0) jobsCache[idx].Notes=updated.Notes; currentJob.Notes=updated.Notes;
|
||||
jobNotes.innerHTML=updated.Notes; newNote.innerHTML='';
|
||||
fetch('/log-change',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:'update-notes',user:currentUserName,target:currentJob.id,detail:'Job_Info notes updated + notes record created'})}).catch(()=>{});
|
||||
applyFiltersAndRender();
|
||||
}catch(err){alert('Error saving note: '+err.message); console.error(err);}
|
||||
});
|
||||
document.getElementById('btnClearNote').addEventListener('click',()=>newNote.innerHTML='');
|
||||
|
||||
// --- Init ---
|
||||
fetchAllJobs();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,216 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Sign In</title>
|
||||
<script src="https://cdn.jsdelivr.net/npm/pocketbase@0.26.5/dist/pocketbase.umd.js"></script>
|
||||
<script src="auth.js"></script>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.container {
|
||||
background: white;
|
||||
padding: 3rem;
|
||||
border-radius: 1rem;
|
||||
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
|
||||
text-align: center;
|
||||
max-width: 400px;
|
||||
width: 90%;
|
||||
}
|
||||
h1 {
|
||||
color: #333;
|
||||
margin-bottom: 0.5rem;
|
||||
font-size: 1.75rem;
|
||||
}
|
||||
p {
|
||||
color: #666;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
button {
|
||||
background: #0078d4;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.875rem 2rem;
|
||||
font-size: 1rem;
|
||||
border-radius: 0.375rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
font-weight: 500;
|
||||
}
|
||||
button:hover:not(:disabled) {
|
||||
background: #005a9e;
|
||||
}
|
||||
button:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.user-info {
|
||||
display: none;
|
||||
margin-top: 2rem;
|
||||
text-align: left;
|
||||
background: #f8f9fa;
|
||||
padding: 1.5rem;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
.user-info h2 {
|
||||
font-size: 1.125rem;
|
||||
margin-bottom: 1rem;
|
||||
color: #333;
|
||||
}
|
||||
.user-info p {
|
||||
margin-bottom: 0.75rem;
|
||||
color: #555;
|
||||
word-break: break-all;
|
||||
}
|
||||
.user-info strong {
|
||||
color: #333;
|
||||
}
|
||||
.error {
|
||||
color: #d32f2f;
|
||||
margin-top: 1rem;
|
||||
display: none;
|
||||
}
|
||||
.logout-btn {
|
||||
background: #6c757d;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
.logout-btn:hover {
|
||||
background: #5a6268;
|
||||
}
|
||||
.notes-section {
|
||||
display: none;
|
||||
margin-top: 2rem;
|
||||
text-align: left;
|
||||
}
|
||||
.notes-section h3 {
|
||||
font-size: 1rem;
|
||||
margin-bottom: 1rem;
|
||||
color: #333;
|
||||
}
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 0.375rem;
|
||||
font-family: inherit;
|
||||
font-size: 0.9rem;
|
||||
resize: vertical;
|
||||
min-height: 80px;
|
||||
}
|
||||
textarea:focus {
|
||||
outline: none;
|
||||
border-color: #0078d4;
|
||||
}
|
||||
.submit-btn {
|
||||
margin-top: 0.75rem;
|
||||
width: 100%;
|
||||
}
|
||||
.success {
|
||||
color: #2e7d32;
|
||||
margin-top: 0.75rem;
|
||||
display: none;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>Welcome</h1>
|
||||
<p>Sign in with your Microsoft account</p>
|
||||
|
||||
<button id="loginBtn" onclick="login()">Sign in with Microsoft</button>
|
||||
|
||||
<div class="error" id="error"></div>
|
||||
|
||||
<div class="user-info" id="userInfo">
|
||||
<h2>Signed in</h2>
|
||||
<p><strong>Name:</strong> <span id="displayName"></span></p>
|
||||
<p><strong>Email:</strong> <span id="email"></span></p>
|
||||
|
||||
<button id="continueBtn" style="display:none;margin-top:1rem;" onclick="goToIndex()">Continue to Job Info</button>
|
||||
<button class="logout-btn" onclick="logout()">Sign out</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const { pb, getDisplayName } = window.Auth;
|
||||
|
||||
const loginBtn = document.getElementById('loginBtn');
|
||||
const errorEl = document.getElementById('error');
|
||||
const userInfo = document.getElementById('userInfo');
|
||||
const continueBtn = document.getElementById('continueBtn');
|
||||
|
||||
function goToIndex() {
|
||||
window.location.href = 'index.html';
|
||||
}
|
||||
|
||||
function showAuthedUI(displayName, email) {
|
||||
loginBtn.style.display = 'none';
|
||||
loginBtn.disabled = false;
|
||||
loginBtn.textContent = 'Sign in with Microsoft';
|
||||
userInfo.style.display = 'block';
|
||||
continueBtn.style.display = 'block';
|
||||
document.getElementById('displayName').textContent = displayName || 'Unknown';
|
||||
document.getElementById('email').textContent = email || 'Not available';
|
||||
}
|
||||
|
||||
async function login() {
|
||||
loginBtn.disabled = true;
|
||||
loginBtn.textContent = 'Signing in...';
|
||||
errorEl.style.display = 'none';
|
||||
|
||||
try {
|
||||
const authData = await pb.collection('users').authWithOAuth2({
|
||||
provider: 'microsoft',
|
||||
});
|
||||
displayUserInfo(authData);
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error);
|
||||
errorEl.textContent = error.message || 'Authentication failed. Please try again.';
|
||||
errorEl.style.display = 'block';
|
||||
loginBtn.disabled = false;
|
||||
loginBtn.textContent = 'Sign in with Microsoft';
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
pb.authStore.clear();
|
||||
loginBtn.style.display = 'block';
|
||||
userInfo.style.display = 'none';
|
||||
continueBtn.style.display = 'none';
|
||||
loginBtn.disabled = false;
|
||||
loginBtn.textContent = 'Sign in with Microsoft';
|
||||
}
|
||||
|
||||
function displayUserInfo(authData) {
|
||||
const displayName = getDisplayName();
|
||||
const email = authData?.meta?.rawUser?.email || authData?.record?.email || pb.authStore.model?.email || 'Not available';
|
||||
showAuthedUI(displayName, email);
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (pb.authStore.isValid) {
|
||||
try {
|
||||
const authData = await pb.collection('users').authRefresh();
|
||||
displayUserInfo(authData);
|
||||
} catch (err) {
|
||||
pb.authStore.clear();
|
||||
logout();
|
||||
}
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "job-info-pb",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "bun run backend/server.ts",
|
||||
"start": "bun run backend/server.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "latest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": "^5"
|
||||
},
|
||||
"dependencies": {
|
||||
"dotenv": "^17.2.3",
|
||||
"hono": "^4.10.8",
|
||||
"pocketbase": "^0.26.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
trap "echo 'Server stopped by user'; exit 0" SIGINT
|
||||
|
||||
MAX_BACKOFF=60
|
||||
FAIL_COUNT=0
|
||||
PID_FILE="bun.pid"
|
||||
PORT=${PORT:-3000}
|
||||
ENTRYPOINT="backend/server.ts"
|
||||
|
||||
mkdir -p logs
|
||||
|
||||
while true; do
|
||||
# Check if previous server PID exists
|
||||
if [ -f "$PID_FILE" ]; then
|
||||
PREV_PID=$(cat "$PID_FILE")
|
||||
if ps -p $PREV_PID > /dev/null 2>&1; then
|
||||
echo "Previous server (PID $PREV_PID) still running. Waiting 2 seconds..."
|
||||
sleep 2
|
||||
continue
|
||||
else
|
||||
# Clean up stale PID file
|
||||
rm "$PID_FILE"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "Starting Bun server on port $PORT..." | tee -a logs/server.log
|
||||
|
||||
# Start Bun in background and store PID
|
||||
bun run $ENTRYPOINT 2>&1 | tee -a logs/server.log &
|
||||
SERVER_PID=$!
|
||||
echo $SERVER_PID > "$PID_FILE"
|
||||
|
||||
# Wait for server to exit
|
||||
wait $SERVER_PID
|
||||
EXIT_CODE=$?
|
||||
|
||||
echo "Server exited with code $EXIT_CODE" | tee -a logs/server.log
|
||||
|
||||
# Remove PID file
|
||||
rm -f "$PID_FILE"
|
||||
|
||||
# Backoff logic
|
||||
FAIL_COUNT=$((FAIL_COUNT + 1))
|
||||
BACKOFF=$((2 ** FAIL_COUNT))
|
||||
[ $BACKOFF -gt $MAX_BACKOFF ] && BACKOFF=$MAX_BACKOFF
|
||||
JITTER=$((RANDOM % 4))
|
||||
SLEEP_TIME=$((BACKOFF + JITTER))
|
||||
|
||||
echo "Restarting in $SLEEP_TIME seconds (failures: $FAIL_COUNT)..." | tee -a logs/server.log
|
||||
sleep $SLEEP_TIME
|
||||
|
||||
if [ $FAIL_COUNT -ge 10 ]; then
|
||||
echo "High number of failures — cooling down for 5 minutes..." | tee -a logs/server.log
|
||||
sleep 300
|
||||
FAIL_COUNT=0
|
||||
fi
|
||||
|
||||
done
|
||||
Reference in New Issue
Block a user