Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
375 lines (336 loc) · 17.4 KB
/
Copy pathapp.py
File metadata and controls
375 lines (336 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python3
"""
ChemSafeSync — Production Web Control Hub & API Dashboard
Provides a clean, ultra-responsive Web Dashboard for Safety Directors to manage SKUs,
run automated SDS compliance audits, and download OSHA compliance reports.
"""
import os
import json
import logging
from flask import Flask, render_template_string, jsonify, request, send_file
from pathlib import Path
from database_manager import DatabaseManager
from sds_orchestrator import SDSComplianceOrchestrator
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("ChemSafeSyncWeb")
app = Flask(__name__)
db = DatabaseManager()
DASHBOARD_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>🧪 ChemSafeSync | OSHA SDS Compliance Control Hub</title>
<style>
:root {
--bg: #090C15;
--card: #111625;
--border: rgba(255, 255, 255, 0.08);
--text: #F0F4F8;
--muted: #8E9BAE;
--accent-green: #00FF66;
--accent-red: #FF3366;
--accent-blue: #00E5FF;
--accent-yellow: #FFCC00;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background: var(--bg); color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
padding: 24px; max-width: 1200px; margin: 0 auto;
}
.header {
display: flex; justify-content: space-between; align-items: center;
padding-bottom: 20px; border-bottom: 1px solid var(--border); margin-bottom: 24px;
}
.brand { font-size: 22px; font-weight: 800; color: var(--accent-green); display: flex; align-items: center; gap: 10px; }
.status-badge {
background: rgba(0, 255, 102, 0.15); color: var(--accent-green);
padding: 6px 14px; border-radius: 20px; font-size: 12px; font-weight: 700;
border: 1px solid rgba(0, 255, 102, 0.3); display: flex; align-items: center; gap: 6px;
}
.dot { width: 8px; height: 8px; background: var(--accent-green); border-radius: 50%; box-shadow: 0 0 8px var(--accent-green); }
.grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 24px; }
.card { background: var(--card); border: 1px solid var(--border); padding: 20px; border-radius: 14px; }
.label { font-size: 12px; color: var(--muted); font-weight: 600; text-transform: uppercase; margin-bottom: 6px; }
.val { font-size: 28px; font-weight: 800; color: #FFF; }
.sub { font-size: 12px; color: var(--accent-green); font-weight: 700; margin-top: 4px; }
.action-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.btn {
padding: 12px 20px; border-radius: 10px; font-weight: 800; font-size: 13px;
border: none; cursor: pointer; transition: all 0.2s; display: inline-flex; align-items: center; gap: 8px;
}
.btn-primary { background: linear-gradient(135deg, #00FF66, #00B347); color: #000; box-shadow: 0 4px 15px rgba(0, 255, 102, 0.3); }
.btn-secondary { background: rgba(255, 255, 255, 0.08); color: var(--text); border: 1px solid var(--border); }
.btn:hover { opacity: 0.9; transform: translateY(-1px); }
table { width: 100%; border-collapse: collapse; background: var(--card); border-radius: 14px; overflow: hidden; border: 1px solid var(--border); }
th, td { padding: 14px 18px; text-align: left; font-size: 13px; border-bottom: 1px solid var(--border); }
th { background: rgba(255, 255, 255, 0.03); color: var(--muted); font-weight: 700; text-transform: uppercase; font-size: 11px; }
.badge { padding: 4px 10px; border-radius: 6px; font-size: 11px; font-weight: 800; text-transform: uppercase; }
.badge-verified { background: rgba(0, 255, 102, 0.15); color: var(--accent-green); border: 1px solid rgba(0, 255, 102, 0.3); }
.badge-outdated { background: rgba(255, 51, 102, 0.15); color: var(--accent-red); border: 1px solid rgba(255, 51, 102, 0.3); }
.badge-pending { background: rgba(255, 204, 0, 0.15); color: var(--accent-yellow); border: 1px solid rgba(255, 204, 0, 0.3); }
</style>
</head>
<body>
<div class="header">
<div class="brand">🧪 ChemSafeSync</div>
<div class="status-badge"><span class="dot"></span> OSHA COMPLIANCE MONITOR ACTIVE</div>
</div>
<div class="grid">
<div class="card">
<div class="label">OSHA Score</div>
<div class="val" style="color: var(--accent-green);">{{ audit.compliance_score_pct }}%</div>
<div class="sub">Verified Compliant</div>
</div>
<div class="card">
<div class="label">Total Chemical SKUs</div>
<div class="val">{{ audit.total_skus }}</div>
<div class="sub" style="color: var(--accent-blue);">Active Inventory</div>
</div>
<div class="card">
<div class="label">Verified Up-To-Date</div>
<div class="val" style="color: var(--accent-green);">{{ audit.verified_skus }}</div>
<div class="sub">16-Section Standardized</div>
</div>
<div class="card">
<div class="label">Outdated Revisions</div>
<div class="val" style="color: var(--accent-red);">{{ audit.outdated_skus }}</div>
<div class="sub" style="color: var(--accent-red);">Requires Update</div>
</div>
</div>
<div id="toastBanner" style="display:none;background:rgba(0,255,102,0.15);border:1px solid var(--accent-green);color:var(--accent-green);padding:12px 18px;border-radius:10px;margin-bottom:20px;font-weight:700;font-size:13px;"></div>
<div style="background:linear-gradient(135deg, rgba(0,255,102,0.1), rgba(0,229,255,0.05));border:1px solid var(--accent-green);padding:20px;border-radius:14px;margin-bottom:24px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px;">
<div>
<h3 style="color:var(--accent-green);font-size:18px;font-weight:800;margin-bottom:4px;">🧪 ChemSafeSync Enterprise Pro Tier</h3>
<p style="font-size:13px;color:var(--muted);">Automated GHS 16-section SDS revision monitoring & vendor sync for 500+ SKUs.</p>
</div>
<div style="display:flex;align-items:center;gap:12px;">
<span style="font-size:22px;font-weight:800;color:#fff;">$299 <span style="font-size:13px;color:var(--muted);">/ mo</span></span>
<a href="/checkout" class="btn btn-primary" style="text-decoration:none;background:linear-gradient(135deg, #00FF66, #00B347);color:#000;font-size:14px;padding:12px 22px;box-shadow:0 0 15px rgba(0,255,102,0.4);">💳 Start 14-Day Free Trial</a>
</div>
</div>
<div class="action-bar">
<h3 style="font-size: 18px; font-weight: 700;">Chemical Inventory & Safety Data Sheets (SDSs)</h3>
<div style="display:flex; gap:10px; flex-wrap:wrap;">
<label class="btn btn-secondary" style="cursor:pointer;">
📤 Upload CSV Inventory
<input type="file" id="csvFileInput" accept=".csv" style="display:none;" onchange="uploadCSV(this)">
</label>
<button class="btn btn-secondary" style="border-color:var(--accent-red);color:var(--accent-red);" onclick="loadFailingScenario()">⚠️ Load Failing Test Scenario (33.3% Score)</button>
<button class="btn btn-secondary" style="border-color:var(--accent-green);color:var(--accent-green);" onclick="loadCompliantScenario()">🟢 Reset Compliant Scenario (100% Score)</button>
<button class="btn btn-secondary" onclick="runAudit()">🔄 Run Live Vendor Audit</button>
<a href="/report" target="_blank" class="btn btn-primary" style="text-decoration:none;background:rgba(255,255,255,0.08);color:#fff;border:1px solid var(--border);">📄 Download Executive Audit PDF</a>
</div>
</div>
<script>
function activateTrialDirect() {
const email = prompt("Enter your Work Email Address to activate your 14-Day Enterprise Trial:", "safety.director@apexchemical.com");
if(!email) return;
fetch('/api/subscribe_direct', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: email, company: "Apex Industrial Chemical Corp" })
})
.then(r => r.json())
.then(data => {
alert('🎉 14-DAY ENTERPRISE FREE TRIAL ACTIVATED!\nWelcome ' + email + '!\nYour Enterprise Pro dashboard is unlocked ($299/mo after 14 days).');
window.location.href = '/report';
});
}
</script>
<table>
<thead>
<tr>
<th>SKU Code</th>
<th>Product Chemical Name</th>
<th>CAS Registry No.</th>
<th>Supplier Vendor</th>
<th>Revision Date</th>
<th>OSHA Status</th>
</tr>
</thead>
<tbody>
{% for item in inventory %}
<tr>
<td><strong>{{ item.sku }}</strong></td>
<td>{{ item.product_name }}</td>
<td><code style="color: var(--accent-blue);">{{ item.cas_number or 'N/A' }}</code></td>
<td>{{ item.supplier_name }}</td>
<td>{{ item.current_revision_date or 'N/A' }}</td>
<td>
{% if item.status == 'VERIFIED' %}
<span class="badge badge-verified">VERIFIED</span>
{% elif item.status == 'OUTDATED' %}
<span class="badge badge-outdated">OUTDATED</span>
{% else %}
<span class="badge badge-pending">{{ item.status }}</span>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
function loadFailingScenario() {
if(!confirm("Load Non-Compliant test dataset with 10 outdated 2018-2021 SDS sheets?")) return;
fetch('/api/load_failing_dataset', { method: 'POST' })
.then(r => r.json())
.then(data => {
alert('⚠️ FAILING SCENARIO LOADED!\nTotal SKUs: ' + data.total_skus + '\nOutdated SKUs: ' + data.outdated_skus + '\nOSHA Compliance Score: ' + data.compliance_score_pct + '%');
location.reload();
});
}
function loadCompliantScenario() {
fetch('/api/load_compliant_dataset', { method: 'POST' })
.then(r => r.json())
.then(data => {
alert('🟢 COMPLIANT 50-SKU DATASET RESTORED!\nOSHA Compliance Score: ' + data.compliance_score_pct + '%');
location.reload();
});
}
function uploadCSV(input) {
const file = input.files[0];
if(!file) return;
const formData = new FormData();
formData.append('file', file);
fetch('/api/upload_csv', { method: 'POST', body: formData })
.then(r => r.json())
.then(data => {
alert('✅ CSV Inventory Uploaded Successfully!\nLoaded ' + data.total_skus + ' SKUs.\nNew Compliance Score: ' + data.compliance_score_pct + '%');
location.reload();
})
.catch(err => alert('Upload error: ' + err));
}
function runAudit() {
const btn = document.querySelector('.btn-secondary');
const toast = document.getElementById('toastBanner');
btn.disabled = true;
btn.innerText = '⚡ Auditing SKUs...';
toast.style.display = 'block';
toast.style.background = 'rgba(0, 229, 255, 0.15)';
toast.style.borderColor = 'var(--accent-blue)';
toast.style.color = 'var(--accent-blue)';
toast.innerHTML = '⏳ <strong>AUDIT IN PROGRESS:</strong> Parsing GHS 16-section SDS files across inventory...';
fetch('/api/audit', { method: 'POST' })
.then(r => r.json())
.then(data => {
btn.disabled = false;
btn.innerText = '🔄 Run Live Vendor Audit';
toast.style.background = data.compliance_score_pct < 80 ? 'rgba(255, 51, 102, 0.15)' : 'rgba(0, 255, 102, 0.15)';
toast.style.borderColor = data.compliance_score_pct < 80 ? 'var(--accent-red)' : 'var(--accent-green)';
toast.style.color = data.compliance_score_pct < 80 ? 'var(--accent-red)' : 'var(--accent-green)';
toast.innerHTML = '✅ <strong>AUDIT COMPLETE!</strong> OSHA Score: <strong>' + data.compliance_score_pct + '%</strong> | Outdated SKUs: <strong>' + data.outdated_skus + '</strong>';
const valCards = document.querySelectorAll('.val');
if (valCards.length >= 4) {
valCards[0].innerText = data.compliance_score_pct + '%';
valCards[1].innerText = data.total_skus;
valCards[2].innerText = data.verified_skus;
valCards[3].innerText = data.outdated_skus;
}
});
}
</script>
<script src="/static/protodex-companion-widget.js"></script>
</body>
</html>
"""
@app.route("/")
def index():
client = db.get_client(1)
inventory = db.get_inventory(1)
audit = db.record_audit(1)
return render_template_string(DASHBOARD_HTML, client=client, inventory=inventory, audit=audit)
@app.route("/api/audit", methods=["POST"])
def api_audit():
orchestrator = SDSComplianceOrchestrator(client_id=1)
res = orchestrator.run_full_compliance_audit()
return jsonify(res)
@app.route("/api/load_failing_dataset", methods=["POST"])
def api_load_failing():
count = db.load_failing_sample_dataset(1)
audit = db.record_audit(1)
return jsonify(audit)
@app.route("/api/load_compliant_dataset", methods=["POST"])
def api_load_compliant():
count = db.load_compliant_sample_dataset(1)
audit = db.record_audit(1)
return jsonify(audit)
@app.route("/api/upload_csv", methods=["POST"])
def api_upload_csv():
if 'file' not in request.files:
return jsonify({"error": "No file uploaded"}), 400
file = request.files['file']
csv_str = file.read().decode('utf-8', errors='ignore')
count = db.replace_inventory_from_csv(1, csv_str)
audit = db.record_audit(1)
return jsonify(audit)
CHECKOUT_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>🧪 ChemSafeSync | Start 14-Day Enterprise Trial</title>
<style>
body { background: #090C15; color: #F0F4F8; font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; }
.card { background: #111625; border: 1px solid #00FF66; padding: 36px; border-radius: 16px; max-width: 480px; width: 90%; box-shadow: 0 0 30px rgba(0,255,102,0.2); }
h2 { color: #00FF66; font-size: 24px; margin-bottom: 8px; }
p { color: #8E9BAE; font-size: 13px; margin-bottom: 20px; line-height: 1.5; }
.price-box { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); padding: 16px; border-radius: 10px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; }
input { width: 100%; padding: 12px; border-radius: 8px; background: #090C15; border: 1px solid rgba(255,255,255,0.1); color: #fff; font-size: 14px; margin-bottom: 14px; box-sizing: border-box; }
.btn { width: 100%; padding: 14px; background: linear-gradient(135deg, #00FF66, #00B347); color: #000; border: none; border-radius: 10px; font-weight: 800; font-size: 15px; cursor: pointer; }
.btn:hover { opacity: 0.9; }
.back-link { display: block; text-align: center; margin-top: 16px; color: #8E9BAE; text-decoration: none; font-size: 13px; }
</style>
</head>
<body>
<div class="card">
<h2>🧪 ChemSafeSync Enterprise</h2>
<p>Automated GHS 16-section SDS revision monitoring, vendor sync, and monthly PDF compliance audits for 500+ SKUs.</p>
<div class="price-box">
<span style="font-weight:700;">Enterprise Plan</span>
<span style="font-weight:800;font-size:22px;color:#00FF66;">$299 / mo</span>
</div>
<form method="POST" action="/checkout">
<label style="font-size:11px;color:#8E9BAE;font-weight:700;display:block;margin-bottom:6px;">WORK EMAIL ADDRESS</label>
<input type="email" name="email" required placeholder="safety.director@apexchemical.com">
<label style="font-size:11px;color:#8E9BAE;font-weight:700;display:block;margin-bottom:6px;">COMPANY / FACILITY NAME</label>
<input type="text" name="company" required placeholder="Apex Chemical Logistics Corp">
<button type="submit" class="btn">⚡ Activate 14-Day Free Trial ($299/mo)</button>
</form>
<a href="/" class="back-link">← Return to Dashboard</a>
</div>
</body>
</html>
"""
@app.route("/checkout", methods=["GET", "POST"])
def checkout():
if request.method == "POST":
email = request.form.get("email", "client@apexchemical.com")
company = request.form.get("company", "Apex Chemical Logistics Corp")
client_id = db.register_client("Safety Director", company, email, "TrialPass123!", "Enterprise")
logger.info(f"🎉 14-Day Enterprise Trial Activated for {company} ({email})")
return f"""
<script>
alert('🎉 14-DAY ENTERPRISE FREE TRIAL ACTIVATED!\\n\\nWelcome {company}!\\nYour Enterprise Pro dashboard is unlocked.');
window.location.href = '/?subscribed=true';
</script>
"""
return render_template_string(CHECKOUT_HTML)
@app.route("/report")
def download_report():
client = db.get_client(1)
inventory = db.get_inventory(1)
audit = db.record_audit(1)
from compliance_report_generator import ComplianceReportGenerator
rep_gen = ComplianceReportGenerator()
path = rep_gen.generate_html_report(client, inventory, audit)
return send_file(path)
@app.route("/static/protodex-companion-widget.js")
def protodex_widget():
with open("/Users/apple/Documents/products/protodex-ai-companions/protodex-companion-widget.js", "r") as f:
return f.read(), 200, {"Content-Type": "application/javascript"}
if __name__ == "__main__":
logger.info("⚡ Launching ChemSafeSync Web Dashboard on port 8095...")
app.run(host="0.0.0.0", port=8095, debug=False)