# AssetFlow — Hulhudhuffaaru Health Centre

## What is included
An administrative application with a Google Apps Script backend and Google Sheets database. No alternative database is used. Sample records in the disconnected workspace are read-only and never seeded into Google Sheets.

## 1. Create the backend
1. Visit https://script.google.com/home/start and create a standalone project named **AssetFlow Health Centre**.
2. Download **Apps Script Source** from the application's Settings page.
3. Replace the contents of `Code.gs` with the downloaded file. Save.
4. Select `initializeDatabase` from the function selector and click Run.
5. Authorize access to Google Sheets and Google Drive. Google may display an unverified-app warning for your own script; review the code and only proceed if you trust your own project.
6. Find the spreadsheet URL in the execution log. The script creates **ASSET MANAGEMENT DATABASE** and eight worksheets. It creates the ten required categories, but no sample assets or locations.
7. Your spreadsheet and document folder remain private. Do not publish them to the web.

Re-running initialization preserves records and unrelated worksheets. It stops on incompatible existing headers rather than overwriting them. ASSETS includes an additional Document Links column for Drive uploads.

## 2. Create your administrator
1. Under Apps Script **Project Settings → Script properties**, optionally add `ADMIN_EMAIL` and `ADMIN_NAME`. If omitted, your executing Google account's email is used with the name “Health Centre Administrator”.
2. Run `setupAdministrator`.
3. Copy the generated 64-character personal access key from the execution log. Treat it as a password and share it only with that administrator. This key is high entropy; its SHA-256 digest, never its raw value, is stored in private Script properties.
4. Do not run setup again for an existing account. For recovery set `RESET_USER_EMAIL` in Script properties and run `resetUserAccessKey` as the script owner. This replaces the user's key and invalidates remembered sessions immediately; ordinary sessions expire within one hour.

## 3. Deploy Google Apps Script
1. Choose **Deploy → New deployment → Web app**.
2. Set **Execute as: Me**, and **Who has access: Anyone**.
3. Click Deploy. Copy the URL ending in `/exec`, not the editor URL or `/dev` testing URL.
4. The public endpoint exposes no records without a valid session. Email + personal access key sign-in is required. Every operation enforces roles in Apps Script.
5. Google Workspace policies may prevent public deployments. Confirm that your organization permits this deployment before using the app. This connection cannot be tested until deployment exists.
6. When changing backend code, use **Manage deployments → Edit → New version → Deploy**.

## 4. Connect the app
1. Open **Settings** in AssetFlow.
2. Paste the deployed URL.
3. Enter your authorized email and generated personal access key.
4. Select **Connect & Sign In**. Sample records disappear and the actual spreadsheet loads.
5. Create locations and suppliers first. Then register your assets.
6. Create other users from **User Management**. Their unique access keys appear once in the success message. Copy and share each privately.

The connection URL and email are remembered on this device in encrypted, HttpOnly cookies. With **Keep me signed in** selected, a separate opaque session restores sign-in for up to 30 days; the personal access key is never saved. Sessions are sent to Google only by the app's secure server. No organizational records are stored in cookies, localStorage or the Cloud database. Sign Out revokes the session but remembers URL/email; Forget Connection also removes saved connection details. Reauthentication is required after expiry, key reset, deactivation, clearing cookies, or explicit sign-out. Avoid remembered sign-in on shared devices. Connections do not transfer to other browsers or domains.

**Existing installations:** replace Code.gs with the latest source, then **Manage deployments → Edit → New version → Deploy**, keeping the same URL. Sign in once afterward. Old deployments still support one-hour restored sessions, but cannot provide 30-day sign-in. The app's `ASSETFLOW_SESSION_SECRET` is managed securely in Lovable Cloud; publish the updated app to activate it on the live site. Cloud provides secure server-side session handling only; Google Sheets remains the sole records database and Google Drive remains document storage.

## 5. Roles and security
- Administrator: full access, including deletion, users, categories, locations and suppliers.
- Asset Manager: register and edit assets, transfer assets, record maintenance, verify and export reports.
- Viewer: read records and authorized reports only.
- Sheets and Drive permissions are separate from app roles. Keep the spreadsheet accessible only to its owners. Share necessary Drive folders with authorized Google accounts explicitly; the application never makes documents publicly accessible.
- Ordinary sessions expire within one hour. Remembered sessions expire after 30 days, use hashed-token records in private Script properties, are capped at 10 devices per user, and are revoked on sign-out or key reset. User status and current role are checked on every request. Failed login attempts are throttled per email for 15 minutes. Apps Script CacheService is best-effort, not a hardened distributed rate limiter.
- Writes use ScriptLock to prevent simultaneous conflicts. Spreadsheet updates and the activity log are serialized, but Google Sheets has no transactional rollback; make periodic backups and audit logs if a Google service operation fails.
- QR codes contain only an inventory number, not confidential asset details. Record lookup still requires sign-in for live data.
- Do not share the Apps Script project itself with untrusted users; project editors can access Script properties.

## 6. Documents and QR labels
Open an asset's details to upload photographs or PDF/Word supporting documents (up to 5 MB). Each asset has its own private Drive folder. Download QR codes from asset details. Browser printing currently prints the asset details together with its QR code. QR scanning uses the browser's BarcodeDetector API; use Chrome on Android when available. Manual inventory lookup works on all supported browsers.

## 7. Reports
Select Reports to filter and export PDF, Excel or printable records. PDF reports include the centre's name, report title, timestamp and page numbers. Useful-life reports use a 90-day warning window. Straight-line depreciation assumes zero salvage value and is an estimate, not an accounting ledger. Expiry never changes an asset's condition or disposes of it.

## 8. Acceptance tests after deployment
Use dedicated temporary records rather than real inventory:
1. Sign in as administrator. Add a location and a supplier.
2. Register `E18SM-97-3-35-1`; confirm the new ASSETS row, dashboard totals and activity log.
3. Try the same number again; confirm duplicate rejection. Try an invalid number and a negative cost; both must fail.
4. Change an asset's condition; inspect the dated user-attributed activity log.
5. Transfer an asset; verify its current location and the ASSET TRANSFERS history.
6. Register maintenance; confirm the linked record and next maintenance date.
7. Upload a small PDF; confirm a private Drive file and link in ASSETS.
8. Download and scan its QR code. Verify the asset and confirm the activity log.
9. Export PDF/Excel and confirm filter results and organization name.
10. Create a Viewer and Asset Manager; sign in separately. Confirm Viewer writes and Manager deletes are rejected by the backend, not only the screen.
11. Use two browser windows to register the same number concurrently; one must fail.
12. Delete the temporary asset as administrator; confirm removal, log entry and preserved history.
13. Create an expired test asset; confirm that its condition is not changed automatically.
14. With Keep me signed in selected, reload and close/reopen the browser; confirm live records reload without entering connection details. Sign out; confirm records disappear and URL/email stay remembered. Forget Connection; confirm URL/email are removed. Confirm inactive accounts and reset access keys invalidate remembered sessions.

## Operational notes
Automatic synchronization is every five minutes during an active session; manual refresh is available. Apps Script and Sheets are quota-limited. Only encrypted session and connection cookies persist in the browser, never organizational records or access keys. Currency is Maldivian rufiyaa (MVR). Live acceptance testing against the user's deployed spreadsheet is required before production use.
