Spaces:
Sleeping
Sleeping
Commit ·
caf3667
1
Parent(s): c13f602
feat: complete shipping email segregation and extraction system with traceback UI
Browse files- .gitignore +21 -0
- Procfile +1 -0
- app.py +52 -0
- classification/__init__.py +0 -0
- classification/classifier.py +96 -0
- classification/training_data.py +101 -0
- config.py +10 -0
- data/.gitkeep +0 -0
- database/__init__.py +0 -0
- database/db.py +24 -0
- database/models.py +141 -0
- extraction/__init__.py +0 -0
- extraction/cargo_tc_extractor.py +160 -0
- extraction/cargo_vc_extractor.py +180 -0
- extraction/extractor.py +33 -0
- extraction/tonnage_extractor.py +259 -0
- ingestion/__init__.py +0 -0
- ingestion/email_parser.py +133 -0
- render.yaml +13 -0
- requirements.txt +8 -0
- routes/__init__.py +0 -0
- routes/cargo_tc.py +112 -0
- routes/cargo_vc.py +112 -0
- routes/emails.py +221 -0
- routes/matching.py +235 -0
- routes/stats.py +86 -0
- routes/tonnage.py +116 -0
- seed.py +347 -0
- static/css/styles.css +1043 -0
- static/index.html +188 -0
- static/js/api.js +66 -0
- static/js/app.js +215 -0
- static/js/utils.js +88 -0
- static/js/views/cargo_tc.js +124 -0
- static/js/views/cargo_vc.js +124 -0
- static/js/views/dashboard.js +166 -0
- static/js/views/history.js +84 -0
- static/js/views/inbox.js +259 -0
- static/js/views/matching.js +157 -0
- static/js/views/tonnage.js +133 -0
- tests/test_pipeline.py +90 -0
.gitignore
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*.pyo
|
| 4 |
+
*.pyd
|
| 5 |
+
.Python
|
| 6 |
+
env/
|
| 7 |
+
venv/
|
| 8 |
+
.venv/
|
| 9 |
+
*.egg
|
| 10 |
+
*.egg-info/
|
| 11 |
+
dist/
|
| 12 |
+
build/
|
| 13 |
+
.eggs/
|
| 14 |
+
*.log
|
| 15 |
+
.env
|
| 16 |
+
.DS_Store
|
| 17 |
+
*.db
|
| 18 |
+
*.sqlite3
|
| 19 |
+
classification/model.pkl
|
| 20 |
+
.idea/
|
| 21 |
+
.vscode/
|
Procfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
web: gunicorn app:app --bind 0.0.0.0:$PORT --workers 2 --timeout 120
|
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from flask import Flask, send_from_directory
|
| 3 |
+
from flask_cors import CORS
|
| 4 |
+
|
| 5 |
+
from database.db import init_db
|
| 6 |
+
from routes.emails import emails_bp
|
| 7 |
+
from routes.tonnage import tonnage_bp
|
| 8 |
+
from routes.cargo_vc import cargo_vc_bp
|
| 9 |
+
from routes.cargo_tc import cargo_tc_bp
|
| 10 |
+
from routes.stats import stats_bp
|
| 11 |
+
from routes.matching import matching_bp
|
| 12 |
+
|
| 13 |
+
app = Flask(__name__, static_folder='static', static_url_path='')
|
| 14 |
+
CORS(app)
|
| 15 |
+
|
| 16 |
+
# ── API blueprints ─────────────────────────────────────────────────────────────
|
| 17 |
+
app.register_blueprint(emails_bp, url_prefix='/api')
|
| 18 |
+
app.register_blueprint(tonnage_bp, url_prefix='/api')
|
| 19 |
+
app.register_blueprint(cargo_vc_bp, url_prefix='/api')
|
| 20 |
+
app.register_blueprint(cargo_tc_bp, url_prefix='/api')
|
| 21 |
+
app.register_blueprint(stats_bp, url_prefix='/api')
|
| 22 |
+
app.register_blueprint(matching_bp, url_prefix='/api')
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ── Frontend SPA ──────────────────────────────────────────────────────────────
|
| 26 |
+
@app.route('/')
|
| 27 |
+
def index():
|
| 28 |
+
return send_from_directory(app.static_folder, 'index.html')
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@app.route('/<path:path>')
|
| 32 |
+
def catch_all(path):
|
| 33 |
+
# Serve static files; fall back to index.html for SPA routing
|
| 34 |
+
full_path = os.path.join(app.static_folder, path)
|
| 35 |
+
if os.path.isfile(full_path):
|
| 36 |
+
return send_from_directory(app.static_folder, path)
|
| 37 |
+
return send_from_directory(app.static_folder, 'index.html')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# ── Startup ───────────────────────────────────────────────────────────────────
|
| 41 |
+
def startup():
|
| 42 |
+
init_db()
|
| 43 |
+
# Import classifier to trigger training at startup (fast, ~1 s)
|
| 44 |
+
from classification.classifier import classify # noqa: F401
|
| 45 |
+
print("[ShipSeg] Database initialised. Classifier ready.")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
startup()
|
| 49 |
+
|
| 50 |
+
if __name__ == '__main__':
|
| 51 |
+
port = int(os.environ.get('PORT', 5000))
|
| 52 |
+
app.run(host='0.0.0.0', port=port, debug=False)
|
classification/__init__.py
ADDED
|
File without changes
|
classification/classifier.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import re
|
| 3 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 4 |
+
from sklearn.linear_model import LogisticRegression
|
| 5 |
+
from sklearn.pipeline import Pipeline
|
| 6 |
+
from classification.training_data import TONNAGE_SAMPLES, CARGO_VC_SAMPLES, CARGO_TC_SAMPLES
|
| 7 |
+
|
| 8 |
+
# ── Confidence threshold below which we fall back to keyword rules ──────────
|
| 9 |
+
CONFIDENCE_THRESHOLD = 0.55
|
| 10 |
+
|
| 11 |
+
# ── Keyword rule sets (based on real shipping email patterns) ────────────────
|
| 12 |
+
TONNAGE_KEYWORDS = [
|
| 13 |
+
r'\bopen\s+[a-z]', r'\bdwt\b', r'\bbuilt\s*\d{4}', r'\bblt\s*\d{4}',
|
| 14 |
+
r'\bloa\b', r'\beeta\b', r'\bscrubber\b', r'\bspeed.{0,20}cons',
|
| 15 |
+
r'\bballast\b', r'\bbeam\b', r'\bgrain\s*cap', r'\bflag\b.*\bclass\b',
|
| 16 |
+
r'\bopen\s+vessel', r'\bvessel\s+position', r'\bour\s+direct\s+ow',
|
| 17 |
+
r'\bopen\s+as\s+follows', r'\bdirect\s+ow', r'o/a\s+\d',
|
| 18 |
+
]
|
| 19 |
+
CARGO_VC_KEYWORDS = [
|
| 20 |
+
r'\bload\s*port\b', r'\bdischarge\s*port\b', r'\blaycan\b',
|
| 21 |
+
r'\bpol\b', r'\bpod\b', r'\bfios\b', r'\bpwwd\b', r'\bsshex\b',
|
| 22 |
+
r'\blp\s*:', r'\bdp\s*:', r'\bload\s*rate\b', r'\bvoyage\s*charter\b',
|
| 23 |
+
r'\bmts\b.*\b(?:bulk|coal|grain|ore|cargo)\b',
|
| 24 |
+
r'\bcargo.*(?:port|laycan)', r'(?:discharge|load).*laycan',
|
| 25 |
+
]
|
| 26 |
+
CARGO_TC_KEYWORDS = [
|
| 27 |
+
r'\btime\s*charter\b', r'\btct\b', r'\bdely\b', r'\bdelivery\b.*\bredelivery\b',
|
| 28 |
+
r'\bduration\s+abt\b', r'\bredel\b', r'\bredelivery\b', r'\bhire\b',
|
| 29 |
+
r'1\s*tct\s*with', r'\bdelivery\b.*\blaycan\b', r'\bperiod\b.*\bdelivery\b',
|
| 30 |
+
r'\b1[-–]\d+\s*years?\b', r'\bflat\s*or\s*index\b',
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
# ── Global pipeline instance ─────────────────────────────────────────────────
|
| 34 |
+
_pipeline: Pipeline | None = None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _build_and_train():
|
| 38 |
+
global _pipeline
|
| 39 |
+
X = TONNAGE_SAMPLES + CARGO_VC_SAMPLES + CARGO_TC_SAMPLES
|
| 40 |
+
y = (
|
| 41 |
+
["tonnage"] * len(TONNAGE_SAMPLES)
|
| 42 |
+
+ ["cargo_vc"] * len(CARGO_VC_SAMPLES)
|
| 43 |
+
+ ["cargo_tc"] * len(CARGO_TC_SAMPLES)
|
| 44 |
+
)
|
| 45 |
+
_pipeline = Pipeline([
|
| 46 |
+
("tfidf", TfidfVectorizer(
|
| 47 |
+
ngram_range=(1, 3),
|
| 48 |
+
max_features=8000,
|
| 49 |
+
sublinear_tf=True,
|
| 50 |
+
min_df=1,
|
| 51 |
+
)),
|
| 52 |
+
("clf", LogisticRegression(
|
| 53 |
+
max_iter=1000,
|
| 54 |
+
C=2.0,
|
| 55 |
+
solver="lbfgs",
|
| 56 |
+
multi_class="multinomial",
|
| 57 |
+
)),
|
| 58 |
+
])
|
| 59 |
+
_pipeline.fit(X, y)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _keyword_classify(text: str) -> str | None:
|
| 63 |
+
t = text.lower()
|
| 64 |
+
scores = {
|
| 65 |
+
"tonnage": sum(1 for p in TONNAGE_KEYWORDS if re.search(p, t)),
|
| 66 |
+
"cargo_vc": sum(1 for p in CARGO_VC_KEYWORDS if re.search(p, t)),
|
| 67 |
+
"cargo_tc": sum(1 for p in CARGO_TC_KEYWORDS if re.search(p, t)),
|
| 68 |
+
}
|
| 69 |
+
best = max(scores, key=scores.get)
|
| 70 |
+
return best if scores[best] > 0 else "unknown"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def classify(text: str) -> tuple[str, float]:
|
| 74 |
+
"""Return (category, confidence). Category is one of:
|
| 75 |
+
'tonnage' | 'cargo_vc' | 'cargo_tc' | 'unknown'
|
| 76 |
+
"""
|
| 77 |
+
global _pipeline
|
| 78 |
+
if _pipeline is None:
|
| 79 |
+
_build_and_train()
|
| 80 |
+
|
| 81 |
+
clean = text.upper()
|
| 82 |
+
proba = _pipeline.predict_proba([clean])[0]
|
| 83 |
+
classes = _pipeline.classes_
|
| 84 |
+
best_idx = proba.argmax()
|
| 85 |
+
confidence = float(proba[best_idx])
|
| 86 |
+
label = classes[best_idx]
|
| 87 |
+
|
| 88 |
+
if confidence < CONFIDENCE_THRESHOLD:
|
| 89 |
+
kw_label = _keyword_classify(text)
|
| 90 |
+
return kw_label, confidence
|
| 91 |
+
|
| 92 |
+
return label, confidence
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# Initialise on import so first request is fast
|
| 96 |
+
_build_and_train()
|
classification/training_data.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Training samples derived from real shipping email patterns.
|
| 2 |
+
# 30 per class → 90 total labelled examples for TF-IDF + LogReg.
|
| 3 |
+
|
| 4 |
+
TONNAGE_SAMPLES = [
|
| 5 |
+
"MV SHENG AN HAI DWT 56564 OPEN XIAMEN CHINA O/A 2ND JUNE 2026 BULK CARRIER CCS CLASS",
|
| 6 |
+
"MV FENG HUI HAI DWT 63260 OPEN GUANGZHOU CHINA O/A 6TH JUNE 2026 SDSTBC BUILT 2017",
|
| 7 |
+
"SARONIC CHAMPION 93K SCRUBBER FITTED 2011 OPEN VUNG ANG VIETNAM 08-12 JUNE BULK CARRIER",
|
| 8 |
+
"MV TRUE FRIEND DWT 51241 BUILT 2009 OPEN BEJAIA 1ST JUNE BULK CARRIER NK CLASS BARBADOS FLAG",
|
| 9 |
+
"MV BLUE STAR 38K DWT OPEN GABES TUNISIA 25 MAY GEARED SELF TRIMMING BULK CARRIER ABS",
|
| 10 |
+
"MV YIN HUA 1 DWT 46613 OPEN CHITTAGONG BANGLADESH O/A 5TH JUNE 2026 5HO 5HA CCS",
|
| 11 |
+
"MV BI JIA SHAN DWT 56625 OPEN GWADAR PAKISTAN O/A 2ND JUNE 2026 HONG KONG FLAG SDBC",
|
| 12 |
+
"MV YUANNING SEA DWT 55580 OPEN SOHAR OMAN O/A 30TH MAY 2026 PANAMA FLAG SDSTBC 4X30T CRANES",
|
| 13 |
+
"MV COS ORCHID DWT 55550 OPEN DAR ES SALAAM TANZANIA O/A 1ST JUNE 2026 SINGAPORE FLAG SDBC",
|
| 14 |
+
"MV DE SHENG HAI DWT 38821 OPEN MUCURIPE BRAZIL O/A 24-25 MAY 2026 BULK CARRIER",
|
| 15 |
+
"MV AN DING HAI DWT 38800 OPEN CASABLANCA O/A 28-30 MAY 2026 HONG KONG FLAG SDBC 5HO 5HA",
|
| 16 |
+
"VESSEL ATLANTIC BULKER 75000 DWT OPEN SANTOS BRAZIL 15 JUNE BUILT 2015 PANAMAX BULK CARRIER",
|
| 17 |
+
"OUR DIRECT OWNERS OPEN AS FOLLOWS MV PACIFIC GLORY 82000 DWT OPEN ROTTERDAM 20 JUNE",
|
| 18 |
+
"VESSEL AVAILABLE OCEAN PIONEER 58000 DWT ETA SINGAPORE 10 JUNE HANDYMAX BULK CARRIER",
|
| 19 |
+
"MV DELTA WIND DWT 32000 OPEN ISTANBUL TURKEY 5 JULY BUILT 2008 HANDYSIZE GEARED",
|
| 20 |
+
"MV ALPHA STAR 176000 DWT OPEN QINGDAO CHINA 1 JULY CAPESIZE BULK CARRIER LR CLASS",
|
| 21 |
+
"DWT 28000 MV EMERALD SEAS OPEN PARANAGUA BRAZIL O/A 18 JUNE HANDYSIZE 4 CRANES 30T",
|
| 22 |
+
"VESSEL POSITION MV CORAL BAY 50000 DWT OPEN PORT KLANG MALAYSIA 25 JUNE ETA HANDYMAX",
|
| 23 |
+
"MV STEEL WING 64000 DWT OPEN ANTWERP BELGIUM 8 JUNE ULTRAMAX BULK CARRIER NK CLASS",
|
| 24 |
+
"MV IRON HAWK 81000 DWT OPEN TUBARAO BRAZIL 22 JUNE PANAMAX BUILT 2012 BV CLASS",
|
| 25 |
+
"GEARED BULK CARRIER MV OCEAN TIDE 38000 DWT OPEN CHITTAGONG O/A 14 JUNE 4X30T CRANES",
|
| 26 |
+
"MV GRAND PEAK 57000 DWT OPEN COLOMBO SRI LANKA 18 JUNE SUPRAMAX BULK CARRIER SDBC",
|
| 27 |
+
"VESSEL OPEN MV CAPE GLORY 181000 DWT QINGDAO 01 JULY CAPESIZE NO GEAR BUILT 2010",
|
| 28 |
+
"MV RUBY STAR DWT 56000 OPEN HALDIA INDIA O/A 10 JUNE BUILT 2014 SUPRAMAX 5HO 5HA",
|
| 29 |
+
"MV GOLDEN VENTURE 33000 DWT OPEN CONSTANTA ROMANIA 17 JUNE HANDYSIZE BUILT 2006",
|
| 30 |
+
"MV CORAL SEA DWT 45000 OPEN PORT SUDAN O/A 12 JUNE HANDYMAX 4X30T CRANES SDBC",
|
| 31 |
+
"VESSEL ATLAS BULK 92000 DWT OPEN NEWCASTLE AUSTRALIA 5 JULY KAMSARMAX BUILT 2016 LR",
|
| 32 |
+
"MV SILVER PEAK 55000 DWT OPEN KRISHNAPATNAM INDIA O/A 3 JUNE SUPRAMAX CCS CLASS",
|
| 33 |
+
"MV HORIZON GLORY 63000 DWT OPEN PASIR GUDANG MALAYSIA O/A 7 JUNE ULTRAMAX BUILT 2019",
|
| 34 |
+
"OPEN VESSEL MV DELTA OCEAN 38000 DWT MORMUGAO INDIA 9 JUNE HANDYSIZE 4X30T",
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
CARGO_VC_SAMPLES = [
|
| 38 |
+
"PLEASE OFFER FIRM FOR FULL CARGO 15000 20000 MTS MOLASSES LOAD PORT KOH SI CHANG THAILAND DISCHARGE PORT KANDLA CHENNAI LAYCAN MID JULY 2026",
|
| 39 |
+
"CARGO 20000 MT HRC JEDDAH BILBAO FIOS 4000MT FHINC CQD DISCHARGE 25 JUNE 5 JULY 3.75 PCT",
|
| 40 |
+
"20000 30000 MTS IRON SLAG IN BULK LP BUSHEHR DP DOHA 10000 12000 LAYCAN 25-30 JULY 3.75 TTL",
|
| 41 |
+
"CARGO 30000 MTS UREA IN BULK POL BIK POD ISKENDERUN OR DURBAN 5000 5000 LAYCAN 16-20 JULY",
|
| 42 |
+
"VOYAGE CHARTER 45000 MT COAL LOADING PORT NEWCASTLE AUSTRALIA DISCHARGE PORT MUNDRA INDIA LAYCAN JULY 2026",
|
| 43 |
+
"CARGO REQUEST 25000 MT CLINKER POL COLOMBO SRI LANKA POD CHITTAGONG BANGLADESH LAYCAN EARLY JUNE",
|
| 44 |
+
"FIRM CARGO 10000 12000 TONS SALT LOAD PORT KANDLA INDIA DISCH PORT COLOMBO LAYCAN 1-10 JUNE",
|
| 45 |
+
"PLEASE FIND BELOW CARGO 50000 MT GRAIN POL ROSARIO ARGENTINA POD ANY PACIFIC PORT LAYCAN 15-25 JUNE",
|
| 46 |
+
"VOYAGE CHARTER CARGO 35000 MT FERTILIZER LOADING YUZHNE UKRAINE DISCHARGE PARANAGUA BRAZIL",
|
| 47 |
+
"CARGO 55000 MT COAL LP MUARA KUIN DISCHARGE PORT KRISHNAPATNAM LAYCAN 10-20 JULY 2026",
|
| 48 |
+
"DIRECT CHARTERERS CARGO 22000 MT STEEL COILS LOAD ANTWERP DISCHARGE HOUSTON LAYCAN JUNE 2026",
|
| 49 |
+
"CARGO 15000 MT SUGAR LOAD PORT SANTOS BRAZIL DISCHARGE PORT CASABLANCA MOROCCO LAYCAN 5-15 JUNE",
|
| 50 |
+
"CARGO AVAILABILITY 60000 MT IRON ORE LOAD TUBARAO BRAZIL DISCHARGE QINGDAO CHINA LAYCAN JULY",
|
| 51 |
+
"PLEASE OFFER 40000 MTS ROCK PHOSPHATE LOAD PORT JORF LASFAR DISCHARGE PORT CHENNAI LAYCAN MID JUNE",
|
| 52 |
+
"CARGO 18000 MT WHEAT LOADING PORT ODESSA UKRAINE DISCHARGE PORT ALEXANDRIA EGYPT LAYCAN JUNE 2026",
|
| 53 |
+
"VOYAGE CHARTER NEEDED 25000 MT PET COKE LOAD HOUSTON DISCHARGE MUNDRA LAYCAN EARLY JULY",
|
| 54 |
+
"CARGO INQUIRY 30000 MT BAUXITE LOAD PORT CONAKRY GUINEA DISCHARGE PORT TIANJIN CHINA LAYCAN JULY",
|
| 55 |
+
"CARGO REQUEST FIRM 12000 MTS RICE LOAD BANGKOK THAILAND DISCHARGE DAKAR SENEGAL LAYCAN JUNE",
|
| 56 |
+
"50000 MT SOYBEANS LOAD PORT PARANAGUA BRAZIL DISCHARGE BARCELONA SPAIN LAYCAN LATE JUNE",
|
| 57 |
+
"CARGO 75000 MT COAL LOADING PORT KHATOVKA RUSSIA DISCHARGE JAPAN PORTS LAYCAN AUGUST 2026",
|
| 58 |
+
"VOYAGE CHARTER 20000 MT SCRAP LOAD ROTTERDAM NETHERLANDS DISCHARGE ALIAGA TURKEY LAYCAN JULY",
|
| 59 |
+
"CARGO AVAILABILITY 40000 MT CORN LOAD ROSARIO ARGENTINA DISCHARGE ANY PORT SPAIN LAYCAN JUNE",
|
| 60 |
+
"CARGO REQUEST 8000 MT CEMENT CLINKER LP VISHAKHAPATNAM INDIA DP CHITTAGONG LAYCAN 20-30 JUNE",
|
| 61 |
+
"FIRM CARGO 35000 MT PHOSPHATE ROCK LOAD SAFI MOROCCO DISCHARGE HAMBURG GERMANY LAYCAN JUNE",
|
| 62 |
+
"25000 MTS STEAM COAL LOAD PORT BONTANG INDONESIA DISCH PORT KARACHI PAKISTAN LAYCAN JULY",
|
| 63 |
+
"CARGO 14000 MT SULFUR LP ADEN YEMEN DP NHAVA SHEVA INDIA LAYCAN EARLY JUNE",
|
| 64 |
+
"VOYAGE CHARTER 30000 MT LIMESTONE LOAD VIZAG INDIA DISCHARGE HALDIA INDIA LAYCAN MID JUNE",
|
| 65 |
+
"CARGO NEED 55000 MT COAL LOADING NEWLANDS AUSTRALIA DISCHARGE TUTICORIN INDIA LAYCAN JULY",
|
| 66 |
+
"CARGO 18000 MT MOP FERTILIZER LOAD VANCOUVER CANADA DISCHARGE COLOMBO SRI LANKA LAYCAN JUNE",
|
| 67 |
+
"PLEASE QUOTE 45000 MT IRON ORE PELLETS LOAD OMAN DISCHARGE QINGDAO CHINA LAYCAN AUGUST 2026",
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
CARGO_TC_SAMPLES = [
|
| 71 |
+
"CHINA NOPAC ACCOUNT DAI AN OCEAN SHIPPING DELIVERY TM VANCOUVER LC 10-17 JUNE SMX UMX 1 TCT WITH GRAINS REDELIVERY CHITTAGONG 3.75 ADDCOM",
|
| 72 |
+
"SEASIA DELIVERY MAKE SANGATTA EAST KALIMANTAN INDONESIA 29 2ND JUN 1 TCT WITH CLINKER TO BANGLADESH DURATION ABT 30 DAYS",
|
| 73 |
+
"1 TCT WITH STEELS GEN LAWFULS 22K DWT HMAX DELIVERY ECI LAYCAN 15-18 JULY REDEL MED VIA GOA DURATION ABT 35-40 DAYS WOG",
|
| 74 |
+
"WORLDWIDE ACCOUNT SEA SCHIFFE SUPRA ULTRA DELIVERY WW FULL MAY 1-3 YEARS TIME CHARTER INDEX WORKABLE 3.75 ADDCOM",
|
| 75 |
+
"1 TCT WITH STEELS 33K DWT DELIVERY ECI LAYCAN 21-23 JULY REDELIVERY ARAG VIA COGH DURATION ABT 50-55 DAYS 3.75 ADC",
|
| 76 |
+
"TIME CHARTER TRIP SUPRAMAX DELIVERY SINGAPORE REDELIVERY JAPAN 1 TCT COAL DURATION 30 DAYS HIRE USD 12000 PD",
|
| 77 |
+
"TCT ULTRAMAX DELY ROTTERDAM REDEL WEST AFRICA 1 TCT GRAIN DURATION ABT 45 DAYS LAYCAN JUNE 2026",
|
| 78 |
+
"ACCOUNT PACIFIC LOGISTICS TIME CHARTER TRIP PANAMAX DELIVERY SANTOS BRAZIL REDELIVERY ANTWERP DURATION 35 DAYS",
|
| 79 |
+
"1 TCT WITH FERTILIZER SMX DELY AQABA JORDAN REDEL INDIA SUBCONTINENT LAYCAN MID JUNE DURATION 25 DAYS",
|
| 80 |
+
"TIME CHARTER CAPESIZE DELIVERY QINGDAO CHINA REDELIVERY BRAZIL 1 TCT IRON ORE DURATION 60 DAYS",
|
| 81 |
+
"TCT HANDY DELY CHITTAGONG REDEL SINGAPORE INDONESIA RANGE DURATION 15-20 DAYS CARGO CLINKER LAYCAN JUNE",
|
| 82 |
+
"1 TCT PANAMAX DELIVERY RECALADA ARGENTINA REDELIVERY SPAIN PORTUG RANGE GRAIN 35-40 DAYS",
|
| 83 |
+
"TCT REQUIRED ULTRAMAX DELIVERY PORT KLANG MALAYSIA REDELIVERY JAPAN KOREA RANGE COAL 30 DAYS LAYCAN JULY",
|
| 84 |
+
"ACCOUNT GLOBAL SHIPPING 1 TCT SUPRAMAX DELY DURBAN REDEL CHINA FAR EAST DURATION 40-45 DAYS COAL",
|
| 85 |
+
"TIME CHARTER TRIP HANDYSIZE DELIVERY ISTANBUL REDELIVERY WEST AFRICA DURATION 20-25 DAYS STEEL",
|
| 86 |
+
"1 TCT WITH LOGS HANDYMAX DELIVERY MOMBASA KENYA REDELIVERY CHINA DURATION 45 DAYS LAYCAN JUNE",
|
| 87 |
+
"TCT PANAMAX ACCOUNT OCEANWIDE CHARTERING DELY TUBARAO BRAZIL REDEL QINGDAO CHINA IRON ORE 55 DAYS",
|
| 88 |
+
"MINI TCT HANDYSIZE 28000 DWT DELIVERY ROTTERDAM REDELIVERY WEST AFRICA DURATION 18 DAYS CARGO SCRAPS",
|
| 89 |
+
"1 TCT SUPRAMAX DELIVERY SINGAPORE REDELIVERY INDONESIA RANGE 15-20 DAYS CLINKER LAYCAN EARLY JUNE",
|
| 90 |
+
"TIME CHARTER TRIP ULTRAMAX DELY MANILA PHILIPPINES REDEL SOUTH KOREA DURATION 20 DAYS COAL",
|
| 91 |
+
"TCT REQUIRED PANAMAX DELIVERY VENTSPILS LATVIA REDELIVERY AMSTERDAM RANGE LAYCAN MID JUNE GRAIN",
|
| 92 |
+
"1 TCT WITH FERTILIZER SUPRAMAX DELY AQABA LAYCAN JULY REDEL INDIA DURATION 20-25 DAYS 3.75 ADDCOM",
|
| 93 |
+
"WORLDWIDE TIME CHARTER 1-2 YEARS HANDYMAX DELIVERY ANYWHERE WORLDWIDE REDELIVERY WORLDWIDE FLAT HIRE",
|
| 94 |
+
"TCT CAPESIZE 160K DWT DELIVERY DAMPIER AUSTRALIA REDELIVERY SOUTH KOREA IRON ORE 15-20 DAYS",
|
| 95 |
+
"1 TCT HANDY DELY YANBU SAUDI ARABIA REDEL NHAVA SHEVA INDIA DURATION 12 DAYS CARGO CLINKER LAYCAN JUNE",
|
| 96 |
+
"TIME CHARTER TRIP ULTRAMAX DELIVERY SOHAR OMAN REDELIVERY VIZAG INDIA DURATION 10 DAYS COAL",
|
| 97 |
+
"TCT SUPRAMAX ACCOUNT MARITIME VENTURES DELY PORT SAID EGYPT REDEL BLACK SEA DURATION 15 DAYS",
|
| 98 |
+
"1 TCT PANAMAX WITH COAL DELIVERY NEWCASTLE AUSTRALIA REDELIVERY EAST COAST INDIA DURATION 20 DAYS",
|
| 99 |
+
"TIME CHARTER TRIP HANDYSIZE DELY AGADIR MOROCCO REDEL NORTH EUROPE RANGE DURATION 20-25 DAYS",
|
| 100 |
+
"TCT REQUIRED GEARED ULTRAMAX DELIVERY PASIR GUDANG MALAYSIA REDELIVERY PHILIPPINES DURATION 15 DAYS CEMENT",
|
| 101 |
+
]
|
config.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 4 |
+
DATA_DIR = os.path.join(BASE_DIR, 'data')
|
| 5 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 6 |
+
|
| 7 |
+
DATABASE_URL = os.environ.get(
|
| 8 |
+
'DATABASE_URL',
|
| 9 |
+
f'sqlite:///{os.path.join(DATA_DIR, "emails.db")}'
|
| 10 |
+
)
|
data/.gitkeep
ADDED
|
File without changes
|
database/__init__.py
ADDED
|
File without changes
|
database/db.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import create_engine
|
| 2 |
+
from sqlalchemy.orm import sessionmaker, DeclarativeBase
|
| 3 |
+
import sys, os
|
| 4 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 5 |
+
from config import DATABASE_URL
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Base(DeclarativeBase):
|
| 9 |
+
pass
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
_connect_args = {"check_same_thread": False} if "sqlite" in DATABASE_URL else {}
|
| 13 |
+
engine = create_engine(DATABASE_URL, connect_args=_connect_args, echo=False)
|
| 14 |
+
Session = sessionmaker(bind=engine)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def init_db():
|
| 18 |
+
"""Create all tables if they don't exist yet."""
|
| 19 |
+
from database.models import Email, Tonnage, CargoVC, CargoTC # noqa: F401
|
| 20 |
+
Base.metadata.create_all(engine)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def get_session():
|
| 24 |
+
return Session()
|
database/models.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import Column, Integer, String, Float, Boolean, DateTime, Text, ForeignKey, Index
|
| 2 |
+
from sqlalchemy.orm import relationship
|
| 3 |
+
from datetime import datetime, timezone
|
| 4 |
+
from database.db import Base
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _utcnow():
|
| 8 |
+
return datetime.now(timezone.utc)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Email(Base):
|
| 12 |
+
__tablename__ = "emails"
|
| 13 |
+
|
| 14 |
+
id = Column(Integer, primary_key=True)
|
| 15 |
+
subject = Column(String(500))
|
| 16 |
+
sender = Column(String(200))
|
| 17 |
+
received_at = Column(DateTime)
|
| 18 |
+
raw_body = Column(Text)
|
| 19 |
+
category = Column(String(50)) # tonnage | cargo_vc | cargo_tc | unknown
|
| 20 |
+
confidence = Column(Float, default=0.0)
|
| 21 |
+
is_duplicate = Column(Boolean, default=False)
|
| 22 |
+
fingerprint = Column(String(64), nullable=True, index=True) # SHA-256 of normalised body
|
| 23 |
+
created_at = Column(DateTime, default=_utcnow)
|
| 24 |
+
|
| 25 |
+
tonnage = relationship("Tonnage", back_populates="email", cascade="all, delete-orphan")
|
| 26 |
+
cargo_vc = relationship("CargoVC", back_populates="email", cascade="all, delete-orphan")
|
| 27 |
+
cargo_tc = relationship("CargoTC", back_populates="email", cascade="all, delete-orphan")
|
| 28 |
+
|
| 29 |
+
def to_dict(self, include_extracted=False):
|
| 30 |
+
d = {
|
| 31 |
+
"id": self.id,
|
| 32 |
+
"subject": self.subject,
|
| 33 |
+
"sender": self.sender,
|
| 34 |
+
"received_at": self.received_at.isoformat() if self.received_at else None,
|
| 35 |
+
"raw_body": self.raw_body,
|
| 36 |
+
"category": self.category,
|
| 37 |
+
"confidence": round(self.confidence or 0, 3),
|
| 38 |
+
"is_duplicate": self.is_duplicate,
|
| 39 |
+
"fingerprint": self.fingerprint,
|
| 40 |
+
"created_at": self.created_at.isoformat() if self.created_at else None,
|
| 41 |
+
}
|
| 42 |
+
if include_extracted:
|
| 43 |
+
d["tonnage"] = [t.to_dict() for t in self.tonnage]
|
| 44 |
+
d["cargo_vc"] = [c.to_dict() for c in self.cargo_vc]
|
| 45 |
+
d["cargo_tc"] = [c.to_dict() for c in self.cargo_tc]
|
| 46 |
+
return d
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Tonnage(Base):
|
| 50 |
+
__tablename__ = "tonnage"
|
| 51 |
+
|
| 52 |
+
id = Column(Integer, primary_key=True)
|
| 53 |
+
email_id = Column(Integer, ForeignKey("emails.id"))
|
| 54 |
+
vessel_name = Column(String(200))
|
| 55 |
+
account_name = Column(String(200))
|
| 56 |
+
open_port = Column(String(200))
|
| 57 |
+
open_date = Column(String(100))
|
| 58 |
+
vessel_type = Column(String(100))
|
| 59 |
+
vessel_size = Column(String(100))
|
| 60 |
+
flag = Column(String(100))
|
| 61 |
+
built_year = Column(String(20))
|
| 62 |
+
class_society = Column(String(100))
|
| 63 |
+
loa = Column(String(50))
|
| 64 |
+
beam = Column(String(50))
|
| 65 |
+
|
| 66 |
+
email = relationship("Email", back_populates="tonnage")
|
| 67 |
+
|
| 68 |
+
def to_dict(self):
|
| 69 |
+
return {
|
| 70 |
+
"id": self.id,
|
| 71 |
+
"email_id": self.email_id,
|
| 72 |
+
"vessel_name": self.vessel_name,
|
| 73 |
+
"account_name": self.account_name,
|
| 74 |
+
"open_port": self.open_port,
|
| 75 |
+
"open_date": self.open_date,
|
| 76 |
+
"vessel_type": self.vessel_type,
|
| 77 |
+
"vessel_size": self.vessel_size,
|
| 78 |
+
"flag": self.flag,
|
| 79 |
+
"built_year": self.built_year,
|
| 80 |
+
"class_society": self.class_society,
|
| 81 |
+
"loa": self.loa,
|
| 82 |
+
"beam": self.beam,
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class CargoVC(Base):
|
| 87 |
+
__tablename__ = "cargo_vc"
|
| 88 |
+
|
| 89 |
+
id = Column(Integer, primary_key=True)
|
| 90 |
+
email_id = Column(Integer, ForeignKey("emails.id"))
|
| 91 |
+
account_name = Column(String(200))
|
| 92 |
+
cargo_name = Column(String(200))
|
| 93 |
+
loading_port = Column(String(200))
|
| 94 |
+
discharge_port = Column(String(200))
|
| 95 |
+
laycan = Column(String(100))
|
| 96 |
+
cargo_type = Column(String(100))
|
| 97 |
+
quantity = Column(String(100))
|
| 98 |
+
|
| 99 |
+
email = relationship("Email", back_populates="cargo_vc")
|
| 100 |
+
|
| 101 |
+
def to_dict(self):
|
| 102 |
+
return {
|
| 103 |
+
"id": self.id,
|
| 104 |
+
"email_id": self.email_id,
|
| 105 |
+
"account_name": self.account_name,
|
| 106 |
+
"cargo_name": self.cargo_name,
|
| 107 |
+
"loading_port": self.loading_port,
|
| 108 |
+
"discharge_port": self.discharge_port,
|
| 109 |
+
"laycan": self.laycan,
|
| 110 |
+
"cargo_type": self.cargo_type,
|
| 111 |
+
"quantity": self.quantity,
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class CargoTC(Base):
|
| 116 |
+
__tablename__ = "cargo_tc"
|
| 117 |
+
|
| 118 |
+
id = Column(Integer, primary_key=True)
|
| 119 |
+
email_id = Column(Integer, ForeignKey("emails.id"))
|
| 120 |
+
account_name = Column(String(200))
|
| 121 |
+
cargo_name = Column(String(200))
|
| 122 |
+
delivery_port = Column(String(200))
|
| 123 |
+
redelivery_port = Column(String(200))
|
| 124 |
+
duration = Column(String(100))
|
| 125 |
+
laycan = Column(String(100))
|
| 126 |
+
cargo_type = Column(String(100))
|
| 127 |
+
|
| 128 |
+
email = relationship("Email", back_populates="cargo_tc")
|
| 129 |
+
|
| 130 |
+
def to_dict(self):
|
| 131 |
+
return {
|
| 132 |
+
"id": self.id,
|
| 133 |
+
"email_id": self.email_id,
|
| 134 |
+
"account_name": self.account_name,
|
| 135 |
+
"cargo_name": self.cargo_name,
|
| 136 |
+
"delivery_port": self.delivery_port,
|
| 137 |
+
"redelivery_port": self.redelivery_port,
|
| 138 |
+
"duration": self.duration,
|
| 139 |
+
"laycan": self.laycan,
|
| 140 |
+
"cargo_type": self.cargo_type,
|
| 141 |
+
}
|
extraction/__init__.py
ADDED
|
File without changes
|
extraction/cargo_tc_extractor.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def _clean(s: str) -> str:
|
| 6 |
+
return re.sub(r'\s+', ' ', s).strip().rstrip(',').rstrip('.').strip()
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _extract_account(text: str) -> str | None:
|
| 10 |
+
m = re.search(
|
| 11 |
+
r'(?:ACCOUNT|ACC(?:OUNT)?|A/C)\s*:?\s*([\w\s&.,]+?)(?:\n|$)',
|
| 12 |
+
text, re.IGNORECASE
|
| 13 |
+
)
|
| 14 |
+
if m:
|
| 15 |
+
val = _clean(m.group(1))
|
| 16 |
+
if 3 < len(val) < 80:
|
| 17 |
+
return val
|
| 18 |
+
return None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _extract_delivery_port(text: str) -> str | None:
|
| 22 |
+
patterns = [
|
| 23 |
+
r'(?:DELIVERY|DELY)\s+(?:TO\s+MAKE\s+|TM\s+)?([A-Z][A-Z\s(),/.-]{2,60}?)(?:\n|LC|LAYCAN|REDELIVERY|REDEL|DURATION|$)',
|
| 24 |
+
r'DELIVERY\s*:\s*([^\n]{3,60})',
|
| 25 |
+
]
|
| 26 |
+
for p in patterns:
|
| 27 |
+
m = re.search(p, text, re.IGNORECASE)
|
| 28 |
+
if m:
|
| 29 |
+
val = _clean(m.group(1))
|
| 30 |
+
# Strip trailing noise
|
| 31 |
+
val = re.sub(r'\s+(?:LC|LAYCAN|REDEL|DURATION|$).*', '', val, flags=re.IGNORECASE).strip()
|
| 32 |
+
if 2 < len(val) < 80:
|
| 33 |
+
return val
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _extract_redelivery_port(text: str) -> str | None:
|
| 38 |
+
patterns = [
|
| 39 |
+
r'(?:REDELIVERY|REDEL)\s*:?\s*([A-Z][A-Z\s(),/.-]{2,60}?)(?:\n|DURATION|3\.?\d+\s*%|$)',
|
| 40 |
+
r'REDELIVERY\s*:\s*([^\n]{3,60})',
|
| 41 |
+
]
|
| 42 |
+
for p in patterns:
|
| 43 |
+
m = re.search(p, text, re.IGNORECASE)
|
| 44 |
+
if m:
|
| 45 |
+
val = _clean(m.group(1))
|
| 46 |
+
if 2 < len(val) < 80:
|
| 47 |
+
return val
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _extract_duration(text: str) -> str | None:
|
| 52 |
+
patterns = [
|
| 53 |
+
r'DURATION\s+(?:ABT\s+)?([\d\s\-–]+(?:DAYS?|MONTHS?|YEARS?)\s*(?:WOG)?)',
|
| 54 |
+
r'(?:ABT\s+)?([\d]+\s*[-–]\s*[\d]+\s*(?:DAYS?|MONTHS?))\s*(?:WOG)?',
|
| 55 |
+
r'(1[-–]\d+\s*YEARS?)',
|
| 56 |
+
r'(\d+\s*(?:DAYS?|MONTHS?|YEARS?))',
|
| 57 |
+
]
|
| 58 |
+
for p in patterns:
|
| 59 |
+
m = re.search(p, text, re.IGNORECASE)
|
| 60 |
+
if m:
|
| 61 |
+
val = _clean(m.group(1))
|
| 62 |
+
if len(val) > 1:
|
| 63 |
+
return val
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _extract_laycan(text: str) -> str | None:
|
| 68 |
+
patterns = [
|
| 69 |
+
r'(?:LAYCAN|LC)\s*:?\s*([^\n]{3,40})',
|
| 70 |
+
r'(\d{1,2}\s*[-–]\s*\d{1,2}\s+(?:JAN|FEB|MAR|APR|MAY|JUN|JUNE|JUL|JULY|AUG|SEP|OCT|NOV|DEC)\w*(?:\s+\d{4})?)',
|
| 71 |
+
r'((?:MID|EARLY|LATE|FULL|END)\s+(?:JAN|FEB|MAR|APR|MAY|JUN|JUNE|JUL|JULY|AUG|SEP|OCT|NOV|DEC)\w*(?:\s+\d{4})?)',
|
| 72 |
+
r'(?:^|\n)(\d{1,2}\s*[-–]?\s*\d{1,2}(?:ST|ND|RD|TH)?\s+(?:JUN|JUNE|JUL|JULY|AUG|MAY)\w*(?:\s+\d{4})?)',
|
| 73 |
+
]
|
| 74 |
+
for p in patterns:
|
| 75 |
+
m = re.search(p, text, re.IGNORECASE | re.MULTILINE)
|
| 76 |
+
if m:
|
| 77 |
+
val = _clean(m.group(1))
|
| 78 |
+
if 2 < len(val) < 60:
|
| 79 |
+
return val
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _extract_cargo_name(text: str) -> str | None:
|
| 84 |
+
# "1 TCT WITH GRAINS", "1 TCT WITH CLINKER TO BDESH"
|
| 85 |
+
m = re.search(r'1\s*TCT\s+WITH\s+([A-Z][A-Z\s/]{2,30}?)(?:\n|TO\s|$)', text, re.IGNORECASE)
|
| 86 |
+
if m:
|
| 87 |
+
return _clean(m.group(1))
|
| 88 |
+
# "CARGO: COAL"
|
| 89 |
+
m = re.search(r'CARGO\s*:?\s*([A-Z][A-Z\s]{2,30}?)(?:\n|$)', text, re.IGNORECASE)
|
| 90 |
+
if m:
|
| 91 |
+
return _clean(m.group(1))
|
| 92 |
+
# Detect known commodities
|
| 93 |
+
commodities = [
|
| 94 |
+
'GRAIN', 'GRAINS', 'COAL', 'CLINKER', 'IRON ORE', 'FERTILIZER',
|
| 95 |
+
'STEEL', 'STEELS', 'GENERAL CARGO', 'LAWFULS', 'GENS', 'LOGS',
|
| 96 |
+
'BAUXITE', 'CEMENT', 'PHOSPHATE', 'SCRAPS', 'SOYBEANS',
|
| 97 |
+
]
|
| 98 |
+
text_up = text.upper()
|
| 99 |
+
for c in commodities:
|
| 100 |
+
if c in text_up:
|
| 101 |
+
return c
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _extract_cargo_type(text: str) -> str:
|
| 106 |
+
text_up = text.upper()
|
| 107 |
+
if any(x in text_up for x in ['STEEL', 'GENS', 'GENERAL CARGO', 'LAWFUL']):
|
| 108 |
+
return 'BREAKBULK/GENERAL'
|
| 109 |
+
if any(x in text_up for x in ['GRAIN', 'COAL', 'CLINKER', 'BAUXITE', 'IRON ORE']):
|
| 110 |
+
return 'BULK'
|
| 111 |
+
return 'BULK'
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ── Multi-cargo splitter ──────────────────────────────────────────────────────
|
| 115 |
+
|
| 116 |
+
def extract_cargo_tc(text: str, email_id: int) -> list[dict]:
|
| 117 |
+
"""Return list of TC cargo dicts extracted from email text."""
|
| 118 |
+
results = []
|
| 119 |
+
|
| 120 |
+
# Split on separators like ---...--- or +++...+++
|
| 121 |
+
chunks = re.split(r'[-]{15,}|[+]{10,}', text)
|
| 122 |
+
|
| 123 |
+
for chunk in chunks:
|
| 124 |
+
chunk = chunk.strip()
|
| 125 |
+
if not chunk:
|
| 126 |
+
continue
|
| 127 |
+
chunk_up = chunk.upper()
|
| 128 |
+
|
| 129 |
+
tc_signals = ['TCT', 'DELIVERY', 'DELY', 'REDELIVERY', 'REDEL', 'DURATION', 'TIME CHARTER']
|
| 130 |
+
if not any(s in chunk_up for s in tc_signals):
|
| 131 |
+
continue
|
| 132 |
+
|
| 133 |
+
delivery = _extract_delivery_port(chunk)
|
| 134 |
+
redelivery = _extract_redelivery_port(chunk)
|
| 135 |
+
duration = _extract_duration(chunk)
|
| 136 |
+
laycan = _extract_laycan(chunk)
|
| 137 |
+
cargo_name = _extract_cargo_name(chunk)
|
| 138 |
+
|
| 139 |
+
if delivery or redelivery or duration:
|
| 140 |
+
results.append({
|
| 141 |
+
'email_id': email_id,
|
| 142 |
+
'account_name': _extract_account(chunk) or _extract_account(text),
|
| 143 |
+
'cargo_name': cargo_name,
|
| 144 |
+
'delivery_port': delivery,
|
| 145 |
+
'redelivery_port': redelivery,
|
| 146 |
+
'duration': duration,
|
| 147 |
+
'laycan': laycan,
|
| 148 |
+
'cargo_type': _extract_cargo_type(chunk),
|
| 149 |
+
})
|
| 150 |
+
|
| 151 |
+
# Deduplicate
|
| 152 |
+
seen = set()
|
| 153 |
+
unique = []
|
| 154 |
+
for r in results:
|
| 155 |
+
key = (r.get('delivery_port', ''), r.get('redelivery_port', ''), r.get('duration', ''))
|
| 156 |
+
if key not in seen:
|
| 157 |
+
seen.add(key)
|
| 158 |
+
unique.append(r)
|
| 159 |
+
|
| 160 |
+
return unique if unique else []
|
extraction/cargo_vc_extractor.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def _clean(s: str) -> str:
|
| 6 |
+
return re.sub(r'\s+', ' ', s).strip().rstrip(',').rstrip('.').strip()
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _extract_account(text: str) -> str | None:
|
| 10 |
+
m = re.search(r'(?:ACCOUNT|ACC(?:OUNT)?|A/C)\s*:?\s*([\w\s&.,]+?)(?:\n|$)', text, re.IGNORECASE)
|
| 11 |
+
if m:
|
| 12 |
+
val = _clean(m.group(1))
|
| 13 |
+
if 3 < len(val) < 80:
|
| 14 |
+
return val
|
| 15 |
+
m = re.search(r'@([\w-]+)\.', text)
|
| 16 |
+
if m:
|
| 17 |
+
return m.group(1).capitalize()
|
| 18 |
+
return None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _extract_quantity(text: str) -> str | None:
|
| 22 |
+
# Matches: "15,000 - 20,000 MTS", "30000 MT", "55,000 MTS"
|
| 23 |
+
m = re.search(
|
| 24 |
+
r'([\d,]+\s*[-–]\s*[\d,]+\s*(?:MTS?|TONS?|MT)|[\d,]+\s*(?:MTS?|TONS?|MT))',
|
| 25 |
+
text, re.IGNORECASE
|
| 26 |
+
)
|
| 27 |
+
if m:
|
| 28 |
+
return _clean(m.group(1))
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _extract_cargo_name(text: str) -> str | None:
|
| 33 |
+
# After quantity: "15,000 MTS MOLASSES", "30000 MT COAL"
|
| 34 |
+
m = re.search(
|
| 35 |
+
r'[\d,]+\s*(?:[-–]\s*[\d,]+\s*)?(?:\d+PCT\s*\w+\s*)?(?:MTS?|TONS?|MT)\s+'
|
| 36 |
+
r'(?:OF\s+)?(?:\d+PCT\s*\w+\s*)?([A-Z][A-Z\s/]{2,40}?)(?:\s*\n|\s*(?:LOAD|LP|POL|IN\s+BULK|FIOS|$))',
|
| 37 |
+
text, re.IGNORECASE
|
| 38 |
+
)
|
| 39 |
+
if m:
|
| 40 |
+
val = _clean(m.group(1))
|
| 41 |
+
if len(val) > 2:
|
| 42 |
+
return val
|
| 43 |
+
|
| 44 |
+
# Alternative: "CARGO: IRON ORE" or "CARGO OF COAL"
|
| 45 |
+
m = re.search(r'CARGO\s*(?:OF\s*)?:?\s*([A-Z][A-Z\s]{2,30}?)(?:\n|LP|POL|LOAD|$)', text, re.IGNORECASE)
|
| 46 |
+
if m:
|
| 47 |
+
return _clean(m.group(1))
|
| 48 |
+
|
| 49 |
+
# Slash format: port / port pattern — commodity may be in subject
|
| 50 |
+
# Try common commodities
|
| 51 |
+
commodities = [
|
| 52 |
+
'COAL', 'GRAIN', 'IRON ORE', 'FERTILIZER', 'UREA', 'WHEAT', 'CORN',
|
| 53 |
+
'SUGAR', 'RICE', 'CLINKER', 'CEMENT', 'BAUXITE', 'PHOSPHATE',
|
| 54 |
+
'MOLASSES', 'SALT', 'SCRAP', 'STEEL', 'HRC', 'PET COKE', 'GYPSUM',
|
| 55 |
+
'SOYBEANS', 'SOYBEAN MEAL', 'IRON SLAG', 'ROCK PHOSPHATE', 'LIMESTONE',
|
| 56 |
+
'MOLOCHOPT', 'SULFUR', 'MOP'
|
| 57 |
+
]
|
| 58 |
+
text_up = text.upper()
|
| 59 |
+
for c in commodities:
|
| 60 |
+
if c in text_up:
|
| 61 |
+
return c
|
| 62 |
+
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _extract_loading_port(text: str) -> str | None:
|
| 67 |
+
patterns = [
|
| 68 |
+
r'(?:LOAD(?:ING)?\s*PORT|LP|POL)\s*:?\s*([A-Z][A-Z\s,/+&.()-]{2,60}?)(?:\n|DISCHARGE|DISCH|DP|POD|$)',
|
| 69 |
+
r'(?:LOAD\s*PORT\s*:\s*)([^\n]+)',
|
| 70 |
+
]
|
| 71 |
+
for p in patterns:
|
| 72 |
+
m = re.search(p, text, re.IGNORECASE)
|
| 73 |
+
if m:
|
| 74 |
+
val = _clean(m.group(1))
|
| 75 |
+
if 2 < len(val) < 80:
|
| 76 |
+
return val
|
| 77 |
+
|
| 78 |
+
# Slash format: "JEDDAH / BILBAO" → first is load
|
| 79 |
+
m = re.search(r'^([A-Z][A-Z\s,]{2,30}?)\s*/\s*([A-Z][A-Z\s,]{2,30})', text, re.IGNORECASE | re.MULTILINE)
|
| 80 |
+
if m:
|
| 81 |
+
return _clean(m.group(1))
|
| 82 |
+
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _extract_discharge_port(text: str) -> str | None:
|
| 87 |
+
patterns = [
|
| 88 |
+
r'(?:DISCH(?:ARGE)?\s*PORT|DP|POD)\s*:?\s*([A-Z][A-Z\s,/+&.()-]{2,80}?)(?:\n|LAYCAN|LOAD|LP|COMM|$)',
|
| 89 |
+
r'(?:DISCHARGE\s*PORT\s*:\s*)([^\n]+)',
|
| 90 |
+
]
|
| 91 |
+
for p in patterns:
|
| 92 |
+
m = re.search(p, text, re.IGNORECASE)
|
| 93 |
+
if m:
|
| 94 |
+
val = _clean(m.group(1))
|
| 95 |
+
if 2 < len(val) < 80:
|
| 96 |
+
return val
|
| 97 |
+
|
| 98 |
+
# Slash format: "JEDDAH / BILBAO" → second is discharge
|
| 99 |
+
m = re.search(r'^([A-Z][A-Z\s,]{2,30}?)\s*/\s*([A-Z][A-Z\s,]{2,30})', text, re.IGNORECASE | re.MULTILINE)
|
| 100 |
+
if m:
|
| 101 |
+
return _clean(m.group(2))
|
| 102 |
+
|
| 103 |
+
return None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _extract_laycan(text: str) -> str | None:
|
| 107 |
+
patterns = [
|
| 108 |
+
r'LAYCAN\s*:?\s*([^\n]{3,40})',
|
| 109 |
+
r'(?:LC|L/C)\s*:?\s*([^\n]{3,30})',
|
| 110 |
+
# Date range like "25 June - 5 July" or "25-30 july"
|
| 111 |
+
r'(\d{1,2}\s*[-–]\s*\d{1,2}\s+(?:JAN|FEB|MAR|APR|MAY|JUN|JUNE|JUL|JULY|AUG|SEP|OCT|NOV|DEC)\w*(?:\s+\d{4})?)',
|
| 112 |
+
r'(\d{1,2}\s+(?:JAN|FEB|MAR|APR|MAY|JUN|JUNE|JUL|JULY|AUG|SEP|OCT|NOV|DEC)\w*\s*[-–]\s*\d{1,2}\s+\w+(?:\s+\d{4})?)',
|
| 113 |
+
r'((?:MID|EARLY|LATE|END)\s+(?:JAN|FEB|MAR|APR|MAY|JUN|JUNE|JUL|JULY|AUG|SEP|OCT|NOV|DEC)\w*(?:\s+\d{4})?)',
|
| 114 |
+
]
|
| 115 |
+
for p in patterns:
|
| 116 |
+
m = re.search(p, text, re.IGNORECASE)
|
| 117 |
+
if m:
|
| 118 |
+
val = _clean(m.group(1))
|
| 119 |
+
if 2 < len(val) < 60:
|
| 120 |
+
return val
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _extract_cargo_type(text: str) -> str:
|
| 125 |
+
text_up = text.upper()
|
| 126 |
+
if 'IN BULK' in text_up:
|
| 127 |
+
return 'BULK'
|
| 128 |
+
if 'BAGGED' in text_up:
|
| 129 |
+
return 'BAGGED'
|
| 130 |
+
if 'CONTAINER' in text_up:
|
| 131 |
+
return 'CONTAINERISED'
|
| 132 |
+
return 'BULK'
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# ── Multi-cargo splitter (for emails with several VC cargos separated by +++ or ---) ──
|
| 136 |
+
|
| 137 |
+
def extract_cargo_vc(text: str, email_id: int) -> list[dict]:
|
| 138 |
+
"""Return list of VC cargo dicts extracted from email text."""
|
| 139 |
+
results = []
|
| 140 |
+
|
| 141 |
+
# Split on separators like +++...+++ or ---...---
|
| 142 |
+
chunks = re.split(r'[+]{10,}|[-]{20,}', text)
|
| 143 |
+
for chunk in chunks:
|
| 144 |
+
chunk = chunk.strip()
|
| 145 |
+
if not chunk:
|
| 146 |
+
continue
|
| 147 |
+
# Only process chunks that look like VC cargo
|
| 148 |
+
chunk_up = chunk.upper()
|
| 149 |
+
vc_signals = ['LOAD PORT', 'LP:', 'POL', 'DISCHARGE PORT', 'DP:', 'POD', 'LAYCAN', 'MTS', 'MT ']
|
| 150 |
+
if not any(s in chunk_up for s in vc_signals):
|
| 151 |
+
continue
|
| 152 |
+
|
| 153 |
+
qty = _extract_quantity(chunk)
|
| 154 |
+
cargo_name = _extract_cargo_name(chunk)
|
| 155 |
+
loading_port = _extract_loading_port(chunk)
|
| 156 |
+
discharge_port = _extract_discharge_port(chunk)
|
| 157 |
+
laycan = _extract_laycan(chunk)
|
| 158 |
+
|
| 159 |
+
if loading_port or discharge_port or laycan:
|
| 160 |
+
results.append({
|
| 161 |
+
'email_id': email_id,
|
| 162 |
+
'account_name': _extract_account(chunk) or _extract_account(text),
|
| 163 |
+
'cargo_name': cargo_name,
|
| 164 |
+
'loading_port': loading_port,
|
| 165 |
+
'discharge_port': discharge_port,
|
| 166 |
+
'laycan': laycan,
|
| 167 |
+
'cargo_type': _extract_cargo_type(chunk),
|
| 168 |
+
'quantity': qty,
|
| 169 |
+
})
|
| 170 |
+
|
| 171 |
+
# Deduplicate (same load+discharge)
|
| 172 |
+
seen = set()
|
| 173 |
+
unique = []
|
| 174 |
+
for r in results:
|
| 175 |
+
key = (r.get('loading_port', ''), r.get('discharge_port', ''))
|
| 176 |
+
if key not in seen:
|
| 177 |
+
seen.add(key)
|
| 178 |
+
unique.append(r)
|
| 179 |
+
|
| 180 |
+
return unique if unique else []
|
extraction/extractor.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dispatcher: routes to the correct extractor and saves records."""
|
| 2 |
+
from extraction.tonnage_extractor import extract_tonnage
|
| 3 |
+
from extraction.cargo_vc_extractor import extract_cargo_vc
|
| 4 |
+
from extraction.cargo_tc_extractor import extract_cargo_tc
|
| 5 |
+
from database.models import Tonnage, CargoVC, CargoTC
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def extract(category: str, text: str, email_id: int, session) -> list[dict]:
|
| 9 |
+
"""Extract structured data, persist to DB, return list of extracted dicts."""
|
| 10 |
+
records = []
|
| 11 |
+
|
| 12 |
+
if category == 'tonnage':
|
| 13 |
+
vessels = extract_tonnage(text, email_id)
|
| 14 |
+
for v in vessels:
|
| 15 |
+
obj = Tonnage(**v)
|
| 16 |
+
session.add(obj)
|
| 17 |
+
records.append(v)
|
| 18 |
+
|
| 19 |
+
elif category == 'cargo_vc':
|
| 20 |
+
cargos = extract_cargo_vc(text, email_id)
|
| 21 |
+
for c in cargos:
|
| 22 |
+
obj = CargoVC(**c)
|
| 23 |
+
session.add(obj)
|
| 24 |
+
records.append(c)
|
| 25 |
+
|
| 26 |
+
elif category == 'cargo_tc':
|
| 27 |
+
cargos = extract_cargo_tc(text, email_id)
|
| 28 |
+
for c in cargos:
|
| 29 |
+
obj = CargoTC(**c)
|
| 30 |
+
session.add(obj)
|
| 31 |
+
records.append(c)
|
| 32 |
+
|
| 33 |
+
return records
|
extraction/tonnage_extractor.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import re
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# ── Helper extractors ─────────────────────────────────────────────────────────
|
| 6 |
+
|
| 7 |
+
def _clean(s: str) -> str:
|
| 8 |
+
return re.sub(r'\s+', ' ', s).strip().rstrip(',').rstrip('.').strip()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _extract_account(text: str) -> str | None:
|
| 12 |
+
patterns = [
|
| 13 |
+
r'(?:PRIME MARITIME)[^\n]*',
|
| 14 |
+
r'(?:ACC(?:OUNT)?\s+)([\w\s]+?)(?:\n|$)',
|
| 15 |
+
r'(?:FROM|ON\s+BEHALF\s+OF)\s*:?\s*([\w\s&.,]+?)(?:\n|$)',
|
| 16 |
+
r'DEAR\s+SIRS[^\n]*\n.*?([A-Z][A-Z\s&.]+(?:INC|LTD|CO|CORP|SHIPPING|MARITIME)[^\n]*)',
|
| 17 |
+
]
|
| 18 |
+
for p in patterns:
|
| 19 |
+
m = re.search(p, text, re.IGNORECASE)
|
| 20 |
+
if m:
|
| 21 |
+
grp = m.group(1) if m.lastindex else m.group(0)
|
| 22 |
+
val = _clean(grp)
|
| 23 |
+
if 3 < len(val) < 80:
|
| 24 |
+
return val
|
| 25 |
+
# Try extracting company from email domain
|
| 26 |
+
m = re.search(r'@([\w-]+)\.', text)
|
| 27 |
+
if m:
|
| 28 |
+
return m.group(1).capitalize()
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _extract_flag(text: str) -> str | None:
|
| 33 |
+
m = re.search(r'(?:FLAG\s*:?\s*|FLAG\s+)([A-Z][A-Z\s]+?)(?:\n|CLASS|BUILT|LOA|$)', text, re.IGNORECASE)
|
| 34 |
+
if m:
|
| 35 |
+
return _clean(m.group(1))[:50]
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _extract_built(text: str) -> str | None:
|
| 40 |
+
m = re.search(r'(?:BUILT|BLT)\s*:?\s*(\d{4})', text, re.IGNORECASE)
|
| 41 |
+
if m:
|
| 42 |
+
return m.group(1)
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _extract_class(text: str) -> str | None:
|
| 47 |
+
m = re.search(r'(?:CLASS(?:IFICATION)?\s*:?\s*|CLASSED\s+)([A-Z]+(?:\s+[A-Z]+)?)', text, re.IGNORECASE)
|
| 48 |
+
if m:
|
| 49 |
+
val = _clean(m.group(1))[:50]
|
| 50 |
+
if val.lower() not in ('class', 'highest'):
|
| 51 |
+
return val
|
| 52 |
+
# Common class notations inline
|
| 53 |
+
m = re.search(r'\b(LR|ABS|NK|BV|DNV|GL|CCS|KR|RINA|PRS)\b', text)
|
| 54 |
+
if m:
|
| 55 |
+
return m.group(1)
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _extract_loa(text: str) -> str | None:
|
| 60 |
+
m = re.search(r'LOA\s*[:/]?\s*([\d.]+)\s*M', text, re.IGNORECASE)
|
| 61 |
+
if m:
|
| 62 |
+
return m.group(1) + 'M'
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _extract_beam(text: str) -> str | None:
|
| 67 |
+
m = re.search(r'(?:BEAM|BREADTH)\s*[:/]?\s*([\d.]+)\s*M', text, re.IGNORECASE)
|
| 68 |
+
if m:
|
| 69 |
+
return m.group(1) + 'M'
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _extract_vessel_type(text: str) -> str:
|
| 74 |
+
t = text.upper()
|
| 75 |
+
if 'SDBC' in t:
|
| 76 |
+
return 'SDBC'
|
| 77 |
+
if 'SDSTBC' in t:
|
| 78 |
+
return 'SDSTBC'
|
| 79 |
+
if 'BULK CARRIER' in t:
|
| 80 |
+
return 'BULK CARRIER'
|
| 81 |
+
if 'CAPESIZE' in t:
|
| 82 |
+
return 'CAPESIZE BULK'
|
| 83 |
+
if 'PANAMAX' in t:
|
| 84 |
+
return 'PANAMAX BULK'
|
| 85 |
+
if 'SUPRAMAX' in t or 'ULTRAMAX' in t:
|
| 86 |
+
return 'SUPRAMAX BULK'
|
| 87 |
+
if 'HANDYMAX' in t:
|
| 88 |
+
return 'HANDYMAX BULK'
|
| 89 |
+
if 'HANDYSIZE' in t:
|
| 90 |
+
return 'HANDYSIZE BULK'
|
| 91 |
+
return 'BULK CARRIER'
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _enrich(vessel: dict, section: str):
|
| 95 |
+
"""Try to fill in blank fields from a vessel detail section."""
|
| 96 |
+
sec_up = section.upper()
|
| 97 |
+
name = vessel.get('vessel_name', '')
|
| 98 |
+
if name and name.upper() not in sec_up:
|
| 99 |
+
return # This section is not about this vessel
|
| 100 |
+
|
| 101 |
+
if not vessel.get('flag'):
|
| 102 |
+
vessel['flag'] = _extract_flag(section)
|
| 103 |
+
if not vessel.get('built_year'):
|
| 104 |
+
vessel['built_year'] = _extract_built(section)
|
| 105 |
+
if not vessel.get('class_society'):
|
| 106 |
+
vessel['class_society'] = _extract_class(section)
|
| 107 |
+
if not vessel.get('loa'):
|
| 108 |
+
vessel['loa'] = _extract_loa(section)
|
| 109 |
+
if not vessel.get('beam'):
|
| 110 |
+
vessel['beam'] = _extract_beam(section)
|
| 111 |
+
if not vessel.get('vessel_type') or vessel.get('vessel_type') == 'BULK CARRIER':
|
| 112 |
+
vt = _extract_vessel_type(section)
|
| 113 |
+
if vt != 'BULK CARRIER':
|
| 114 |
+
vessel['vessel_type'] = vt
|
| 115 |
+
# Try enriching DWT from detailed specs
|
| 116 |
+
if not vessel.get('vessel_size'):
|
| 117 |
+
m = re.search(r'DWT\s*([\d,\.]+)\s*MT|(\d[\d,\.]+)\s*(?:MT\s+)?DWT', section, re.IGNORECASE)
|
| 118 |
+
if m:
|
| 119 |
+
val = (m.group(1) or m.group(2)).replace(',', '').strip()
|
| 120 |
+
vessel['vessel_size'] = val + ' DWT'
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# ── Main extractor ────────────────────────────────────────────────────────────
|
| 124 |
+
|
| 125 |
+
def extract_tonnage(text: str, email_id: int) -> list[dict]:
|
| 126 |
+
"""Extract all vessels from a tonnage email. Returns list of vessel dicts."""
|
| 127 |
+
vessels: list[dict] = []
|
| 128 |
+
text_up = text.upper()
|
| 129 |
+
|
| 130 |
+
# ── Pattern 1: "MV VESSEL DWT XXXXX OPEN PORT O/A DATE" ─────────────────
|
| 131 |
+
p1 = re.compile(
|
| 132 |
+
r'(?:MV|M/V)\s+([A-Z][A-Z0-9\s]{2,35}?)\s+'
|
| 133 |
+
r'DWT\s+([\d,\.]+)\s+'
|
| 134 |
+
r'OPEN\s+([A-Z][A-Z\s,./\-]{2,40}?)\s+'
|
| 135 |
+
r'O/A\s+([A-Z0-9\s\-/]+)',
|
| 136 |
+
re.IGNORECASE | re.MULTILINE,
|
| 137 |
+
)
|
| 138 |
+
for m in p1.finditer(text_up):
|
| 139 |
+
vessel_name = _clean(m.group(1))
|
| 140 |
+
dwt = m.group(2).replace(',', '').replace('.', '')
|
| 141 |
+
open_port = _clean(m.group(3))
|
| 142 |
+
open_date = _clean(m.group(4))
|
| 143 |
+
if not any(v['vessel_name'] == vessel_name for v in vessels):
|
| 144 |
+
vessels.append({
|
| 145 |
+
'email_id': email_id,
|
| 146 |
+
'vessel_name': vessel_name,
|
| 147 |
+
'vessel_size': dwt + ' DWT',
|
| 148 |
+
'open_port': open_port,
|
| 149 |
+
'open_date': open_date,
|
| 150 |
+
'vessel_type': 'BULK CARRIER',
|
| 151 |
+
'account_name': _extract_account(text),
|
| 152 |
+
'flag': None, 'built_year': None, 'class_society': None,
|
| 153 |
+
'loa': None, 'beam': None,
|
| 154 |
+
})
|
| 155 |
+
|
| 156 |
+
# ── Pattern 2: "VESSEL_NAME (XXK – SCRUBBER / YEAR) – OPEN PORT DATE" ───
|
| 157 |
+
p2 = re.compile(
|
| 158 |
+
r'([A-Z][A-Z\s]{3,30}?)\s*\((\d+)K\s*[-–][^)]{0,60}\)\s*[-–]+\s*OPEN\s+'
|
| 159 |
+
r'([A-Z][A-Z\s,]{2,40}?),\s*([A-Z][A-Z\s]+?)\s+(\d{2}[-–]\d{2}\s+\w+|\d{1,2}\s+\w+)',
|
| 160 |
+
re.IGNORECASE,
|
| 161 |
+
)
|
| 162 |
+
for m in p2.finditer(text_up):
|
| 163 |
+
vessel_name = _clean(m.group(1))
|
| 164 |
+
dwt_k = m.group(2)
|
| 165 |
+
open_port = _clean(m.group(3)) + ', ' + _clean(m.group(4))
|
| 166 |
+
open_date = _clean(m.group(5))
|
| 167 |
+
if not any(v['vessel_name'] == vessel_name for v in vessels):
|
| 168 |
+
vessels.append({
|
| 169 |
+
'email_id': email_id,
|
| 170 |
+
'vessel_name': vessel_name,
|
| 171 |
+
'vessel_size': dwt_k + 'K DWT',
|
| 172 |
+
'open_port': open_port,
|
| 173 |
+
'open_date': open_date,
|
| 174 |
+
'vessel_type': 'BULK CARRIER',
|
| 175 |
+
'account_name': _extract_account(text),
|
| 176 |
+
'flag': None, 'built_year': None, 'class_society': None,
|
| 177 |
+
'loa': None, 'beam': None,
|
| 178 |
+
})
|
| 179 |
+
|
| 180 |
+
# ── Pattern 3: Single vessel intro "MV TRUE FRIEND/51K/ 09 - BEJAIA, 1ST JUNE" ─
|
| 181 |
+
p3 = re.compile(
|
| 182 |
+
r'(?:MV|M/V)\s+([A-Z][A-Z\s]{2,30}?)\s*/\s*(\d+)K\s*/\s*(\d{2})\s*[-–]\s*'
|
| 183 |
+
r'([A-Z][A-Z\s,]+?),?\s*([0-9A-Z\s]+(?:JUNE|JULY|AUG|SEP|OCT|NOV|DEC|JAN|FEB|MAR|APR|MAY)[^\n]*)',
|
| 184 |
+
re.IGNORECASE,
|
| 185 |
+
)
|
| 186 |
+
for m in p3.finditer(text_up):
|
| 187 |
+
vessel_name = _clean(m.group(1))
|
| 188 |
+
dwt_k = m.group(2)
|
| 189 |
+
open_port = _clean(m.group(4))
|
| 190 |
+
open_date = _clean(m.group(5))
|
| 191 |
+
if not any(v['vessel_name'] == vessel_name for v in vessels):
|
| 192 |
+
vessels.append({
|
| 193 |
+
'email_id': email_id,
|
| 194 |
+
'vessel_name': vessel_name,
|
| 195 |
+
'vessel_size': dwt_k + 'K DWT',
|
| 196 |
+
'open_port': open_port,
|
| 197 |
+
'open_date': open_date,
|
| 198 |
+
'vessel_type': 'BULK CARRIER',
|
| 199 |
+
'account_name': _extract_account(text),
|
| 200 |
+
'flag': None, 'built_year': None, 'class_society': None,
|
| 201 |
+
'loa': None, 'beam': None,
|
| 202 |
+
})
|
| 203 |
+
|
| 204 |
+
# ── Enrich vessels from detail sections (separated by ---) ───────────────
|
| 205 |
+
sections = re.split(r'\n[-]{10,}\n', text)
|
| 206 |
+
for section in sections:
|
| 207 |
+
for vessel in vessels:
|
| 208 |
+
_enrich(vessel, section)
|
| 209 |
+
|
| 210 |
+
# ── Fallback: single vessel email ────────────────────────────────────────
|
| 211 |
+
if not vessels:
|
| 212 |
+
v = _extract_single_vessel_fallback(text, email_id)
|
| 213 |
+
if v:
|
| 214 |
+
vessels.append(v)
|
| 215 |
+
|
| 216 |
+
return vessels
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _extract_single_vessel_fallback(text: str, email_id: int) -> dict | None:
|
| 220 |
+
text_up = text.upper()
|
| 221 |
+
# Try "M/V: VESSEL_NAME" or "MV VESSEL_NAME\n"
|
| 222 |
+
m = re.search(r'(?:M/V\s*:\s*|^MV\s+)([A-Z][A-Z0-9\s]{2,30})$', text_up, re.MULTILINE)
|
| 223 |
+
if not m:
|
| 224 |
+
m = re.search(r'(?:VESSEL|VSL)\s*[:\s]+([A-Z][A-Z0-9\s]{3,30})$', text_up, re.MULTILINE)
|
| 225 |
+
if not m:
|
| 226 |
+
return None
|
| 227 |
+
|
| 228 |
+
vessel_name = _clean(m.group(1))
|
| 229 |
+
dwt_m = re.search(r'DWT\s*([\d,\.]+)\s*MT|([\d,\.]+)\s*(?:MT\s+)?DWT', text_up)
|
| 230 |
+
dwt = None
|
| 231 |
+
if dwt_m:
|
| 232 |
+
dwt = (dwt_m.group(1) or dwt_m.group(2)).replace(',', '') + ' DWT'
|
| 233 |
+
|
| 234 |
+
open_port, open_date = _extract_open_port_date(text_up)
|
| 235 |
+
|
| 236 |
+
return {
|
| 237 |
+
'email_id': email_id,
|
| 238 |
+
'vessel_name': vessel_name,
|
| 239 |
+
'vessel_size': dwt,
|
| 240 |
+
'open_port': open_port,
|
| 241 |
+
'open_date': open_date,
|
| 242 |
+
'vessel_type': _extract_vessel_type(text),
|
| 243 |
+
'account_name': _extract_account(text),
|
| 244 |
+
'flag': _extract_flag(text),
|
| 245 |
+
'built_year': _extract_built(text),
|
| 246 |
+
'class_society': _extract_class(text),
|
| 247 |
+
'loa': _extract_loa(text),
|
| 248 |
+
'beam': _extract_beam(text),
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _extract_open_port_date(text_up: str) -> tuple[str | None, str | None]:
|
| 253 |
+
m = re.search(r'OPEN\s+([A-Z][A-Z\s,]{2,40}?)\s+(?:O/A|ETA)?\s*(\d[^\n]{3,25})', text_up)
|
| 254 |
+
if m:
|
| 255 |
+
return _clean(m.group(1)), _clean(m.group(2))
|
| 256 |
+
m = re.search(r'OPEN\s+([A-Z][A-Z\s,]{2,40})', text_up)
|
| 257 |
+
if m:
|
| 258 |
+
return _clean(m.group(1)), None
|
| 259 |
+
return None, None
|
ingestion/__init__.py
ADDED
|
File without changes
|
ingestion/email_parser.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lightweight email text normaliser + attachment parser — no external deps required."""
|
| 2 |
+
import re
|
| 3 |
+
import email as _email_lib
|
| 4 |
+
from email import policy as _policy
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# ── Plain text / paste parser ─────────────────────────────────────────────────
|
| 8 |
+
|
| 9 |
+
def parse_email(raw: str) -> dict:
|
| 10 |
+
"""
|
| 11 |
+
Accepts raw email text (paste or file content).
|
| 12 |
+
Returns dict with: subject, sender, body (cleaned).
|
| 13 |
+
"""
|
| 14 |
+
lines = raw.splitlines()
|
| 15 |
+
subject = 'Manual Input'
|
| 16 |
+
sender = 'unknown'
|
| 17 |
+
body_lines = []
|
| 18 |
+
in_header = True
|
| 19 |
+
|
| 20 |
+
for line in lines:
|
| 21 |
+
stripped = line.strip()
|
| 22 |
+
if in_header:
|
| 23 |
+
if stripped.lower().startswith('subject:'):
|
| 24 |
+
subject = stripped[8:].strip()
|
| 25 |
+
elif stripped.lower().startswith('from:'):
|
| 26 |
+
sender = stripped[5:].strip()
|
| 27 |
+
elif stripped == '':
|
| 28 |
+
in_header = False
|
| 29 |
+
else:
|
| 30 |
+
body_lines.append(line)
|
| 31 |
+
|
| 32 |
+
body = '\n'.join(body_lines) if body_lines else raw
|
| 33 |
+
|
| 34 |
+
# Clean up excessive whitespace while preserving structure
|
| 35 |
+
body = re.sub(r'\r\n', '\n', body)
|
| 36 |
+
body = re.sub(r'\n{4,}', '\n\n\n', body)
|
| 37 |
+
|
| 38 |
+
return {
|
| 39 |
+
'subject': subject,
|
| 40 |
+
'sender': sender,
|
| 41 |
+
'body': body.strip(),
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ── EML parser (stdlib `email`) ────────────────────────────────────────────────
|
| 46 |
+
|
| 47 |
+
def parse_eml_bytes(raw_bytes: bytes) -> dict:
|
| 48 |
+
"""
|
| 49 |
+
Parse a raw .eml file. Extracts subject, sender, and the plain-text body.
|
| 50 |
+
Attachment text content is appended after the main body.
|
| 51 |
+
Returns dict: {subject, sender, body, attachments: [{filename, text}]}
|
| 52 |
+
"""
|
| 53 |
+
msg = _email_lib.message_from_bytes(raw_bytes, policy=_policy.default)
|
| 54 |
+
|
| 55 |
+
subject = str(msg.get('Subject', 'No Subject'))
|
| 56 |
+
sender = str(msg.get('From', 'unknown'))
|
| 57 |
+
|
| 58 |
+
body_parts = []
|
| 59 |
+
attachments = []
|
| 60 |
+
|
| 61 |
+
for part in msg.walk():
|
| 62 |
+
content_type = part.get_content_type()
|
| 63 |
+
disposition = str(part.get('Content-Disposition', ''))
|
| 64 |
+
filename = part.get_filename()
|
| 65 |
+
|
| 66 |
+
if filename:
|
| 67 |
+
# It's an attachment
|
| 68 |
+
try:
|
| 69 |
+
payload = part.get_payload(decode=True) or b''
|
| 70 |
+
att_text = extract_text_from_attachment(filename, payload)
|
| 71 |
+
if att_text:
|
| 72 |
+
attachments.append({'filename': filename, 'text': att_text})
|
| 73 |
+
body_parts.append(f'\n\n--- Attachment: {filename} ---\n{att_text}')
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
elif content_type == 'text/plain' and 'attachment' not in disposition:
|
| 77 |
+
try:
|
| 78 |
+
charset = part.get_content_charset() or 'utf-8'
|
| 79 |
+
payload = part.get_payload(decode=True) or b''
|
| 80 |
+
body_parts.append(payload.decode(charset, errors='replace'))
|
| 81 |
+
except Exception:
|
| 82 |
+
pass
|
| 83 |
+
|
| 84 |
+
body = '\n'.join(body_parts).strip()
|
| 85 |
+
body = re.sub(r'\n{4,}', '\n\n\n', body)
|
| 86 |
+
|
| 87 |
+
return {
|
| 88 |
+
'subject': subject,
|
| 89 |
+
'sender': sender,
|
| 90 |
+
'body': body,
|
| 91 |
+
'attachments': attachments,
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# ── Attachment text extractor ─────────────────────────────────────────────────
|
| 96 |
+
|
| 97 |
+
def extract_text_from_attachment(filename: str, data: bytes) -> str:
|
| 98 |
+
"""
|
| 99 |
+
Extract plain text from an attachment payload.
|
| 100 |
+
Supports: .txt, .csv, .pdf (via pdfminer.six if installed; regex fallback otherwise).
|
| 101 |
+
"""
|
| 102 |
+
name_lower = (filename or '').lower()
|
| 103 |
+
|
| 104 |
+
if name_lower.endswith(('.txt', '.csv')):
|
| 105 |
+
return data.decode('utf-8', errors='replace')
|
| 106 |
+
|
| 107 |
+
if name_lower.endswith('.pdf'):
|
| 108 |
+
return _extract_pdf_text(data)
|
| 109 |
+
|
| 110 |
+
# Try decoding unknown types as UTF-8 text
|
| 111 |
+
try:
|
| 112 |
+
return data.decode('utf-8', errors='replace')
|
| 113 |
+
except Exception:
|
| 114 |
+
return ''
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _extract_pdf_text(data: bytes) -> str:
|
| 118 |
+
"""Extract text from PDF bytes. Uses pdfminer.six if available, else regex fallback."""
|
| 119 |
+
try:
|
| 120 |
+
from pdfminer.high_level import extract_text_to_fp
|
| 121 |
+
from pdfminer.layout import LAParams
|
| 122 |
+
import io
|
| 123 |
+
|
| 124 |
+
output = io.StringIO()
|
| 125 |
+
extract_text_to_fp(io.BytesIO(data), output, laparams=LAParams())
|
| 126 |
+
return output.getvalue().strip()
|
| 127 |
+
except ImportError:
|
| 128 |
+
pass
|
| 129 |
+
|
| 130 |
+
# Regex fallback: extract printable text chunks from raw PDF bytes
|
| 131 |
+
raw = data.decode('latin-1', errors='replace')
|
| 132 |
+
chunks = re.findall(r'\(([^\)]{3,})\)', raw)
|
| 133 |
+
return ' '.join(c for c in chunks if re.search(r'[a-zA-Z]{3,}', c)).strip()
|
render.yaml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
- type: web
|
| 3 |
+
name: ship-email-segregation
|
| 4 |
+
env: python
|
| 5 |
+
region: oregon
|
| 6 |
+
plan: free
|
| 7 |
+
buildCommand: pip install -r requirements.txt && python seed.py
|
| 8 |
+
startCommand: gunicorn app:app --bind 0.0.0.0:$PORT --workers 2 --timeout 120
|
| 9 |
+
envVars:
|
| 10 |
+
- key: PYTHON_VERSION
|
| 11 |
+
value: 3.11.0
|
| 12 |
+
- key: FLASK_ENV
|
| 13 |
+
value: production
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask==3.0.3
|
| 2 |
+
flask-cors==4.0.1
|
| 3 |
+
scikit-learn==1.5.2
|
| 4 |
+
sqlalchemy==2.0.36
|
| 5 |
+
numpy==1.26.4
|
| 6 |
+
python-dotenv==1.0.1
|
| 7 |
+
gunicorn==23.0.0
|
| 8 |
+
pdfminer.six==20231228
|
routes/__init__.py
ADDED
|
File without changes
|
routes/cargo_tc.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import io
|
| 3 |
+
from flask import Blueprint, request, jsonify, Response
|
| 4 |
+
from database.db import get_session
|
| 5 |
+
from database.models import CargoTC
|
| 6 |
+
|
| 7 |
+
cargo_tc_bp = Blueprint('cargo_tc', __name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@cargo_tc_bp.route('/cargo_tc', methods=['GET'])
|
| 11 |
+
def get_cargo_tc():
|
| 12 |
+
session = get_session()
|
| 13 |
+
try:
|
| 14 |
+
page = max(1, int(request.args.get('page', 1)))
|
| 15 |
+
per_page = min(100, int(request.args.get('per_page', 20)))
|
| 16 |
+
search = request.args.get('search', '').strip()
|
| 17 |
+
|
| 18 |
+
query = session.query(CargoTC)
|
| 19 |
+
if search:
|
| 20 |
+
query = query.filter(
|
| 21 |
+
CargoTC.cargo_name.ilike(f'%{search}%') |
|
| 22 |
+
CargoTC.delivery_port.ilike(f'%{search}%') |
|
| 23 |
+
CargoTC.redelivery_port.ilike(f'%{search}%')
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
total = query.count()
|
| 27 |
+
records = (
|
| 28 |
+
query.order_by(CargoTC.id.desc())
|
| 29 |
+
.offset((page - 1) * per_page)
|
| 30 |
+
.limit(per_page)
|
| 31 |
+
.all()
|
| 32 |
+
)
|
| 33 |
+
return jsonify({
|
| 34 |
+
'records': [r.to_dict() for r in records],
|
| 35 |
+
'total': total,
|
| 36 |
+
'page': page,
|
| 37 |
+
'per_page': per_page,
|
| 38 |
+
})
|
| 39 |
+
finally:
|
| 40 |
+
session.close()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@cargo_tc_bp.route('/cargo_tc/<int:record_id>', methods=['GET'])
|
| 44 |
+
def get_cargo_tc_record(record_id):
|
| 45 |
+
session = get_session()
|
| 46 |
+
try:
|
| 47 |
+
obj = session.get(CargoTC, record_id)
|
| 48 |
+
if not obj:
|
| 49 |
+
return jsonify({'error': 'Not found'}), 404
|
| 50 |
+
return jsonify(obj.to_dict())
|
| 51 |
+
finally:
|
| 52 |
+
session.close()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@cargo_tc_bp.route('/cargo_tc/<int:record_id>', methods=['PATCH'])
|
| 56 |
+
def update_cargo_tc(record_id):
|
| 57 |
+
session = get_session()
|
| 58 |
+
try:
|
| 59 |
+
obj = session.get(CargoTC, record_id)
|
| 60 |
+
if not obj:
|
| 61 |
+
return jsonify({'error': 'Not found'}), 404
|
| 62 |
+
data = request.get_json(force=True)
|
| 63 |
+
allowed = [
|
| 64 |
+
'account_name', 'cargo_name', 'delivery_port', 'redelivery_port',
|
| 65 |
+
'duration', 'laycan', 'cargo_type',
|
| 66 |
+
]
|
| 67 |
+
for field in allowed:
|
| 68 |
+
if field in data:
|
| 69 |
+
setattr(obj, field, data[field])
|
| 70 |
+
session.commit()
|
| 71 |
+
return jsonify(obj.to_dict())
|
| 72 |
+
except Exception as exc:
|
| 73 |
+
session.rollback()
|
| 74 |
+
return jsonify({'error': str(exc)}), 500
|
| 75 |
+
finally:
|
| 76 |
+
session.close()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@cargo_tc_bp.route('/cargo_tc/<int:record_id>', methods=['DELETE'])
|
| 80 |
+
def delete_cargo_tc(record_id):
|
| 81 |
+
session = get_session()
|
| 82 |
+
try:
|
| 83 |
+
obj = session.get(CargoTC, record_id)
|
| 84 |
+
if not obj:
|
| 85 |
+
return jsonify({'error': 'Not found'}), 404
|
| 86 |
+
session.delete(obj)
|
| 87 |
+
session.commit()
|
| 88 |
+
return jsonify({'success': True})
|
| 89 |
+
finally:
|
| 90 |
+
session.close()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@cargo_tc_bp.route('/cargo_tc/export', methods=['GET'])
|
| 94 |
+
def export_cargo_tc_csv():
|
| 95 |
+
session = get_session()
|
| 96 |
+
try:
|
| 97 |
+
records = session.query(CargoTC).order_by(CargoTC.id).all()
|
| 98 |
+
output = io.StringIO()
|
| 99 |
+
fields = ['id', 'email_id', 'account_name', 'cargo_name', 'delivery_port',
|
| 100 |
+
'redelivery_port', 'duration', 'laycan', 'cargo_type']
|
| 101 |
+
writer = csv.DictWriter(output, fieldnames=fields, extrasaction='ignore')
|
| 102 |
+
writer.writeheader()
|
| 103 |
+
for r in records:
|
| 104 |
+
writer.writerow(r.to_dict())
|
| 105 |
+
csv_bytes = output.getvalue().encode('utf-8')
|
| 106 |
+
return Response(
|
| 107 |
+
csv_bytes,
|
| 108 |
+
mimetype='text/csv',
|
| 109 |
+
headers={'Content-Disposition': 'attachment; filename=cargo_tc_export.csv'},
|
| 110 |
+
)
|
| 111 |
+
finally:
|
| 112 |
+
session.close()
|
routes/cargo_vc.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import io
|
| 3 |
+
from flask import Blueprint, request, jsonify, Response
|
| 4 |
+
from database.db import get_session
|
| 5 |
+
from database.models import CargoVC
|
| 6 |
+
|
| 7 |
+
cargo_vc_bp = Blueprint('cargo_vc', __name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@cargo_vc_bp.route('/cargo_vc', methods=['GET'])
|
| 11 |
+
def get_cargo_vc():
|
| 12 |
+
session = get_session()
|
| 13 |
+
try:
|
| 14 |
+
page = max(1, int(request.args.get('page', 1)))
|
| 15 |
+
per_page = min(100, int(request.args.get('per_page', 20)))
|
| 16 |
+
search = request.args.get('search', '').strip()
|
| 17 |
+
|
| 18 |
+
query = session.query(CargoVC)
|
| 19 |
+
if search:
|
| 20 |
+
query = query.filter(
|
| 21 |
+
CargoVC.cargo_name.ilike(f'%{search}%') |
|
| 22 |
+
CargoVC.loading_port.ilike(f'%{search}%') |
|
| 23 |
+
CargoVC.discharge_port.ilike(f'%{search}%')
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
total = query.count()
|
| 27 |
+
records = (
|
| 28 |
+
query.order_by(CargoVC.id.desc())
|
| 29 |
+
.offset((page - 1) * per_page)
|
| 30 |
+
.limit(per_page)
|
| 31 |
+
.all()
|
| 32 |
+
)
|
| 33 |
+
return jsonify({
|
| 34 |
+
'records': [r.to_dict() for r in records],
|
| 35 |
+
'total': total,
|
| 36 |
+
'page': page,
|
| 37 |
+
'per_page': per_page,
|
| 38 |
+
})
|
| 39 |
+
finally:
|
| 40 |
+
session.close()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@cargo_vc_bp.route('/cargo_vc/<int:record_id>', methods=['GET'])
|
| 44 |
+
def get_cargo_vc_record(record_id):
|
| 45 |
+
session = get_session()
|
| 46 |
+
try:
|
| 47 |
+
obj = session.get(CargoVC, record_id)
|
| 48 |
+
if not obj:
|
| 49 |
+
return jsonify({'error': 'Not found'}), 404
|
| 50 |
+
return jsonify(obj.to_dict())
|
| 51 |
+
finally:
|
| 52 |
+
session.close()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@cargo_vc_bp.route('/cargo_vc/<int:record_id>', methods=['PATCH'])
|
| 56 |
+
def update_cargo_vc(record_id):
|
| 57 |
+
session = get_session()
|
| 58 |
+
try:
|
| 59 |
+
obj = session.get(CargoVC, record_id)
|
| 60 |
+
if not obj:
|
| 61 |
+
return jsonify({'error': 'Not found'}), 404
|
| 62 |
+
data = request.get_json(force=True)
|
| 63 |
+
allowed = [
|
| 64 |
+
'account_name', 'cargo_name', 'loading_port', 'discharge_port',
|
| 65 |
+
'laycan', 'cargo_type', 'quantity',
|
| 66 |
+
]
|
| 67 |
+
for field in allowed:
|
| 68 |
+
if field in data:
|
| 69 |
+
setattr(obj, field, data[field])
|
| 70 |
+
session.commit()
|
| 71 |
+
return jsonify(obj.to_dict())
|
| 72 |
+
except Exception as exc:
|
| 73 |
+
session.rollback()
|
| 74 |
+
return jsonify({'error': str(exc)}), 500
|
| 75 |
+
finally:
|
| 76 |
+
session.close()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@cargo_vc_bp.route('/cargo_vc/<int:record_id>', methods=['DELETE'])
|
| 80 |
+
def delete_cargo_vc(record_id):
|
| 81 |
+
session = get_session()
|
| 82 |
+
try:
|
| 83 |
+
obj = session.get(CargoVC, record_id)
|
| 84 |
+
if not obj:
|
| 85 |
+
return jsonify({'error': 'Not found'}), 404
|
| 86 |
+
session.delete(obj)
|
| 87 |
+
session.commit()
|
| 88 |
+
return jsonify({'success': True})
|
| 89 |
+
finally:
|
| 90 |
+
session.close()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@cargo_vc_bp.route('/cargo_vc/export', methods=['GET'])
|
| 94 |
+
def export_cargo_vc_csv():
|
| 95 |
+
session = get_session()
|
| 96 |
+
try:
|
| 97 |
+
records = session.query(CargoVC).order_by(CargoVC.id).all()
|
| 98 |
+
output = io.StringIO()
|
| 99 |
+
fields = ['id', 'email_id', 'account_name', 'cargo_name', 'loading_port',
|
| 100 |
+
'discharge_port', 'laycan', 'cargo_type', 'quantity']
|
| 101 |
+
writer = csv.DictWriter(output, fieldnames=fields, extrasaction='ignore')
|
| 102 |
+
writer.writeheader()
|
| 103 |
+
for r in records:
|
| 104 |
+
writer.writerow(r.to_dict())
|
| 105 |
+
csv_bytes = output.getvalue().encode('utf-8')
|
| 106 |
+
return Response(
|
| 107 |
+
csv_bytes,
|
| 108 |
+
mimetype='text/csv',
|
| 109 |
+
headers={'Content-Disposition': 'attachment; filename=cargo_vc_export.csv'},
|
| 110 |
+
)
|
| 111 |
+
finally:
|
| 112 |
+
session.close()
|
routes/emails.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
import io
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
from flask import Blueprint, request, jsonify
|
| 6 |
+
from database.db import get_session
|
| 7 |
+
from database.models import Email
|
| 8 |
+
from classification.classifier import classify
|
| 9 |
+
from extraction.extractor import extract
|
| 10 |
+
from ingestion.email_parser import parse_email, parse_eml_bytes, extract_text_from_attachment
|
| 11 |
+
|
| 12 |
+
emails_bp = Blueprint('emails', __name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# ── Fingerprint helper ────────────────────────────────────────────────────────
|
| 16 |
+
|
| 17 |
+
def _fingerprint(text: str) -> str:
|
| 18 |
+
"""Normalise and hash first 1000 chars for dedup detection."""
|
| 19 |
+
normalised = re.sub(r'[\s\W]+', '', text.lower())[:1000]
|
| 20 |
+
return hashlib.sha256(normalised.encode()).hexdigest()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ── Helper: classify + extract + save ─────────────────────────────────────────
|
| 24 |
+
|
| 25 |
+
def _process_and_save(raw_text: str, subject: str, sender: str, session) -> dict:
|
| 26 |
+
"""Run classify→extract→save pipeline. Returns result dict."""
|
| 27 |
+
fp = _fingerprint(raw_text)
|
| 28 |
+
|
| 29 |
+
# Dedup check
|
| 30 |
+
existing = session.query(Email).filter_by(fingerprint=fp).first()
|
| 31 |
+
is_dup = existing is not None
|
| 32 |
+
duplicated_of = existing.id if existing else None
|
| 33 |
+
|
| 34 |
+
category, confidence = classify(raw_text)
|
| 35 |
+
|
| 36 |
+
email_obj = Email(
|
| 37 |
+
subject=subject,
|
| 38 |
+
sender=sender,
|
| 39 |
+
raw_body=raw_text,
|
| 40 |
+
category=category,
|
| 41 |
+
confidence=confidence,
|
| 42 |
+
is_duplicate=is_dup,
|
| 43 |
+
fingerprint=fp,
|
| 44 |
+
)
|
| 45 |
+
session.add(email_obj)
|
| 46 |
+
session.flush()
|
| 47 |
+
|
| 48 |
+
extracted = extract(category, raw_text, email_obj.id, session)
|
| 49 |
+
session.commit()
|
| 50 |
+
|
| 51 |
+
result = {
|
| 52 |
+
'email': email_obj.to_dict(),
|
| 53 |
+
'extracted': extracted,
|
| 54 |
+
'category': category,
|
| 55 |
+
'confidence': round(confidence, 3),
|
| 56 |
+
'is_duplicate': is_dup,
|
| 57 |
+
}
|
| 58 |
+
if duplicated_of:
|
| 59 |
+
result['duplicated_of'] = duplicated_of
|
| 60 |
+
return result
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# ── GET /api/emails ───────────────────────────────────────────────────────────
|
| 64 |
+
|
| 65 |
+
@emails_bp.route('/emails', methods=['GET'])
|
| 66 |
+
def get_emails():
|
| 67 |
+
session = get_session()
|
| 68 |
+
try:
|
| 69 |
+
page = max(1, int(request.args.get('page', 1)))
|
| 70 |
+
per_page = min(100, int(request.args.get('per_page', 20)))
|
| 71 |
+
category = request.args.get('category', '').strip() or None
|
| 72 |
+
search = request.args.get('search', '').strip()
|
| 73 |
+
show_dupes = request.args.get('duplicates_only', '').lower() == 'true'
|
| 74 |
+
|
| 75 |
+
query = session.query(Email)
|
| 76 |
+
if category:
|
| 77 |
+
query = query.filter(Email.category == category)
|
| 78 |
+
if search:
|
| 79 |
+
query = query.filter(
|
| 80 |
+
Email.raw_body.ilike(f'%{search}%') |
|
| 81 |
+
Email.subject.ilike(f'%{search}%')
|
| 82 |
+
)
|
| 83 |
+
if show_dupes:
|
| 84 |
+
query = query.filter(Email.is_duplicate == True) # noqa: E712
|
| 85 |
+
|
| 86 |
+
total = query.count()
|
| 87 |
+
emails = (
|
| 88 |
+
query.order_by(Email.created_at.desc())
|
| 89 |
+
.offset((page - 1) * per_page)
|
| 90 |
+
.limit(per_page)
|
| 91 |
+
.all()
|
| 92 |
+
)
|
| 93 |
+
return jsonify({
|
| 94 |
+
'emails': [e.to_dict() for e in emails],
|
| 95 |
+
'total': total,
|
| 96 |
+
'page': page,
|
| 97 |
+
'per_page': per_page,
|
| 98 |
+
})
|
| 99 |
+
finally:
|
| 100 |
+
session.close()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# ── POST /api/emails (paste / text submit) ────────────────────────────────────
|
| 104 |
+
|
| 105 |
+
@emails_bp.route('/emails', methods=['POST'])
|
| 106 |
+
def process_email():
|
| 107 |
+
data = request.get_json(force=True)
|
| 108 |
+
raw_text = (data.get('text') or '').strip()
|
| 109 |
+
subject = (data.get('subject') or 'Manual Input').strip()
|
| 110 |
+
sender = (data.get('sender') or 'manual@system').strip()
|
| 111 |
+
|
| 112 |
+
if not raw_text:
|
| 113 |
+
return jsonify({'error': 'No email text provided'}), 400
|
| 114 |
+
|
| 115 |
+
session = get_session()
|
| 116 |
+
try:
|
| 117 |
+
result = _process_and_save(raw_text, subject, sender, session)
|
| 118 |
+
status = 200 if result['is_duplicate'] else 201
|
| 119 |
+
return jsonify(result), status
|
| 120 |
+
except Exception as exc:
|
| 121 |
+
session.rollback()
|
| 122 |
+
return jsonify({'error': str(exc)}), 500
|
| 123 |
+
finally:
|
| 124 |
+
session.close()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# ── POST /api/emails/upload (file upload: .eml / .txt / .pdf) ────────────────
|
| 128 |
+
|
| 129 |
+
@emails_bp.route('/emails/upload', methods=['POST'])
|
| 130 |
+
def upload_email():
|
| 131 |
+
if 'file' not in request.files:
|
| 132 |
+
return jsonify({'error': 'No file uploaded'}), 400
|
| 133 |
+
|
| 134 |
+
f = request.files['file']
|
| 135 |
+
filename = (f.filename or '').lower()
|
| 136 |
+
raw_bytes = f.read()
|
| 137 |
+
|
| 138 |
+
subject = request.form.get('subject', '').strip()
|
| 139 |
+
sender = request.form.get('sender', '').strip()
|
| 140 |
+
|
| 141 |
+
try:
|
| 142 |
+
if filename.endswith('.eml'):
|
| 143 |
+
parsed = parse_eml_bytes(raw_bytes)
|
| 144 |
+
raw_text = parsed['body']
|
| 145 |
+
subject = subject or parsed.get('subject', 'Uploaded .eml')
|
| 146 |
+
sender = sender or parsed.get('sender', 'unknown@upload')
|
| 147 |
+
elif filename.endswith('.txt'):
|
| 148 |
+
raw_text = raw_bytes.decode('utf-8', errors='replace')
|
| 149 |
+
parsed = parse_email(raw_text)
|
| 150 |
+
subject = subject or parsed.get('subject', 'Uploaded .txt')
|
| 151 |
+
sender = sender or parsed.get('sender', 'unknown@upload')
|
| 152 |
+
raw_text = parsed.get('body', raw_text)
|
| 153 |
+
elif filename.endswith('.pdf'):
|
| 154 |
+
raw_text = extract_text_from_attachment('file.pdf', raw_bytes)
|
| 155 |
+
subject = subject or 'Uploaded PDF'
|
| 156 |
+
sender = sender or 'unknown@upload'
|
| 157 |
+
else:
|
| 158 |
+
return jsonify({'error': 'Unsupported file type. Use .eml, .txt, or .pdf'}), 400
|
| 159 |
+
|
| 160 |
+
if not raw_text or not raw_text.strip():
|
| 161 |
+
return jsonify({'error': 'Could not extract text from file'}), 422
|
| 162 |
+
except Exception as exc:
|
| 163 |
+
return jsonify({'error': f'File parse error: {str(exc)}'}), 422
|
| 164 |
+
|
| 165 |
+
session = get_session()
|
| 166 |
+
try:
|
| 167 |
+
result = _process_and_save(raw_text.strip(), subject or 'Uploaded File', sender, session)
|
| 168 |
+
status = 200 if result['is_duplicate'] else 201
|
| 169 |
+
return jsonify(result), status
|
| 170 |
+
except Exception as exc:
|
| 171 |
+
session.rollback()
|
| 172 |
+
return jsonify({'error': str(exc)}), 500
|
| 173 |
+
finally:
|
| 174 |
+
session.close()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# ── GET /api/emails/<id> ──────────────────────────────────────────────────────
|
| 178 |
+
|
| 179 |
+
@emails_bp.route('/emails/<int:email_id>', methods=['GET'])
|
| 180 |
+
def get_email(email_id):
|
| 181 |
+
session = get_session()
|
| 182 |
+
try:
|
| 183 |
+
obj = session.get(Email, email_id)
|
| 184 |
+
if not obj:
|
| 185 |
+
return jsonify({'error': 'Not found'}), 404
|
| 186 |
+
return jsonify(obj.to_dict(include_extracted=True))
|
| 187 |
+
finally:
|
| 188 |
+
session.close()
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# ── DELETE /api/emails/<id> ───────────────────────────────────────────────────
|
| 192 |
+
|
| 193 |
+
@emails_bp.route('/emails/<int:email_id>', methods=['DELETE'])
|
| 194 |
+
def delete_email(email_id):
|
| 195 |
+
session = get_session()
|
| 196 |
+
try:
|
| 197 |
+
obj = session.get(Email, email_id)
|
| 198 |
+
if not obj:
|
| 199 |
+
return jsonify({'error': 'Not found'}), 404
|
| 200 |
+
session.delete(obj)
|
| 201 |
+
session.commit()
|
| 202 |
+
return jsonify({'success': True})
|
| 203 |
+
finally:
|
| 204 |
+
session.close()
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# ── GET /api/emails/duplicates ────────────────────────────────────────────────
|
| 208 |
+
|
| 209 |
+
@emails_bp.route('/emails/duplicates', methods=['GET'])
|
| 210 |
+
def get_duplicates():
|
| 211 |
+
session = get_session()
|
| 212 |
+
try:
|
| 213 |
+
dupes = (
|
| 214 |
+
session.query(Email)
|
| 215 |
+
.filter(Email.is_duplicate == True) # noqa: E712
|
| 216 |
+
.order_by(Email.created_at.desc())
|
| 217 |
+
.all()
|
| 218 |
+
)
|
| 219 |
+
return jsonify({'duplicates': [e.to_dict() for e in dupes], 'total': len(dupes)})
|
| 220 |
+
finally:
|
| 221 |
+
session.close()
|
routes/matching.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import re
|
| 3 |
+
from flask import Blueprint, request, jsonify
|
| 4 |
+
from database.db import get_session
|
| 5 |
+
from database.models import Tonnage, CargoVC, CargoTC
|
| 6 |
+
|
| 7 |
+
matching_bp = Blueprint('matching', __name__)
|
| 8 |
+
|
| 9 |
+
# ── Helpers ───────────────────────────────────────────────────────────────────
|
| 10 |
+
|
| 11 |
+
def _port_score(port_a: str | None, port_b: str | None) -> int:
|
| 12 |
+
if not port_a or not port_b:
|
| 13 |
+
return 0
|
| 14 |
+
a, b = port_a.upper().strip(), port_b.upper().strip()
|
| 15 |
+
if a == b:
|
| 16 |
+
return 50
|
| 17 |
+
# Match on first meaningful token (e.g. city name)
|
| 18 |
+
tok_a = re.split(r'[\s,/]+', a)[0]
|
| 19 |
+
tok_b = re.split(r'[\s,/]+', b)[0]
|
| 20 |
+
if tok_a and tok_b and tok_a == tok_b:
|
| 21 |
+
return 35
|
| 22 |
+
# Match if either contains the other (partial)
|
| 23 |
+
if tok_a in b or tok_b in a:
|
| 24 |
+
return 20
|
| 25 |
+
# Match on last token (country code)
|
| 26 |
+
last_a = re.split(r'[\s,/]+', a)[-1]
|
| 27 |
+
last_b = re.split(r'[\s,/]+', b)[-1]
|
| 28 |
+
if last_a and last_b and last_a == last_b and len(last_a) >= 2:
|
| 29 |
+
return 10
|
| 30 |
+
return 0
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _parse_dwt(size_str: str | None) -> float | None:
|
| 34 |
+
if not size_str:
|
| 35 |
+
return None
|
| 36 |
+
m = re.search(r'([\d,\.]+)', size_str.replace(',', ''))
|
| 37 |
+
if m:
|
| 38 |
+
try:
|
| 39 |
+
val = float(m.group(1))
|
| 40 |
+
# Handle "56K DWT" style
|
| 41 |
+
if 'K' in (size_str or '').upper() and val < 1000:
|
| 42 |
+
val *= 1000
|
| 43 |
+
return val
|
| 44 |
+
except ValueError:
|
| 45 |
+
return None
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _parse_quantity(qty_str: str | None) -> float | None:
|
| 50 |
+
if not qty_str:
|
| 51 |
+
return None
|
| 52 |
+
# e.g. "15,000 - 20,000 MTS" → average
|
| 53 |
+
nums = re.findall(r'[\d,]+', qty_str.replace(',', ''))
|
| 54 |
+
vals = []
|
| 55 |
+
for n in nums:
|
| 56 |
+
try:
|
| 57 |
+
vals.append(float(n))
|
| 58 |
+
except ValueError:
|
| 59 |
+
pass
|
| 60 |
+
if not vals:
|
| 61 |
+
return None
|
| 62 |
+
return sum(vals) / len(vals)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _size_score(dwt_str: str | None, qty_str: str | None) -> int:
|
| 66 |
+
dwt = _parse_dwt(dwt_str)
|
| 67 |
+
qty = _parse_quantity(qty_str)
|
| 68 |
+
if not dwt or not qty or qty == 0:
|
| 69 |
+
return 0
|
| 70 |
+
ratio = dwt / qty
|
| 71 |
+
if 0.6 <= ratio <= 1.6: # ±40% of cargo fills the vessel
|
| 72 |
+
return 20
|
| 73 |
+
if 0.4 <= ratio <= 2.0:
|
| 74 |
+
return 10
|
| 75 |
+
return 0
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _date_score(open_date: str | None, laycan: str | None) -> int:
|
| 79 |
+
"""
|
| 80 |
+
Rough textual date overlap scoring. We extract first year + month mentioned
|
| 81 |
+
in each string and compare proximity in months.
|
| 82 |
+
"""
|
| 83 |
+
if not open_date or not laycan:
|
| 84 |
+
return 0
|
| 85 |
+
|
| 86 |
+
month_map = {
|
| 87 |
+
'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
|
| 88 |
+
'june': 6, 'jul': 7, 'july': 7, 'aug': 8, 'sep': 9, 'oct': 10,
|
| 89 |
+
'nov': 11, 'dec': 12,
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
def _extract_month_year(s: str):
|
| 93 |
+
s_lo = s.lower()
|
| 94 |
+
m = re.search(r'\b(\d{1,2})\b', s)
|
| 95 |
+
day = int(m.group(1)) if m else 1
|
| 96 |
+
for token, num in month_map.items():
|
| 97 |
+
if token in s_lo:
|
| 98 |
+
yr_m = re.search(r'\b(20\d{2})\b', s)
|
| 99 |
+
yr = int(yr_m.group(1)) if yr_m else 2026
|
| 100 |
+
return (yr, num, day)
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
od = _extract_month_year(open_date)
|
| 104 |
+
lc = _extract_month_year(laycan)
|
| 105 |
+
if not od or not lc:
|
| 106 |
+
return 0
|
| 107 |
+
|
| 108 |
+
# Difference in months
|
| 109 |
+
diff = abs((od[0] * 12 + od[1]) - (lc[0] * 12 + lc[1]))
|
| 110 |
+
if diff == 0:
|
| 111 |
+
return 30
|
| 112 |
+
if diff == 1:
|
| 113 |
+
return 20
|
| 114 |
+
if diff == 2:
|
| 115 |
+
return 10
|
| 116 |
+
return 0
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _score_tonnage_vs_vc(t: Tonnage, c: CargoVC) -> int:
|
| 120 |
+
port = _port_score(t.open_port, c.loading_port)
|
| 121 |
+
date = _date_score(t.open_date, c.laycan)
|
| 122 |
+
size = _size_score(t.vessel_size, c.quantity)
|
| 123 |
+
return min(100, port + date + size)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _score_tonnage_vs_tc(t: Tonnage, c: CargoTC) -> int:
|
| 127 |
+
port = _port_score(t.open_port, c.delivery_port)
|
| 128 |
+
date = _date_score(t.open_date, c.laycan)
|
| 129 |
+
size = _size_score(t.vessel_size, None) # TC rarely specifies exact quantity
|
| 130 |
+
return min(100, port + date + size + 10) # +10 base for TC (size less critical)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# ── Routes ────────────────────────────────────────────────────────────────────
|
| 134 |
+
|
| 135 |
+
@matching_bp.route('/matches', methods=['GET'])
|
| 136 |
+
def get_matches():
|
| 137 |
+
"""
|
| 138 |
+
GET /api/matches?mode=tonnage_to_vc&id=<tonnage_id>
|
| 139 |
+
GET /api/matches?mode=tonnage_to_tc&id=<tonnage_id>
|
| 140 |
+
GET /api/matches?mode=vc_to_tonnage&id=<cargo_vc_id>
|
| 141 |
+
GET /api/matches?mode=tc_to_tonnage&id=<cargo_tc_id>
|
| 142 |
+
GET /api/matches?mode=all → full cross-match summary (top-5 per vessel)
|
| 143 |
+
"""
|
| 144 |
+
mode = request.args.get('mode', 'all')
|
| 145 |
+
record_id = request.args.get('id', type=int)
|
| 146 |
+
|
| 147 |
+
session = get_session()
|
| 148 |
+
try:
|
| 149 |
+
if mode == 'tonnage_to_vc':
|
| 150 |
+
if not record_id:
|
| 151 |
+
return jsonify({'error': 'id required'}), 400
|
| 152 |
+
vessel = session.get(Tonnage, record_id)
|
| 153 |
+
if not vessel:
|
| 154 |
+
return jsonify({'error': 'Tonnage record not found'}), 404
|
| 155 |
+
cargos = session.query(CargoVC).all()
|
| 156 |
+
matches = sorted(
|
| 157 |
+
[{'cargo_vc': c.to_dict(), 'score': _score_tonnage_vs_vc(vessel, c)} for c in cargos],
|
| 158 |
+
key=lambda x: x['score'], reverse=True,
|
| 159 |
+
)
|
| 160 |
+
return jsonify({'vessel': vessel.to_dict(), 'matches': matches, 'mode': mode})
|
| 161 |
+
|
| 162 |
+
elif mode == 'tonnage_to_tc':
|
| 163 |
+
if not record_id:
|
| 164 |
+
return jsonify({'error': 'id required'}), 400
|
| 165 |
+
vessel = session.get(Tonnage, record_id)
|
| 166 |
+
if not vessel:
|
| 167 |
+
return jsonify({'error': 'Tonnage record not found'}), 404
|
| 168 |
+
cargos = session.query(CargoTC).all()
|
| 169 |
+
matches = sorted(
|
| 170 |
+
[{'cargo_tc': c.to_dict(), 'score': _score_tonnage_vs_tc(vessel, c)} for c in cargos],
|
| 171 |
+
key=lambda x: x['score'], reverse=True,
|
| 172 |
+
)
|
| 173 |
+
return jsonify({'vessel': vessel.to_dict(), 'matches': matches, 'mode': mode})
|
| 174 |
+
|
| 175 |
+
elif mode == 'vc_to_tonnage':
|
| 176 |
+
if not record_id:
|
| 177 |
+
return jsonify({'error': 'id required'}), 400
|
| 178 |
+
cargo = session.get(CargoVC, record_id)
|
| 179 |
+
if not cargo:
|
| 180 |
+
return jsonify({'error': 'Cargo VC record not found'}), 404
|
| 181 |
+
vessels = session.query(Tonnage).all()
|
| 182 |
+
matches = sorted(
|
| 183 |
+
[{'vessel': v.to_dict(), 'score': _score_tonnage_vs_vc(v, cargo)} for v in vessels],
|
| 184 |
+
key=lambda x: x['score'], reverse=True,
|
| 185 |
+
)
|
| 186 |
+
return jsonify({'cargo_vc': cargo.to_dict(), 'matches': matches, 'mode': mode})
|
| 187 |
+
|
| 188 |
+
elif mode == 'tc_to_tonnage':
|
| 189 |
+
if not record_id:
|
| 190 |
+
return jsonify({'error': 'id required'}), 400
|
| 191 |
+
cargo = session.get(CargoTC, record_id)
|
| 192 |
+
if not cargo:
|
| 193 |
+
return jsonify({'error': 'Cargo TC record not found'}), 404
|
| 194 |
+
vessels = session.query(Tonnage).all()
|
| 195 |
+
matches = sorted(
|
| 196 |
+
[{'vessel': v.to_dict(), 'score': _score_tonnage_vs_tc(v, cargo)} for v in vessels],
|
| 197 |
+
key=lambda x: x['score'], reverse=True,
|
| 198 |
+
)
|
| 199 |
+
return jsonify({'cargo_tc': cargo.to_dict(), 'matches': matches, 'mode': mode})
|
| 200 |
+
|
| 201 |
+
else: # mode == 'all' — top-5 VC matches per vessel
|
| 202 |
+
vessels = session.query(Tonnage).all()
|
| 203 |
+
vc_cargos = session.query(CargoVC).all()
|
| 204 |
+
tc_cargos = session.query(CargoTC).all()
|
| 205 |
+
summary = []
|
| 206 |
+
for v in vessels:
|
| 207 |
+
vc_matches = sorted(
|
| 208 |
+
[{'id': c.id, 'cargo_name': c.cargo_name, 'loading_port': c.loading_port,
|
| 209 |
+
'laycan': c.laycan, 'score': _score_tonnage_vs_vc(v, c)} for c in vc_cargos],
|
| 210 |
+
key=lambda x: x['score'], reverse=True,
|
| 211 |
+
)[:3]
|
| 212 |
+
tc_matches = sorted(
|
| 213 |
+
[{'id': c.id, 'cargo_name': c.cargo_name, 'delivery_port': c.delivery_port,
|
| 214 |
+
'laycan': c.laycan, 'score': _score_tonnage_vs_tc(v, c)} for c in tc_cargos],
|
| 215 |
+
key=lambda x: x['score'], reverse=True,
|
| 216 |
+
)[:3]
|
| 217 |
+
summary.append({
|
| 218 |
+
'vessel': {
|
| 219 |
+
'id': v.id,
|
| 220 |
+
'vessel_name': v.vessel_name,
|
| 221 |
+
'open_port': v.open_port,
|
| 222 |
+
'open_date': v.open_date,
|
| 223 |
+
'vessel_size': v.vessel_size,
|
| 224 |
+
},
|
| 225 |
+
'top_vc': vc_matches,
|
| 226 |
+
'top_tc': tc_matches,
|
| 227 |
+
'best_score': max(
|
| 228 |
+
(m['score'] for m in vc_matches + tc_matches), default=0
|
| 229 |
+
),
|
| 230 |
+
})
|
| 231 |
+
summary.sort(key=lambda x: x['best_score'], reverse=True)
|
| 232 |
+
return jsonify({'summary': summary, 'mode': 'all'})
|
| 233 |
+
|
| 234 |
+
finally:
|
| 235 |
+
session.close()
|
routes/stats.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Blueprint, jsonify, request
|
| 2 |
+
from sqlalchemy import func
|
| 3 |
+
from database.db import get_session
|
| 4 |
+
from database.models import Email, Tonnage, CargoVC, CargoTC
|
| 5 |
+
|
| 6 |
+
stats_bp = Blueprint('stats', __name__)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@stats_bp.route('/stats', methods=['GET'])
|
| 10 |
+
def get_stats():
|
| 11 |
+
session = get_session()
|
| 12 |
+
try:
|
| 13 |
+
total_emails = session.query(func.count(Email.id)).scalar() or 0
|
| 14 |
+
tonnage_count = session.query(func.count(Tonnage.id)).scalar() or 0
|
| 15 |
+
cargo_vc_count = session.query(func.count(CargoVC.id)).scalar() or 0
|
| 16 |
+
cargo_tc_count = session.query(func.count(CargoTC.id)).scalar() or 0
|
| 17 |
+
duplicate_count = session.query(func.count(Email.id)).filter(
|
| 18 |
+
Email.is_duplicate == True # noqa: E712
|
| 19 |
+
).scalar() or 0
|
| 20 |
+
|
| 21 |
+
# Category breakdown
|
| 22 |
+
by_category = (
|
| 23 |
+
session.query(Email.category, func.count(Email.id))
|
| 24 |
+
.group_by(Email.category)
|
| 25 |
+
.all()
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Recent 5 emails
|
| 29 |
+
recent = (
|
| 30 |
+
session.query(Email)
|
| 31 |
+
.order_by(Email.created_at.desc())
|
| 32 |
+
.limit(5)
|
| 33 |
+
.all()
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
return jsonify({
|
| 37 |
+
'total_emails': total_emails,
|
| 38 |
+
'tonnage_records': tonnage_count,
|
| 39 |
+
'cargo_vc_records': cargo_vc_count,
|
| 40 |
+
'cargo_tc_records': cargo_tc_count,
|
| 41 |
+
'duplicate_count': duplicate_count,
|
| 42 |
+
'by_category': {cat: cnt for cat, cnt in by_category},
|
| 43 |
+
'recent': [e.to_dict() for e in recent],
|
| 44 |
+
})
|
| 45 |
+
finally:
|
| 46 |
+
session.close()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@stats_bp.route('/history', methods=['GET'])
|
| 50 |
+
def get_history():
|
| 51 |
+
"""Returns per-sender (broker) activity breakdown."""
|
| 52 |
+
session = get_session()
|
| 53 |
+
try:
|
| 54 |
+
rows = (
|
| 55 |
+
session.query(
|
| 56 |
+
Email.sender,
|
| 57 |
+
func.count(Email.id).label('total'),
|
| 58 |
+
func.max(Email.created_at).label('last_seen'),
|
| 59 |
+
)
|
| 60 |
+
.group_by(Email.sender)
|
| 61 |
+
.order_by(func.count(Email.id).desc())
|
| 62 |
+
.all()
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# Per-sender category breakdown
|
| 66 |
+
cat_rows = (
|
| 67 |
+
session.query(Email.sender, Email.category, func.count(Email.id))
|
| 68 |
+
.group_by(Email.sender, Email.category)
|
| 69 |
+
.all()
|
| 70 |
+
)
|
| 71 |
+
cat_map: dict = {}
|
| 72 |
+
for sender, cat, cnt in cat_rows:
|
| 73 |
+
cat_map.setdefault(sender, {})[cat] = cnt
|
| 74 |
+
|
| 75 |
+
history = []
|
| 76 |
+
for sender, total, last_seen in rows:
|
| 77 |
+
history.append({
|
| 78 |
+
'sender': sender,
|
| 79 |
+
'total': total,
|
| 80 |
+
'last_seen': last_seen.isoformat() if last_seen else None,
|
| 81 |
+
'categories': cat_map.get(sender, {}),
|
| 82 |
+
})
|
| 83 |
+
|
| 84 |
+
return jsonify({'history': history})
|
| 85 |
+
finally:
|
| 86 |
+
session.close()
|
routes/tonnage.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import csv
|
| 2 |
+
import io
|
| 3 |
+
from flask import Blueprint, request, jsonify, Response
|
| 4 |
+
from database.db import get_session
|
| 5 |
+
from database.models import Tonnage
|
| 6 |
+
|
| 7 |
+
tonnage_bp = Blueprint('tonnage', __name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@tonnage_bp.route('/tonnage', methods=['GET'])
|
| 11 |
+
def get_tonnage():
|
| 12 |
+
session = get_session()
|
| 13 |
+
try:
|
| 14 |
+
page = max(1, int(request.args.get('page', 1)))
|
| 15 |
+
per_page = min(100, int(request.args.get('per_page', 20)))
|
| 16 |
+
search = request.args.get('search', '').strip()
|
| 17 |
+
port = request.args.get('port', '').strip()
|
| 18 |
+
|
| 19 |
+
query = session.query(Tonnage)
|
| 20 |
+
if search:
|
| 21 |
+
query = query.filter(
|
| 22 |
+
Tonnage.vessel_name.ilike(f'%{search}%') |
|
| 23 |
+
Tonnage.open_port.ilike(f'%{search}%')
|
| 24 |
+
)
|
| 25 |
+
if port:
|
| 26 |
+
query = query.filter(Tonnage.open_port.ilike(f'%{port}%'))
|
| 27 |
+
|
| 28 |
+
total = query.count()
|
| 29 |
+
records = (
|
| 30 |
+
query.order_by(Tonnage.id.desc())
|
| 31 |
+
.offset((page - 1) * per_page)
|
| 32 |
+
.limit(per_page)
|
| 33 |
+
.all()
|
| 34 |
+
)
|
| 35 |
+
return jsonify({
|
| 36 |
+
'records': [r.to_dict() for r in records],
|
| 37 |
+
'total': total,
|
| 38 |
+
'page': page,
|
| 39 |
+
'per_page': per_page,
|
| 40 |
+
})
|
| 41 |
+
finally:
|
| 42 |
+
session.close()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@tonnage_bp.route('/tonnage/<int:record_id>', methods=['GET'])
|
| 46 |
+
def get_tonnage_record(record_id):
|
| 47 |
+
session = get_session()
|
| 48 |
+
try:
|
| 49 |
+
obj = session.get(Tonnage, record_id)
|
| 50 |
+
if not obj:
|
| 51 |
+
return jsonify({'error': 'Not found'}), 404
|
| 52 |
+
return jsonify(obj.to_dict())
|
| 53 |
+
finally:
|
| 54 |
+
session.close()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@tonnage_bp.route('/tonnage/<int:record_id>', methods=['PATCH'])
|
| 58 |
+
def update_tonnage(record_id):
|
| 59 |
+
session = get_session()
|
| 60 |
+
try:
|
| 61 |
+
obj = session.get(Tonnage, record_id)
|
| 62 |
+
if not obj:
|
| 63 |
+
return jsonify({'error': 'Not found'}), 404
|
| 64 |
+
data = request.get_json(force=True)
|
| 65 |
+
allowed = [
|
| 66 |
+
'vessel_name', 'account_name', 'open_port', 'open_date',
|
| 67 |
+
'vessel_type', 'vessel_size', 'flag', 'built_year', 'class_society',
|
| 68 |
+
'loa', 'beam',
|
| 69 |
+
]
|
| 70 |
+
for field in allowed:
|
| 71 |
+
if field in data:
|
| 72 |
+
setattr(obj, field, data[field])
|
| 73 |
+
session.commit()
|
| 74 |
+
return jsonify(obj.to_dict())
|
| 75 |
+
except Exception as exc:
|
| 76 |
+
session.rollback()
|
| 77 |
+
return jsonify({'error': str(exc)}), 500
|
| 78 |
+
finally:
|
| 79 |
+
session.close()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@tonnage_bp.route('/tonnage/<int:record_id>', methods=['DELETE'])
|
| 83 |
+
def delete_tonnage(record_id):
|
| 84 |
+
session = get_session()
|
| 85 |
+
try:
|
| 86 |
+
obj = session.get(Tonnage, record_id)
|
| 87 |
+
if not obj:
|
| 88 |
+
return jsonify({'error': 'Not found'}), 404
|
| 89 |
+
session.delete(obj)
|
| 90 |
+
session.commit()
|
| 91 |
+
return jsonify({'success': True})
|
| 92 |
+
finally:
|
| 93 |
+
session.close()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@tonnage_bp.route('/tonnage/export', methods=['GET'])
|
| 97 |
+
def export_tonnage_csv():
|
| 98 |
+
session = get_session()
|
| 99 |
+
try:
|
| 100 |
+
records = session.query(Tonnage).order_by(Tonnage.id).all()
|
| 101 |
+
output = io.StringIO()
|
| 102 |
+
fields = ['id', 'email_id', 'vessel_name', 'account_name', 'open_port',
|
| 103 |
+
'open_date', 'vessel_type', 'vessel_size', 'flag', 'built_year',
|
| 104 |
+
'class_society', 'loa', 'beam']
|
| 105 |
+
writer = csv.DictWriter(output, fieldnames=fields, extrasaction='ignore')
|
| 106 |
+
writer.writeheader()
|
| 107 |
+
for r in records:
|
| 108 |
+
writer.writerow(r.to_dict())
|
| 109 |
+
csv_bytes = output.getvalue().encode('utf-8')
|
| 110 |
+
return Response(
|
| 111 |
+
csv_bytes,
|
| 112 |
+
mimetype='text/csv',
|
| 113 |
+
headers={'Content-Disposition': 'attachment; filename=tonnage_export.csv'},
|
| 114 |
+
)
|
| 115 |
+
finally:
|
| 116 |
+
session.close()
|
seed.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
seed.py — Pre-populate the database with the real sample emails provided.
|
| 3 |
+
Run automatically during Render build: `python seed.py`
|
| 4 |
+
Also safe to re-run (skips if DB already has data).
|
| 5 |
+
"""
|
| 6 |
+
import sys, os
|
| 7 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 8 |
+
|
| 9 |
+
from database.db import init_db, get_session
|
| 10 |
+
from database.models import Email
|
| 11 |
+
from classification.classifier import classify
|
| 12 |
+
from extraction.extractor import extract
|
| 13 |
+
|
| 14 |
+
init_db()
|
| 15 |
+
|
| 16 |
+
# ── Sample emails (real data from Prime Maritime & brokers) ──────────────────
|
| 17 |
+
|
| 18 |
+
SAMPLE_EMAILS = [
|
| 19 |
+
{
|
| 20 |
+
"subject": "PRIME MARITIME – OPEN VESSELS PACIFIC – 25 MAY 2026",
|
| 21 |
+
"sender": "chartering@primemaritime.gr",
|
| 22 |
+
"text": """PRIME MARITIME INC. - PIRAEUS
|
| 23 |
+
GOOD DAY
|
| 24 |
+
OUR DIRECT OWS OPEN AS FOLLOWS
|
| 25 |
+
PLS PPSE SUIT
|
| 26 |
+
PACIFIC
|
| 27 |
+
SARONIC CHAMPION (93K – SCRUBBER FITTED / 2011 ) – OPEN VUNG ANG, VIETNAM 08-12 JUNE
|
| 28 |
+
|
| 29 |
+
SARONIC CHAMPION
|
| 30 |
+
LIBERIA FLAG
|
| 31 |
+
BUILT 2011
|
| 32 |
+
CLASS LR
|
| 33 |
+
ABT 93.116 DWT ON ABT 14.90 MTRS SSW
|
| 34 |
+
LOA 229.253 MTRS / BEAM 38.00 MTRS
|
| 35 |
+
GRAIN CAP ABT 110.330 CBM
|
| 36 |
+
7/7 HO/HA – SCRUBBER FITTED
|
| 37 |
+
SPEED / CONS (INCLUDING A/E)
|
| 38 |
+
BALLAST : ABT 12.75 KNOTS ON ABT 30.50 MTS IFO 380 CST
|
| 39 |
+
LADEN : ABT 11.75 KNOTS ON ABT 30.50 MTS IFO 380 CST
|
| 40 |
+
|
| 41 |
+
BEST REGARDS
|
| 42 |
+
GEORGE RACHIOTIS""",
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"subject": "OPEN TONNAGE LIST – PACIFIC & INDIAN OCEAN – 25 MAY 2026",
|
| 46 |
+
"sender": "chartering@chinashipping.com",
|
| 47 |
+
"text": """GOOD DAY,
|
| 48 |
+
PLS PROPOSE FOR THE BELOW TONNAGE LIST:
|
| 49 |
+
|
| 50 |
+
PACIFIC OCEAN
|
| 51 |
+
MV SHENG AN HAI DWT 56564 OPEN XIAMEN, CHINA O/A 2ND JUNE 2026
|
| 52 |
+
MV FENG HUI HAI DWT 63260 OPEN GUANGZHOU, CHINA O/A 6TH JUNE 2026
|
| 53 |
+
MV YUANPING SEA DWT 55646 OPEN MANILA, PHI O/A 3RD JUNE 2026
|
| 54 |
+
MV SHENG DE HAI DWT 56721 OPEN SAMALAJU, MALAYSIA O/A 3RD JUNE 2026
|
| 55 |
+
|
| 56 |
+
INDIAN OCEAN
|
| 57 |
+
MV YIN HUA 1 DWT 46613 OPEN CHITTAGONG, B.DESH O/A 5TH JUNE 2026
|
| 58 |
+
MV BI JIA SHAN DWT 56623 OPEN GWADAR, PAKISTAN O/A 2ND JUNE 2026
|
| 59 |
+
MV YUANNING SEA DWT 55580 OPEN SOHAR, OMAN O/A 30TH MAY 2026
|
| 60 |
+
MV COS ORCHID DWT 55550 OPEN DAR ES SALAAM, TANZANIA O/A 1ST JUNE 2026
|
| 61 |
+
|
| 62 |
+
VSL PARTICULAR:
|
| 63 |
+
MV SHENG AN HAI
|
| 64 |
+
BUILT: 2012
|
| 65 |
+
FLAG: CHINA
|
| 66 |
+
CLASS: CCS
|
| 67 |
+
DWT 56564.4MT ON 12.8M SSW
|
| 68 |
+
LOA 189.99M / BEAM 32.26M
|
| 69 |
+
5 HO/5 HA
|
| 70 |
+
GRAIN 71634.09CBM
|
| 71 |
+
|
| 72 |
+
------------------------------
|
| 73 |
+
|
| 74 |
+
MV FENG HUI HAI
|
| 75 |
+
2017 BLT HONG KONG FLAG SDSTBC
|
| 76 |
+
63260.8 DWT ON 13.30M SSW
|
| 77 |
+
LOA/BEAM 199.9/32.26M
|
| 78 |
+
5 HO/5 HA
|
| 79 |
+
GRAIN/BALE CAPACITY 78771.0/73430CBM
|
| 80 |
+
4 X 30 TON CRANES AND 4 X 12 CMB GRAB
|
| 81 |
+
|
| 82 |
+
------------------------------
|
| 83 |
+
|
| 84 |
+
MV YIN HUA 1
|
| 85 |
+
2013 BLT CHINA FLAG SDBC
|
| 86 |
+
CLASS: CCS
|
| 87 |
+
DWT 46613 MT ON 10.90M SSW
|
| 88 |
+
LOA/BEAM 189.99/32.26
|
| 89 |
+
5 HO/5 HA
|
| 90 |
+
60276.1 CBM GRAIN
|
| 91 |
+
4X36T CRANE
|
| 92 |
+
|
| 93 |
+
------------------------------
|
| 94 |
+
|
| 95 |
+
MV BI JIA SHAN
|
| 96 |
+
HONG KONG FLAG SDBC
|
| 97 |
+
56625 MTDW ON 12.80M SSW
|
| 98 |
+
LOA/BM 189.99/32.26M
|
| 99 |
+
5HO/5HA GRABS 4X12.0 CBM
|
| 100 |
+
CRANE 4X30T
|
| 101 |
+
|
| 102 |
+
------------------------------
|
| 103 |
+
|
| 104 |
+
MV YUANNING SEA
|
| 105 |
+
2004 BLT PANAMA FLAG SDSTBC
|
| 106 |
+
55580DWT ON 12.52M SSW
|
| 107 |
+
LOA/BEAM 189.94/32.26M
|
| 108 |
+
5 HO/5 HA
|
| 109 |
+
4 X 30TON CRANES
|
| 110 |
+
|
| 111 |
+
------------------------------
|
| 112 |
+
|
| 113 |
+
MV COS ORCHID
|
| 114 |
+
DWT 55550MT DRAFT OF 12.5M SSW
|
| 115 |
+
BUILT 2006
|
| 116 |
+
SINGAPORE FLAG SDBC
|
| 117 |
+
LOA/BEAM 189.9/32.26M
|
| 118 |
+
5 HO/HA 4X30T CRANE/GRAB 4X12CUM
|
| 119 |
+
|
| 120 |
+
END""",
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"subject": "PRIME MARITIME – MV TRUE FRIEND – OPEN BEJAIA 1ST JUNE",
|
| 124 |
+
"sender": "chartering@primemaritime.gr",
|
| 125 |
+
"text": """PRIME MARITIME INC. - PIRAEUS
|
| 126 |
+
GOOD DAY
|
| 127 |
+
OUR CLOSE OWS OPEN ASF
|
| 128 |
+
MV TRUE FRIEND/51K/09 - BEJAIA, 1ST JUNE ONW - EX OUR CP
|
| 129 |
+
|
| 130 |
+
MV TRUE FRIEND
|
| 131 |
+
DWT: 51,241
|
| 132 |
+
BUILT: 2009
|
| 133 |
+
FLAG: BARBADOS
|
| 134 |
+
BULK CARRIER
|
| 135 |
+
CLASSIFICATION: NK
|
| 136 |
+
GROSS TONNAGE: 30,655
|
| 137 |
+
LOA: 182.98M
|
| 138 |
+
5/5 HO/HA
|
| 139 |
+
GRAIN: ABT 59,676
|
| 140 |
+
|
| 141 |
+
SPEED/CONSUMPTION:
|
| 142 |
+
ECO SP&CO
|
| 143 |
+
11.0K@21.5 MT/(BALLAST)&0.25MGO
|
| 144 |
+
11.0K@22.0 MT (LADEN)&0.25MGO
|
| 145 |
+
|
| 146 |
+
BEST REGARDS
|
| 147 |
+
KOSTAS SOTIROPOULOS""",
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"subject": "MV BLUE STAR 38K – OPEN GABES TUNISIA 25 MAY",
|
| 151 |
+
"sender": "chartering@blueship.gr",
|
| 152 |
+
"text": """GOOD DAY,
|
| 153 |
+
PLEASED TO HEAR.
|
| 154 |
+
MV BLUE STAR (38K DWT) - OPEN 25 MAY GABES, TUNISIA
|
| 155 |
+
|
| 156 |
+
GEARED SELF-TRIMMING SINGLE DECK BULK CARRIER
|
| 157 |
+
BUILT 2011 SAMHO SHIPBUILDING CO LTD, KOREA
|
| 158 |
+
LIBERIAN FLAG / CLASSED HIGHEST ABS
|
| 159 |
+
37,947 MTDWT ON 10.63M SSW
|
| 160 |
+
LOA 179.98 / BEAM 30.00M
|
| 161 |
+
GT/NT 23.204/11.900
|
| 162 |
+
5 H/H
|
| 163 |
+
CARGO HOLDS CUBIC 48,133.5/46,689.5 CBM (GRAIN/BALE)
|
| 164 |
+
4 X 35MT CRANES
|
| 165 |
+
CO2 FITTED / ELECTRICAL VENTILATED
|
| 166 |
+
BWTS FITTED (ALPHA LAVAL)
|
| 167 |
+
|
| 168 |
+
SPEED AND CONSUMPTION:
|
| 169 |
+
ABT 11.0 KN ON ABT 17.0 (L)/ ABT 11.5 ON ABT 16.0 (B) MT IFO
|
| 170 |
+
PORT CONSUMPTION: 2.5MT IDLE / 5MT (WORKING CRANES) IFO""",
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"subject": "OPEN TONNAGE ECSA + W.AFRICA + CONTI/MED – 21 MAY 2026",
|
| 174 |
+
"sender": "chartering@haiship.cn",
|
| 175 |
+
"text": """GOOD DAY,
|
| 176 |
+
PLS PROPOSE FOR THE BELOW TONNAGE LIST:
|
| 177 |
+
|
| 178 |
+
ECSA + W. AFRICA
|
| 179 |
+
MV DE SHENG HAI DWT 38,821.5 MT OPEN MUCURIPE, BRAZIL O/A 24-25 MAY 2026
|
| 180 |
+
|
| 181 |
+
CONTI+MED
|
| 182 |
+
M/V AN DING HAI DWT 38,800 MT - OPEN CASABLANCA O/A 28-30 MAY 2026
|
| 183 |
+
|
| 184 |
+
VSL PARTICULAR:
|
| 185 |
+
MV AN DING HAI
|
| 186 |
+
2017 BLT HONG KONG FLAG SDBC
|
| 187 |
+
38800.9 DWT ON 10.5M SSW
|
| 188 |
+
GRAIN/BALE CAPACITY 50873.7/49572.6 M3
|
| 189 |
+
LOA/BEAM 179.95/32.00M
|
| 190 |
+
5 HO/5 HA
|
| 191 |
+
GEAR: 4 X 30 TON CRANES, 4 X 10 CBM RADIO REMOTE CONTROL GRAB""",
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"subject": "VC CARGO – KOH SI CHANG TO KANDLA/CHENNAI – MID JULY",
|
| 195 |
+
"sender": "chartering@broker1.com",
|
| 196 |
+
"text": """22 MAY 2026
|
| 197 |
+
ATTN CHARTERING DESK!
|
| 198 |
+
DEAR SIR
|
| 199 |
+
GOOD DAY
|
| 200 |
+
PLEASE OFFER FIRM FOR FOLL FULLY FIRM CARGO
|
| 201 |
+
|
| 202 |
+
15,000 - 20,000 MTS 10PCT MOLOCHOPT
|
| 203 |
+
LOAD PORT: KOH SI CHANG, THAILAND
|
| 204 |
+
DISCHARGE PORT: KANDLA + CHENNAI
|
| 205 |
+
LOAD RATE: 1,000 MTS PWWD SSHEX
|
| 206 |
+
DISCHARGE RATE: 1500 MTS PWWD SSHEX
|
| 207 |
+
LAYCAN: MID JULY 2026
|
| 208 |
+
COM: 3.75 PCT TTL""",
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"subject": "CARGO OFFERS – JEDDAH/BILBAO, IRON SLAG, UREA",
|
| 212 |
+
"sender": "lidomar@lidomar.ro",
|
| 213 |
+
"text": """MCD LIDOMAR
|
| 214 |
+
Att. Chartering Desk
|
| 215 |
+
|
| 216 |
+
Jeddah / Bilbao
|
| 217 |
+
20 000 mt HRC max 28,5 mt
|
| 218 |
+
FIOS
|
| 219 |
+
4000 mt FHINC / CQD disch
|
| 220 |
+
25 June - 5 July try later
|
| 221 |
+
3.75% here
|
| 222 |
+
|
| 223 |
+
+++++++++++++++++++++++++++++++++++++++++++++++++
|
| 224 |
+
|
| 225 |
+
PLS OFFER FIRM FOR FOLL OUR CLOSE AND DIR CHRTRS
|
| 226 |
+
|
| 227 |
+
20-30,000 mts iron slag in bulk
|
| 228 |
+
LP: Bushehr
|
| 229 |
+
DP: Doha
|
| 230 |
+
10000/12000
|
| 231 |
+
25-30 July
|
| 232 |
+
3.75% TTL
|
| 233 |
+
|
| 234 |
+
+++++++++++++++++++++++++++++++++++++++++++++++++
|
| 235 |
+
|
| 236 |
+
Cargo: 30,000 mts of Urea in bulk
|
| 237 |
+
POL: BIK
|
| 238 |
+
POD: Iskenderun or Durban
|
| 239 |
+
5000/5000
|
| 240 |
+
LAYCAN: 16-20 July
|
| 241 |
+
COMM: 1.25% TTL""",
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"subject": "TC CARGO REQUIREMENTS – CHINA/NOPAC, SEASIA, WORLDWIDE",
|
| 245 |
+
"sender": "chartering@daian.com",
|
| 246 |
+
"text": """GOOD DAY,
|
| 247 |
+
PLEASED TO HEAR.
|
| 248 |
+
|
| 249 |
+
CHINA / NOPAC
|
| 250 |
+
ACC DAI AN OCEAN SHIPPING COMPANY LIMITED
|
| 251 |
+
DELIVERY TM VANCOUVER
|
| 252 |
+
LC 10-17 JUNE
|
| 253 |
+
SMX-UMX, PREF UMX
|
| 254 |
+
1 TCT WITH GRAINS
|
| 255 |
+
REDELIVERY CHITTAGONG
|
| 256 |
+
3.75 ADDCOM PUS
|
| 257 |
+
|
| 258 |
+
----------------------------------------------
|
| 259 |
+
|
| 260 |
+
SEASIA
|
| 261 |
+
ACC DAI AN OCEAN SHIPPING COMPANY LIMITED
|
| 262 |
+
SMX-UMX MAX 20 YRS.
|
| 263 |
+
DELY TO MAKE SANGATTA (NEAR TO TJ BARA), E KALI OF INDONESIA.
|
| 264 |
+
29-2ND JUN
|
| 265 |
+
1 TCT WITH CLINKER TO BDESH.
|
| 266 |
+
DURATION ABT 30 DAYS WOG.
|
| 267 |
+
3.75PCT ADDOM PUS
|
| 268 |
+
|
| 269 |
+
----------------------------------------------
|
| 270 |
+
|
| 271 |
+
WORLDWIDE
|
| 272 |
+
ACC DAI AN OCEAN SHIPPING COMPANY LIMITED
|
| 273 |
+
SUPRA/ULTRA DELY WW
|
| 274 |
+
FULL MAY
|
| 275 |
+
1-3 YEARS TRY SHORT PERIOD
|
| 276 |
+
FLAT OR INDEX BOTH WORKABLE
|
| 277 |
+
3.75 ADDCOM PUS""",
|
| 278 |
+
},
|
| 279 |
+
{
|
| 280 |
+
"subject": "TC REQUIREMENTS – A/C SEA SCHIFFE – ECI DELIVERY",
|
| 281 |
+
"sender": "switson87@seaschiffe.com",
|
| 282 |
+
"text": """Please provide suitable, rated vessels for our following firm requirements.
|
| 283 |
+
|
| 284 |
+
* A/C SeaSchiffe
|
| 285 |
+
* 1 TCT with Steels/Gens/lawfuls
|
| 286 |
+
* 22k dwt upto HMAX
|
| 287 |
+
* Delivery: ECI
|
| 288 |
+
* Laycan: 15-18 July
|
| 289 |
+
* Redel: Med via GOA transit
|
| 290 |
+
* Duration: abt 35-40 days wog
|
| 291 |
+
* 3.75% Adc
|
| 292 |
+
|
| 293 |
+
----------------------------------------------
|
| 294 |
+
|
| 295 |
+
* A/C SeaSchiffe
|
| 296 |
+
* 1 TCT with Steels/Gens/lawfuls
|
| 297 |
+
* 33k dwt upto HMAX
|
| 298 |
+
* Delivery: ECI
|
| 299 |
+
* Laycan: 21-23 July
|
| 300 |
+
* Redel: ARAG via COGH transit
|
| 301 |
+
* Duration: abt 50-55 days wog
|
| 302 |
+
* 3.75% Adc
|
| 303 |
+
|
| 304 |
+
We look forward to hearing from you.
|
| 305 |
+
Best regards,
|
| 306 |
+
Steve
|
| 307 |
+
Sea Schiffe DMCC""",
|
| 308 |
+
},
|
| 309 |
+
]
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def seed():
|
| 313 |
+
session = get_session()
|
| 314 |
+
try:
|
| 315 |
+
count = session.query(Email).count()
|
| 316 |
+
if count > 0:
|
| 317 |
+
print(f"[ShipSeg] Database already has {count} emails. Skipping seed.")
|
| 318 |
+
return
|
| 319 |
+
|
| 320 |
+
print("[ShipSeg] Seeding database with sample shipping emails...")
|
| 321 |
+
for sample in SAMPLE_EMAILS:
|
| 322 |
+
text = sample['text']
|
| 323 |
+
category, confidence = classify(text)
|
| 324 |
+
email_obj = Email(
|
| 325 |
+
subject=sample['subject'],
|
| 326 |
+
sender=sample['sender'],
|
| 327 |
+
raw_body=text,
|
| 328 |
+
category=category,
|
| 329 |
+
confidence=confidence,
|
| 330 |
+
)
|
| 331 |
+
session.add(email_obj)
|
| 332 |
+
session.flush()
|
| 333 |
+
extract(category, text, email_obj.id, session)
|
| 334 |
+
print(f" + [{category.upper():10s}] {sample['subject'][:60]}")
|
| 335 |
+
|
| 336 |
+
session.commit()
|
| 337 |
+
print(f"[ShipSeg] Seeded {len(SAMPLE_EMAILS)} emails successfully.")
|
| 338 |
+
except Exception as exc:
|
| 339 |
+
session.rollback()
|
| 340 |
+
print(f"[ShipSeg] Seed error: {exc}")
|
| 341 |
+
raise
|
| 342 |
+
finally:
|
| 343 |
+
session.close()
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
if __name__ == '__main__':
|
| 347 |
+
seed()
|
static/css/styles.css
ADDED
|
@@ -0,0 +1,1043 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* ═══════════════════════════════════════════════════════════════
|
| 2 |
+
ShipSeg — Premium Dark Theme Design System
|
| 3 |
+
═══════════════════════════════════════════════════════════════ */
|
| 4 |
+
|
| 5 |
+
:root {
|
| 6 |
+
/* Palette */
|
| 7 |
+
--bg-base: #090d16;
|
| 8 |
+
--bg-surface: #0d1421;
|
| 9 |
+
--bg-card: #111927;
|
| 10 |
+
--bg-card-hover: #162030;
|
| 11 |
+
--bg-input: #0d1421;
|
| 12 |
+
--border: #1a2540;
|
| 13 |
+
--border-light: #1e2d4a;
|
| 14 |
+
|
| 15 |
+
/* Brand */
|
| 16 |
+
--gold: #f0b429;
|
| 17 |
+
--gold-dim: rgba(240, 180, 41, 0.12);
|
| 18 |
+
--gold-glow: rgba(240, 180, 41, 0.25);
|
| 19 |
+
--blue: #3d8bff;
|
| 20 |
+
--blue-dim: rgba(61, 139, 255, 0.12);
|
| 21 |
+
--green: #22c55e;
|
| 22 |
+
--green-dim: rgba(34, 197, 94, 0.12);
|
| 23 |
+
--red: #ef4444;
|
| 24 |
+
--red-dim: rgba(239, 68, 68, 0.12);
|
| 25 |
+
--purple: #a855f7;
|
| 26 |
+
--purple-dim: rgba(168, 85, 247, 0.12);
|
| 27 |
+
|
| 28 |
+
/* Text */
|
| 29 |
+
--text-primary: #e2e8f4;
|
| 30 |
+
--text-secondary:#8b9ab8;
|
| 31 |
+
--text-muted: #4a5878;
|
| 32 |
+
--text-label: #6b7fa8;
|
| 33 |
+
|
| 34 |
+
/* Category colors */
|
| 35 |
+
--cat-tonnage: #f0b429;
|
| 36 |
+
--cat-vc: #3d8bff;
|
| 37 |
+
--cat-tc: #a855f7;
|
| 38 |
+
--cat-unknown: #64748b;
|
| 39 |
+
|
| 40 |
+
/* Shadows */
|
| 41 |
+
--shadow-sm: 0 1px 3px rgba(0,0,0,.4);
|
| 42 |
+
--shadow-md: 0 4px 20px rgba(0,0,0,.5);
|
| 43 |
+
--shadow-lg: 0 8px 40px rgba(0,0,0,.6);
|
| 44 |
+
--shadow-gold: 0 0 30px rgba(240, 180, 41, 0.15);
|
| 45 |
+
|
| 46 |
+
/* Sidebar */
|
| 47 |
+
--sidebar-w: 240px;
|
| 48 |
+
--topbar-h: 64px;
|
| 49 |
+
|
| 50 |
+
/* Transitions */
|
| 51 |
+
--t-fast: 150ms ease;
|
| 52 |
+
--t-med: 250ms ease;
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
/* ── Reset ─────────────────────────────────────────────────────── */
|
| 56 |
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
| 57 |
+
html { scroll-behavior: smooth; }
|
| 58 |
+
body {
|
| 59 |
+
font-family: 'Inter', system-ui, sans-serif;
|
| 60 |
+
background: var(--bg-base);
|
| 61 |
+
color: var(--text-primary);
|
| 62 |
+
min-height: 100vh;
|
| 63 |
+
display: flex;
|
| 64 |
+
overflow-x: hidden;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
/* ── Sidebar ───────────────────────────────────────────────────── */
|
| 68 |
+
.sidebar {
|
| 69 |
+
width: var(--sidebar-w);
|
| 70 |
+
min-height: 100vh;
|
| 71 |
+
background: var(--bg-surface);
|
| 72 |
+
border-right: 1px solid var(--border);
|
| 73 |
+
display: flex;
|
| 74 |
+
flex-direction: column;
|
| 75 |
+
position: fixed;
|
| 76 |
+
left: 0; top: 0; bottom: 0;
|
| 77 |
+
z-index: 100;
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
.sidebar-logo {
|
| 81 |
+
display: flex;
|
| 82 |
+
align-items: center;
|
| 83 |
+
gap: 10px;
|
| 84 |
+
padding: 20px 20px;
|
| 85 |
+
border-bottom: 1px solid var(--border);
|
| 86 |
+
height: var(--topbar-h);
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
.logo-icon {
|
| 90 |
+
font-size: 22px;
|
| 91 |
+
filter: drop-shadow(0 0 8px var(--gold));
|
| 92 |
+
animation: pulse-glow 3s ease-in-out infinite;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
@keyframes pulse-glow {
|
| 96 |
+
0%, 100% { filter: drop-shadow(0 0 6px var(--gold)); }
|
| 97 |
+
50% { filter: drop-shadow(0 0 16px var(--gold)); }
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
.logo-text {
|
| 101 |
+
font-size: 20px;
|
| 102 |
+
font-weight: 800;
|
| 103 |
+
background: linear-gradient(135deg, var(--gold), #ffd97d);
|
| 104 |
+
-webkit-background-clip: text;
|
| 105 |
+
-webkit-text-fill-color: transparent;
|
| 106 |
+
background-clip: text;
|
| 107 |
+
letter-spacing: -0.5px;
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
.sidebar-nav {
|
| 111 |
+
flex: 1;
|
| 112 |
+
padding: 16px 12px;
|
| 113 |
+
display: flex;
|
| 114 |
+
flex-direction: column;
|
| 115 |
+
gap: 4px;
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
.nav-section-label {
|
| 119 |
+
font-size: 10px;
|
| 120 |
+
font-weight: 600;
|
| 121 |
+
letter-spacing: 1.2px;
|
| 122 |
+
color: var(--text-muted);
|
| 123 |
+
padding: 12px 8px 6px;
|
| 124 |
+
text-transform: uppercase;
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
.nav-item {
|
| 128 |
+
display: flex;
|
| 129 |
+
align-items: center;
|
| 130 |
+
gap: 10px;
|
| 131 |
+
padding: 10px 12px;
|
| 132 |
+
border-radius: 8px;
|
| 133 |
+
text-decoration: none;
|
| 134 |
+
color: var(--text-secondary);
|
| 135 |
+
font-size: 14px;
|
| 136 |
+
font-weight: 500;
|
| 137 |
+
transition: all var(--t-fast);
|
| 138 |
+
position: relative;
|
| 139 |
+
cursor: pointer;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
.nav-item:hover {
|
| 143 |
+
background: var(--bg-card);
|
| 144 |
+
color: var(--text-primary);
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
.nav-item.active {
|
| 148 |
+
background: var(--gold-dim);
|
| 149 |
+
color: var(--gold);
|
| 150 |
+
border: 1px solid rgba(240, 180, 41, 0.2);
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
.nav-item.active .nav-icon {
|
| 154 |
+
filter: drop-shadow(0 0 4px var(--gold));
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
.nav-icon { font-size: 16px; width: 20px; text-align: center; }
|
| 158 |
+
.nav-label { flex: 1; }
|
| 159 |
+
|
| 160 |
+
.nav-badge {
|
| 161 |
+
background: var(--border-light);
|
| 162 |
+
color: var(--text-secondary);
|
| 163 |
+
font-size: 11px;
|
| 164 |
+
font-weight: 600;
|
| 165 |
+
padding: 1px 7px;
|
| 166 |
+
border-radius: 20px;
|
| 167 |
+
min-width: 22px;
|
| 168 |
+
text-align: center;
|
| 169 |
+
}
|
| 170 |
+
.nav-badge.tonnage { background: var(--gold-dim); color: var(--gold); }
|
| 171 |
+
.nav-badge.vc { background: var(--blue-dim); color: var(--blue); }
|
| 172 |
+
.nav-badge.tc { background: var(--purple-dim); color: var(--purple); }
|
| 173 |
+
|
| 174 |
+
.sidebar-footer {
|
| 175 |
+
padding: 16px 20px;
|
| 176 |
+
border-top: 1px solid var(--border);
|
| 177 |
+
}
|
| 178 |
+
.sidebar-footer-info {
|
| 179 |
+
display: flex;
|
| 180 |
+
align-items: center;
|
| 181 |
+
gap: 8px;
|
| 182 |
+
font-size: 12px;
|
| 183 |
+
color: var(--green);
|
| 184 |
+
font-weight: 500;
|
| 185 |
+
}
|
| 186 |
+
.footer-dot {
|
| 187 |
+
width: 7px; height: 7px;
|
| 188 |
+
background: var(--green);
|
| 189 |
+
border-radius: 50%;
|
| 190 |
+
box-shadow: 0 0 6px var(--green);
|
| 191 |
+
animation: blink 2s ease infinite;
|
| 192 |
+
}
|
| 193 |
+
@keyframes blink { 0%,100%{opacity:1} 50%{opacity:.3} }
|
| 194 |
+
.sidebar-footer-sub {
|
| 195 |
+
font-size: 10px;
|
| 196 |
+
color: var(--text-muted);
|
| 197 |
+
margin-top: 4px;
|
| 198 |
+
letter-spacing: 0.2px;
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
/* ── Main layout ───────────────────────────────────────────────── */
|
| 202 |
+
.main-wrapper {
|
| 203 |
+
margin-left: var(--sidebar-w);
|
| 204 |
+
flex: 1;
|
| 205 |
+
display: flex;
|
| 206 |
+
flex-direction: column;
|
| 207 |
+
min-height: 100vh;
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
/* ── Topbar ────────────────────────────────────────────────────── */
|
| 211 |
+
.topbar {
|
| 212 |
+
height: var(--topbar-h);
|
| 213 |
+
background: var(--bg-surface);
|
| 214 |
+
border-bottom: 1px solid var(--border);
|
| 215 |
+
display: flex;
|
| 216 |
+
align-items: center;
|
| 217 |
+
justify-content: space-between;
|
| 218 |
+
padding: 0 28px;
|
| 219 |
+
position: sticky;
|
| 220 |
+
top: 0;
|
| 221 |
+
z-index: 50;
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
.topbar-left { display: flex; flex-direction: column; gap: 2px; }
|
| 225 |
+
.page-title { font-size: 18px; font-weight: 700; letter-spacing: -0.3px; }
|
| 226 |
+
.breadcrumb { font-size: 12px; color: var(--text-muted); }
|
| 227 |
+
|
| 228 |
+
/* ── Buttons ───────────────────────────────────────────────────── */
|
| 229 |
+
.btn {
|
| 230 |
+
display: inline-flex;
|
| 231 |
+
align-items: center;
|
| 232 |
+
gap: 7px;
|
| 233 |
+
padding: 9px 18px;
|
| 234 |
+
border-radius: 8px;
|
| 235 |
+
font-size: 14px;
|
| 236 |
+
font-weight: 600;
|
| 237 |
+
border: none;
|
| 238 |
+
cursor: pointer;
|
| 239 |
+
transition: all var(--t-fast);
|
| 240 |
+
text-decoration: none;
|
| 241 |
+
white-space: nowrap;
|
| 242 |
+
}
|
| 243 |
+
.btn-icon { font-size: 18px; line-height: 1; }
|
| 244 |
+
|
| 245 |
+
.btn-primary {
|
| 246 |
+
background: linear-gradient(135deg, var(--gold), #d99b00);
|
| 247 |
+
color: #000;
|
| 248 |
+
box-shadow: 0 0 20px var(--gold-glow);
|
| 249 |
+
}
|
| 250 |
+
.btn-primary:hover {
|
| 251 |
+
background: linear-gradient(135deg, #ffc533, var(--gold));
|
| 252 |
+
box-shadow: 0 0 28px rgba(240, 180, 41, 0.4);
|
| 253 |
+
transform: translateY(-1px);
|
| 254 |
+
}
|
| 255 |
+
.btn-primary:active { transform: translateY(0); }
|
| 256 |
+
|
| 257 |
+
.btn-ghost {
|
| 258 |
+
background: transparent;
|
| 259 |
+
color: var(--text-secondary);
|
| 260 |
+
border: 1px solid var(--border-light);
|
| 261 |
+
}
|
| 262 |
+
.btn-ghost:hover { background: var(--bg-card); color: var(--text-primary); }
|
| 263 |
+
|
| 264 |
+
.btn-danger {
|
| 265 |
+
background: var(--red-dim);
|
| 266 |
+
color: var(--red);
|
| 267 |
+
border: 1px solid rgba(239,68,68,.2);
|
| 268 |
+
}
|
| 269 |
+
.btn-danger:hover { background: rgba(239,68,68,.2); }
|
| 270 |
+
|
| 271 |
+
.btn-sm { padding: 6px 12px; font-size: 12px; }
|
| 272 |
+
.btn-icon-only { padding: 7px; width: 32px; height: 32px; justify-content: center; }
|
| 273 |
+
|
| 274 |
+
/* ── Content ───────────────────────────────────────────────────── */
|
| 275 |
+
.content {
|
| 276 |
+
flex: 1;
|
| 277 |
+
padding: 28px;
|
| 278 |
+
max-width: 1400px;
|
| 279 |
+
width: 100%;
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
/* ── Stat Cards ────────────────────────────────────────────────── */
|
| 283 |
+
.stats-grid {
|
| 284 |
+
display: grid;
|
| 285 |
+
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
| 286 |
+
gap: 16px;
|
| 287 |
+
margin-bottom: 28px;
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
.stat-card {
|
| 291 |
+
background: var(--bg-card);
|
| 292 |
+
border: 1px solid var(--border);
|
| 293 |
+
border-radius: 12px;
|
| 294 |
+
padding: 20px 22px;
|
| 295 |
+
transition: all var(--t-med);
|
| 296 |
+
position: relative;
|
| 297 |
+
overflow: hidden;
|
| 298 |
+
}
|
| 299 |
+
.stat-card::before {
|
| 300 |
+
content: '';
|
| 301 |
+
position: absolute;
|
| 302 |
+
inset: 0;
|
| 303 |
+
opacity: 0;
|
| 304 |
+
transition: opacity var(--t-med);
|
| 305 |
+
}
|
| 306 |
+
.stat-card:hover { transform: translateY(-2px); box-shadow: var(--shadow-md); }
|
| 307 |
+
.stat-card:hover::before { opacity: 1; }
|
| 308 |
+
|
| 309 |
+
.stat-card.gold::before { background: linear-gradient(135deg, var(--gold-dim), transparent); }
|
| 310 |
+
.stat-card.blue::before { background: linear-gradient(135deg, var(--blue-dim), transparent); }
|
| 311 |
+
.stat-card.green::before { background: linear-gradient(135deg, var(--green-dim), transparent); }
|
| 312 |
+
.stat-card.purple::before{ background: linear-gradient(135deg, var(--purple-dim), transparent); }
|
| 313 |
+
|
| 314 |
+
.stat-card.gold { border-top: 2px solid var(--gold); }
|
| 315 |
+
.stat-card.blue { border-top: 2px solid var(--blue); }
|
| 316 |
+
.stat-card.green { border-top: 2px solid var(--green); }
|
| 317 |
+
.stat-card.purple{ border-top: 2px solid var(--purple); }
|
| 318 |
+
|
| 319 |
+
.stat-header {
|
| 320 |
+
display: flex;
|
| 321 |
+
align-items: center;
|
| 322 |
+
justify-content: space-between;
|
| 323 |
+
margin-bottom: 14px;
|
| 324 |
+
}
|
| 325 |
+
.stat-label { font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.8px; color: var(--text-label); }
|
| 326 |
+
.stat-icon { font-size: 20px; opacity: .7; }
|
| 327 |
+
.stat-number {
|
| 328 |
+
font-size: 36px;
|
| 329 |
+
font-weight: 800;
|
| 330 |
+
letter-spacing: -1px;
|
| 331 |
+
line-height: 1;
|
| 332 |
+
margin-bottom: 4px;
|
| 333 |
+
}
|
| 334 |
+
.stat-card.gold .stat-number { color: var(--gold); }
|
| 335 |
+
.stat-card.blue .stat-number { color: var(--blue); }
|
| 336 |
+
.stat-card.green .stat-number { color: var(--green); }
|
| 337 |
+
.stat-card.purple .stat-number { color: var(--purple); }
|
| 338 |
+
.stat-sub { font-size: 12px; color: var(--text-muted); }
|
| 339 |
+
|
| 340 |
+
/* ── Section Headers ─────────────────────────────────────────��─── */
|
| 341 |
+
.section-header {
|
| 342 |
+
display: flex;
|
| 343 |
+
align-items: center;
|
| 344 |
+
justify-content: space-between;
|
| 345 |
+
margin-bottom: 16px;
|
| 346 |
+
}
|
| 347 |
+
.section-title {
|
| 348 |
+
font-size: 16px;
|
| 349 |
+
font-weight: 700;
|
| 350 |
+
color: var(--text-primary);
|
| 351 |
+
display: flex;
|
| 352 |
+
align-items: center;
|
| 353 |
+
gap: 8px;
|
| 354 |
+
}
|
| 355 |
+
.section-title::before {
|
| 356 |
+
content: '';
|
| 357 |
+
display: block;
|
| 358 |
+
width: 3px; height: 18px;
|
| 359 |
+
background: var(--gold);
|
| 360 |
+
border-radius: 2px;
|
| 361 |
+
}
|
| 362 |
+
.section-count { font-size: 12px; color: var(--text-muted); font-weight: 400; }
|
| 363 |
+
|
| 364 |
+
/* ── Tables ────────────────────────────────────────────────────── */
|
| 365 |
+
.table-card {
|
| 366 |
+
background: var(--bg-card);
|
| 367 |
+
border: 1px solid var(--border);
|
| 368 |
+
border-radius: 12px;
|
| 369 |
+
overflow: hidden;
|
| 370 |
+
margin-bottom: 24px;
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
.table-toolbar {
|
| 374 |
+
display: flex;
|
| 375 |
+
align-items: center;
|
| 376 |
+
gap: 12px;
|
| 377 |
+
padding: 16px 20px;
|
| 378 |
+
border-bottom: 1px solid var(--border);
|
| 379 |
+
flex-wrap: wrap;
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
.search-box {
|
| 383 |
+
display: flex;
|
| 384 |
+
align-items: center;
|
| 385 |
+
gap: 8px;
|
| 386 |
+
background: var(--bg-input);
|
| 387 |
+
border: 1px solid var(--border-light);
|
| 388 |
+
border-radius: 8px;
|
| 389 |
+
padding: 8px 12px;
|
| 390 |
+
flex: 1;
|
| 391 |
+
min-width: 180px;
|
| 392 |
+
max-width: 320px;
|
| 393 |
+
transition: border-color var(--t-fast);
|
| 394 |
+
}
|
| 395 |
+
.search-box:focus-within { border-color: var(--gold); box-shadow: 0 0 0 2px var(--gold-dim); }
|
| 396 |
+
.search-icon { color: var(--text-muted); font-size: 14px; }
|
| 397 |
+
.search-input {
|
| 398 |
+
background: none;
|
| 399 |
+
border: none;
|
| 400 |
+
outline: none;
|
| 401 |
+
color: var(--text-primary);
|
| 402 |
+
font-size: 14px;
|
| 403 |
+
width: 100%;
|
| 404 |
+
font-family: inherit;
|
| 405 |
+
}
|
| 406 |
+
.search-input::placeholder { color: var(--text-muted); }
|
| 407 |
+
|
| 408 |
+
.table-wrapper { overflow-x: auto; }
|
| 409 |
+
|
| 410 |
+
table {
|
| 411 |
+
width: 100%;
|
| 412 |
+
border-collapse: collapse;
|
| 413 |
+
font-size: 13.5px;
|
| 414 |
+
}
|
| 415 |
+
thead th {
|
| 416 |
+
background: var(--bg-surface);
|
| 417 |
+
color: var(--text-label);
|
| 418 |
+
font-size: 11px;
|
| 419 |
+
font-weight: 600;
|
| 420 |
+
text-transform: uppercase;
|
| 421 |
+
letter-spacing: 0.8px;
|
| 422 |
+
padding: 12px 16px;
|
| 423 |
+
text-align: left;
|
| 424 |
+
white-space: nowrap;
|
| 425 |
+
border-bottom: 1px solid var(--border);
|
| 426 |
+
}
|
| 427 |
+
tbody tr {
|
| 428 |
+
border-bottom: 1px solid var(--border);
|
| 429 |
+
transition: background var(--t-fast);
|
| 430 |
+
}
|
| 431 |
+
tbody tr:last-child { border-bottom: none; }
|
| 432 |
+
tbody tr:hover { background: var(--bg-card-hover); }
|
| 433 |
+
tbody td {
|
| 434 |
+
padding: 13px 16px;
|
| 435 |
+
color: var(--text-primary);
|
| 436 |
+
vertical-align: middle;
|
| 437 |
+
}
|
| 438 |
+
.td-muted { color: var(--text-muted); font-size: 12px; }
|
| 439 |
+
.td-mono { font-family: 'JetBrains Mono', monospace; font-size: 12px; }
|
| 440 |
+
|
| 441 |
+
.empty-state {
|
| 442 |
+
text-align: center;
|
| 443 |
+
padding: 60px 20px;
|
| 444 |
+
color: var(--text-muted);
|
| 445 |
+
}
|
| 446 |
+
.empty-icon { font-size: 40px; margin-bottom: 12px; opacity: .5; }
|
| 447 |
+
.empty-text { font-size: 15px; font-weight: 500; margin-bottom: 6px; color: var(--text-secondary); }
|
| 448 |
+
.empty-sub { font-size: 13px; }
|
| 449 |
+
|
| 450 |
+
/* ── Badges ────────────────────────────────────────────────────── */
|
| 451 |
+
.badge {
|
| 452 |
+
display: inline-flex;
|
| 453 |
+
align-items: center;
|
| 454 |
+
gap: 5px;
|
| 455 |
+
padding: 3px 10px;
|
| 456 |
+
border-radius: 20px;
|
| 457 |
+
font-size: 11px;
|
| 458 |
+
font-weight: 600;
|
| 459 |
+
text-transform: uppercase;
|
| 460 |
+
letter-spacing: 0.5px;
|
| 461 |
+
white-space: nowrap;
|
| 462 |
+
}
|
| 463 |
+
.badge-tonnage { background: var(--gold-dim); color: var(--gold); border: 1px solid rgba(240,180,41,.25); }
|
| 464 |
+
.badge-cargo_vc{ background: var(--blue-dim); color: var(--blue); border: 1px solid rgba(61,139,255,.25); }
|
| 465 |
+
.badge-cargo_tc{ background: var(--purple-dim); color: var(--purple); border: 1px solid rgba(168,85,247,.25); }
|
| 466 |
+
.badge-unknown { background: var(--bg-surface); color: var(--text-muted); border: 1px solid var(--border); }
|
| 467 |
+
|
| 468 |
+
/* ── Category Bar ──────────────────────────────────────────────── */
|
| 469 |
+
.cat-bar { display: flex; gap: 12px; margin-bottom: 28px; flex-wrap: wrap; }
|
| 470 |
+
.cat-pill {
|
| 471 |
+
display: flex;
|
| 472 |
+
align-items: center;
|
| 473 |
+
gap: 8px;
|
| 474 |
+
background: var(--bg-card);
|
| 475 |
+
border: 1px solid var(--border);
|
| 476 |
+
border-radius: 30px;
|
| 477 |
+
padding: 8px 16px;
|
| 478 |
+
cursor: pointer;
|
| 479 |
+
transition: all var(--t-fast);
|
| 480 |
+
font-size: 13px;
|
| 481 |
+
font-weight: 500;
|
| 482 |
+
color: var(--text-secondary);
|
| 483 |
+
}
|
| 484 |
+
.cat-pill:hover { border-color: var(--border-light); color: var(--text-primary); }
|
| 485 |
+
.cat-pill.active-tonnage { border-color: var(--gold); color: var(--gold); background: var(--gold-dim); }
|
| 486 |
+
.cat-pill.active-vc { border-color: var(--blue); color: var(--blue); background: var(--blue-dim); }
|
| 487 |
+
.cat-pill.active-tc { border-color: var(--purple); color: var(--purple); background: var(--purple-dim); }
|
| 488 |
+
.cat-pill.active-all { border-color: var(--text-secondary); color: var(--text-primary); }
|
| 489 |
+
.cat-pill-dot { width: 8px; height: 8px; border-radius: 50%; }
|
| 490 |
+
|
| 491 |
+
/* ── Modal ─────────────────────────────────────────────────────── */
|
| 492 |
+
.modal-overlay {
|
| 493 |
+
display: none;
|
| 494 |
+
position: fixed;
|
| 495 |
+
inset: 0;
|
| 496 |
+
background: rgba(0,0,0,.7);
|
| 497 |
+
backdrop-filter: blur(4px);
|
| 498 |
+
z-index: 999;
|
| 499 |
+
align-items: center;
|
| 500 |
+
justify-content: center;
|
| 501 |
+
padding: 20px;
|
| 502 |
+
}
|
| 503 |
+
.modal-overlay.open { display: flex; animation: fadeIn 0.2s ease; }
|
| 504 |
+
|
| 505 |
+
@keyframes fadeIn { from{opacity:0} to{opacity:1} }
|
| 506 |
+
@keyframes slideUp { from{opacity:0;transform:translateY(24px)} to{opacity:1;transform:translateY(0)} }
|
| 507 |
+
|
| 508 |
+
.modal {
|
| 509 |
+
background: var(--bg-surface);
|
| 510 |
+
border: 1px solid var(--border-light);
|
| 511 |
+
border-radius: 16px;
|
| 512 |
+
width: 100%;
|
| 513 |
+
max-width: 680px;
|
| 514 |
+
max-height: 90vh;
|
| 515 |
+
overflow-y: auto;
|
| 516 |
+
box-shadow: var(--shadow-lg), var(--shadow-gold);
|
| 517 |
+
animation: slideUp 0.25s ease;
|
| 518 |
+
}
|
| 519 |
+
.modal-header {
|
| 520 |
+
display: flex;
|
| 521 |
+
align-items: center;
|
| 522 |
+
justify-content: space-between;
|
| 523 |
+
padding: 20px 24px;
|
| 524 |
+
border-bottom: 1px solid var(--border);
|
| 525 |
+
}
|
| 526 |
+
.modal-title { font-size: 18px; font-weight: 700; }
|
| 527 |
+
.modal-close {
|
| 528 |
+
width: 32px; height: 32px;
|
| 529 |
+
background: var(--bg-card);
|
| 530 |
+
border: 1px solid var(--border);
|
| 531 |
+
border-radius: 6px;
|
| 532 |
+
color: var(--text-secondary);
|
| 533 |
+
cursor: pointer;
|
| 534 |
+
font-size: 14px;
|
| 535 |
+
display: flex;
|
| 536 |
+
align-items: center;
|
| 537 |
+
justify-content: center;
|
| 538 |
+
transition: all var(--t-fast);
|
| 539 |
+
}
|
| 540 |
+
.modal-close:hover { background: var(--bg-card-hover); color: var(--text-primary); }
|
| 541 |
+
.modal-body { padding: 24px; }
|
| 542 |
+
.modal-footer {
|
| 543 |
+
display: flex;
|
| 544 |
+
justify-content: flex-end;
|
| 545 |
+
gap: 10px;
|
| 546 |
+
padding: 16px 24px;
|
| 547 |
+
border-top: 1px solid var(--border);
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
/* ── Forms ─────────────────────────────────────────────────────── */
|
| 551 |
+
.form-group { margin-bottom: 16px; }
|
| 552 |
+
.form-label { display: block; font-size: 13px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px; }
|
| 553 |
+
.required { color: var(--gold); }
|
| 554 |
+
.form-input, .form-textarea {
|
| 555 |
+
width: 100%;
|
| 556 |
+
background: var(--bg-input);
|
| 557 |
+
border: 1px solid var(--border-light);
|
| 558 |
+
border-radius: 8px;
|
| 559 |
+
padding: 10px 14px;
|
| 560 |
+
color: var(--text-primary);
|
| 561 |
+
font-size: 14px;
|
| 562 |
+
font-family: inherit;
|
| 563 |
+
outline: none;
|
| 564 |
+
transition: border-color var(--t-fast);
|
| 565 |
+
resize: vertical;
|
| 566 |
+
}
|
| 567 |
+
.form-input:focus, .form-textarea:focus {
|
| 568 |
+
border-color: var(--gold);
|
| 569 |
+
box-shadow: 0 0 0 2px var(--gold-dim);
|
| 570 |
+
}
|
| 571 |
+
.form-textarea { font-family: 'JetBrains Mono', monospace; font-size: 12.5px; line-height: 1.6; }
|
| 572 |
+
|
| 573 |
+
/* ── Classifier preview ─────────────────────────────────────────── */
|
| 574 |
+
.classifier-preview {
|
| 575 |
+
background: var(--bg-card);
|
| 576 |
+
border: 1px solid var(--border-light);
|
| 577 |
+
border-radius: 8px;
|
| 578 |
+
padding: 14px 16px;
|
| 579 |
+
display: flex;
|
| 580 |
+
align-items: center;
|
| 581 |
+
gap: 12px;
|
| 582 |
+
margin-top: 4px;
|
| 583 |
+
}
|
| 584 |
+
.preview-label { font-size: 12px; color: var(--text-muted); font-weight: 500; }
|
| 585 |
+
.preview-badge { font-size: 13px; font-weight: 700; }
|
| 586 |
+
.preview-confidence { font-size: 12px; color: var(--text-muted); margin-left: auto; }
|
| 587 |
+
|
| 588 |
+
/* ── Pagination ────────────────────────────────────────────────── */
|
| 589 |
+
.pagination {
|
| 590 |
+
display: flex;
|
| 591 |
+
align-items: center;
|
| 592 |
+
justify-content: space-between;
|
| 593 |
+
padding: 14px 20px;
|
| 594 |
+
border-top: 1px solid var(--border);
|
| 595 |
+
font-size: 13px;
|
| 596 |
+
color: var(--text-muted);
|
| 597 |
+
}
|
| 598 |
+
.pagination-controls { display: flex; gap: 6px; }
|
| 599 |
+
.page-btn {
|
| 600 |
+
width: 30px; height: 30px;
|
| 601 |
+
background: var(--bg-surface);
|
| 602 |
+
border: 1px solid var(--border);
|
| 603 |
+
border-radius: 6px;
|
| 604 |
+
color: var(--text-secondary);
|
| 605 |
+
cursor: pointer;
|
| 606 |
+
font-size: 13px;
|
| 607 |
+
display: flex;
|
| 608 |
+
align-items: center;
|
| 609 |
+
justify-content: center;
|
| 610 |
+
transition: all var(--t-fast);
|
| 611 |
+
}
|
| 612 |
+
.page-btn:hover:not(:disabled) { background: var(--bg-card); color: var(--text-primary); }
|
| 613 |
+
.page-btn:disabled { opacity: .3; cursor: not-allowed; }
|
| 614 |
+
.page-btn.active { background: var(--gold-dim); color: var(--gold); border-color: var(--gold); }
|
| 615 |
+
|
| 616 |
+
/* ── Toasts ────────────────────────────────────────────────────── */
|
| 617 |
+
.toast-container {
|
| 618 |
+
position: fixed;
|
| 619 |
+
bottom: 24px;
|
| 620 |
+
right: 24px;
|
| 621 |
+
display: flex;
|
| 622 |
+
flex-direction: column;
|
| 623 |
+
gap: 8px;
|
| 624 |
+
z-index: 9999;
|
| 625 |
+
}
|
| 626 |
+
.toast {
|
| 627 |
+
display: flex;
|
| 628 |
+
align-items: center;
|
| 629 |
+
gap: 10px;
|
| 630 |
+
background: var(--bg-card);
|
| 631 |
+
border: 1px solid var(--border-light);
|
| 632 |
+
border-radius: 10px;
|
| 633 |
+
padding: 12px 16px;
|
| 634 |
+
font-size: 13.5px;
|
| 635 |
+
font-weight: 500;
|
| 636 |
+
box-shadow: var(--shadow-lg);
|
| 637 |
+
min-width: 280px;
|
| 638 |
+
max-width: 380px;
|
| 639 |
+
animation: slideIn 0.3s ease;
|
| 640 |
+
}
|
| 641 |
+
@keyframes slideIn {
|
| 642 |
+
from { opacity: 0; transform: translateX(30px); }
|
| 643 |
+
to { opacity: 1; transform: translateX(0); }
|
| 644 |
+
}
|
| 645 |
+
.toast.success { border-left: 3px solid var(--green); }
|
| 646 |
+
.toast.error { border-left: 3px solid var(--red); }
|
| 647 |
+
.toast.info { border-left: 3px solid var(--blue); }
|
| 648 |
+
.toast-icon { font-size: 18px; }
|
| 649 |
+
.toast-msg { flex: 1; }
|
| 650 |
+
|
| 651 |
+
/* ── Loading Spinner ─────────────────────────────���─────────────── */
|
| 652 |
+
.loading-spinner {
|
| 653 |
+
display: flex;
|
| 654 |
+
flex-direction: column;
|
| 655 |
+
align-items: center;
|
| 656 |
+
justify-content: center;
|
| 657 |
+
height: 300px;
|
| 658 |
+
gap: 16px;
|
| 659 |
+
color: var(--text-muted);
|
| 660 |
+
}
|
| 661 |
+
.spinner {
|
| 662 |
+
width: 40px; height: 40px;
|
| 663 |
+
border: 3px solid var(--border);
|
| 664 |
+
border-top-color: var(--gold);
|
| 665 |
+
border-radius: 50%;
|
| 666 |
+
animation: spin 0.8s linear infinite;
|
| 667 |
+
}
|
| 668 |
+
@keyframes spin { to { transform: rotate(360deg); } }
|
| 669 |
+
|
| 670 |
+
/* ── Chart Bar ─────────────────────────────────────────────────── */
|
| 671 |
+
.chart-bar-row {
|
| 672 |
+
display: flex;
|
| 673 |
+
align-items: center;
|
| 674 |
+
gap: 12px;
|
| 675 |
+
margin-bottom: 14px;
|
| 676 |
+
}
|
| 677 |
+
.chart-bar-label { width: 90px; font-size: 12px; color: var(--text-secondary); text-align: right; white-space: nowrap; }
|
| 678 |
+
.chart-bar-track { flex: 1; height: 8px; background: var(--bg-surface); border-radius: 4px; overflow: hidden; }
|
| 679 |
+
.chart-bar-fill { height: 100%; border-radius: 4px; transition: width 0.8s cubic-bezier(.4,0,.2,1); }
|
| 680 |
+
.chart-bar-fill.gold { background: linear-gradient(90deg, var(--gold), #ffd970); }
|
| 681 |
+
.chart-bar-fill.blue { background: linear-gradient(90deg, var(--blue), #79b3ff); }
|
| 682 |
+
.chart-bar-fill.purple { background: linear-gradient(90deg, var(--purple), #c480ff); }
|
| 683 |
+
.chart-bar-count { font-size: 12px; color: var(--text-muted); width: 30px; }
|
| 684 |
+
|
| 685 |
+
/* ── Vessel / Cargo Detail expand row ─────────────────────────── */
|
| 686 |
+
.detail-row { background: var(--bg-surface) !important; }
|
| 687 |
+
.detail-cell { padding: 0 !important; }
|
| 688 |
+
.detail-panel {
|
| 689 |
+
display: grid;
|
| 690 |
+
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
| 691 |
+
gap: 12px;
|
| 692 |
+
padding: 16px 20px;
|
| 693 |
+
border-top: 1px solid var(--border);
|
| 694 |
+
}
|
| 695 |
+
.detail-item label { font-size: 10px; text-transform: uppercase; letter-spacing: .8px; color: var(--text-muted); display: block; margin-bottom: 3px; }
|
| 696 |
+
.detail-item span { font-size: 13px; color: var(--text-primary); font-weight: 500; }
|
| 697 |
+
.detail-item span.mono { font-family: 'JetBrains Mono', monospace; font-size: 12px; }
|
| 698 |
+
|
| 699 |
+
/* ── Confidence pill ───────────────────────────────────────────── */
|
| 700 |
+
.conf-pill {
|
| 701 |
+
font-size: 11px;
|
| 702 |
+
font-family: 'JetBrains Mono', monospace;
|
| 703 |
+
padding: 2px 7px;
|
| 704 |
+
border-radius: 4px;
|
| 705 |
+
background: var(--bg-surface);
|
| 706 |
+
color: var(--text-muted);
|
| 707 |
+
border: 1px solid var(--border);
|
| 708 |
+
}
|
| 709 |
+
|
| 710 |
+
/* ── Action buttons in table ───────────────────────────────────── */
|
| 711 |
+
.action-cell { display: flex; gap: 6px; align-items: center; }
|
| 712 |
+
|
| 713 |
+
/* ── Grid helpers ──────────────────────────────────────────────── */
|
| 714 |
+
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
|
| 715 |
+
.three-col { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; }
|
| 716 |
+
@media (max-width: 900px) { .two-col, .three-col { grid-template-columns: 1fr; } }
|
| 717 |
+
|
| 718 |
+
/* ── Card ──────────────────────────────────────────────────────── */
|
| 719 |
+
.card {
|
| 720 |
+
background: var(--bg-card);
|
| 721 |
+
border: 1px solid var(--border);
|
| 722 |
+
border-radius: 12px;
|
| 723 |
+
padding: 20px;
|
| 724 |
+
margin-bottom: 20px;
|
| 725 |
+
}
|
| 726 |
+
.card-title { font-size: 14px; font-weight: 700; margin-bottom: 16px; color: var(--text-primary); }
|
| 727 |
+
|
| 728 |
+
/* ── Scrollbar ─────────────────────────────────────────────────── */
|
| 729 |
+
::-webkit-scrollbar { width: 5px; height: 5px; }
|
| 730 |
+
::-webkit-scrollbar-track { background: var(--bg-base); }
|
| 731 |
+
::-webkit-scrollbar-thumb { background: var(--border-light); border-radius: 3px; }
|
| 732 |
+
::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
|
| 733 |
+
|
| 734 |
+
/* ── Animations ────────────────────────────────────────────────── */
|
| 735 |
+
.fade-in { animation: fadeIn 0.3s ease; }
|
| 736 |
+
|
| 737 |
+
/* ── Modal Tabs ────────────────────────────────────────────────── */
|
| 738 |
+
.modal-tabs {
|
| 739 |
+
display: flex;
|
| 740 |
+
gap: 0;
|
| 741 |
+
border-bottom: 1px solid var(--border);
|
| 742 |
+
padding: 0 24px;
|
| 743 |
+
}
|
| 744 |
+
.modal-tab {
|
| 745 |
+
background: none;
|
| 746 |
+
border: none;
|
| 747 |
+
border-bottom: 2px solid transparent;
|
| 748 |
+
color: var(--text-muted);
|
| 749 |
+
font-size: 13px;
|
| 750 |
+
font-weight: 600;
|
| 751 |
+
padding: 12px 16px;
|
| 752 |
+
cursor: pointer;
|
| 753 |
+
transition: all var(--t-fast);
|
| 754 |
+
margin-bottom: -1px;
|
| 755 |
+
font-family: inherit;
|
| 756 |
+
}
|
| 757 |
+
.modal-tab:hover { color: var(--text-primary); }
|
| 758 |
+
.modal-tab.active {
|
| 759 |
+
color: var(--gold);
|
| 760 |
+
border-bottom-color: var(--gold);
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
/* ── File Drop Zone ────────────────────────────────────────────── */
|
| 764 |
+
.file-drop-zone {
|
| 765 |
+
border: 2px dashed var(--border-light);
|
| 766 |
+
border-radius: 10px;
|
| 767 |
+
padding: 36px 24px;
|
| 768 |
+
text-align: center;
|
| 769 |
+
cursor: pointer;
|
| 770 |
+
transition: all var(--t-fast);
|
| 771 |
+
background: var(--bg-input);
|
| 772 |
+
}
|
| 773 |
+
.file-drop-zone:hover,
|
| 774 |
+
.file-drop-zone.drag-over {
|
| 775 |
+
border-color: var(--gold);
|
| 776 |
+
background: var(--gold-dim);
|
| 777 |
+
}
|
| 778 |
+
.file-drop-icon { font-size: 32px; margin-bottom: 10px; opacity: .6; }
|
| 779 |
+
.file-drop-text { font-size: 14px; font-weight: 500; color: var(--text-secondary); margin-bottom: 4px; }
|
| 780 |
+
.file-drop-sub { font-size: 12px; color: var(--text-muted); }
|
| 781 |
+
.file-drop-name {
|
| 782 |
+
margin-top: 12px;
|
| 783 |
+
font-size: 13px;
|
| 784 |
+
color: var(--gold);
|
| 785 |
+
font-weight: 500;
|
| 786 |
+
}
|
| 787 |
+
|
| 788 |
+
/* ── Duplicate Warning ─────────────────────────────────────────── */
|
| 789 |
+
.duplicate-warning {
|
| 790 |
+
background: rgba(240,180,41,.08);
|
| 791 |
+
border: 1px solid rgba(240,180,41,.3);
|
| 792 |
+
border-radius: 8px;
|
| 793 |
+
padding: 10px 14px;
|
| 794 |
+
font-size: 13px;
|
| 795 |
+
color: var(--gold);
|
| 796 |
+
margin-top: 12px;
|
| 797 |
+
}
|
| 798 |
+
|
| 799 |
+
/* ── Warning Toast ─────────────────────────────────────────────── */
|
| 800 |
+
.toast.warning { border-left: 3px solid var(--gold); }
|
| 801 |
+
|
| 802 |
+
/* ── Topbar buttons cluster ────────────────────────────────────── */
|
| 803 |
+
.topbar-right { display: flex; gap: 10px; align-items: center; }
|
| 804 |
+
|
| 805 |
+
/* ── Matching Engine Layout ────────────────────────────────────── */
|
| 806 |
+
.matching-layout {
|
| 807 |
+
grid-template-columns: 340px 1fr;
|
| 808 |
+
align-items: start;
|
| 809 |
+
}
|
| 810 |
+
@media (max-width: 1000px) { .matching-layout { grid-template-columns: 1fr; } }
|
| 811 |
+
|
| 812 |
+
.vessel-list {
|
| 813 |
+
max-height: calc(100vh - 180px);
|
| 814 |
+
overflow-y: auto;
|
| 815 |
+
padding: 8px;
|
| 816 |
+
display: flex;
|
| 817 |
+
flex-direction: column;
|
| 818 |
+
gap: 6px;
|
| 819 |
+
}
|
| 820 |
+
|
| 821 |
+
.vessel-card {
|
| 822 |
+
background: var(--bg-surface);
|
| 823 |
+
border: 1px solid var(--border);
|
| 824 |
+
border-radius: 10px;
|
| 825 |
+
padding: 12px 14px;
|
| 826 |
+
cursor: pointer;
|
| 827 |
+
transition: all var(--t-fast);
|
| 828 |
+
}
|
| 829 |
+
.vessel-card:hover {
|
| 830 |
+
border-color: var(--border-light);
|
| 831 |
+
background: var(--bg-card-hover);
|
| 832 |
+
transform: translateX(3px);
|
| 833 |
+
}
|
| 834 |
+
.vessel-card.selected {
|
| 835 |
+
border-color: var(--gold);
|
| 836 |
+
background: var(--gold-dim);
|
| 837 |
+
}
|
| 838 |
+
.vessel-card-name {
|
| 839 |
+
font-size: 14px;
|
| 840 |
+
font-weight: 600;
|
| 841 |
+
color: var(--gold);
|
| 842 |
+
margin-bottom: 5px;
|
| 843 |
+
}
|
| 844 |
+
.vessel-card-meta {
|
| 845 |
+
font-size: 12px;
|
| 846 |
+
color: var(--text-muted);
|
| 847 |
+
display: flex;
|
| 848 |
+
flex-wrap: wrap;
|
| 849 |
+
gap: 5px;
|
| 850 |
+
align-items: center;
|
| 851 |
+
}
|
| 852 |
+
|
| 853 |
+
/* Mode toggle */
|
| 854 |
+
.mode-toggle {
|
| 855 |
+
display: flex;
|
| 856 |
+
background: var(--bg-surface);
|
| 857 |
+
border: 1px solid var(--border);
|
| 858 |
+
border-radius: 8px;
|
| 859 |
+
overflow: hidden;
|
| 860 |
+
}
|
| 861 |
+
.mode-btn {
|
| 862 |
+
background: none;
|
| 863 |
+
border: none;
|
| 864 |
+
color: var(--text-muted);
|
| 865 |
+
font-size: 12px;
|
| 866 |
+
font-weight: 600;
|
| 867 |
+
padding: 6px 14px;
|
| 868 |
+
cursor: pointer;
|
| 869 |
+
transition: all var(--t-fast);
|
| 870 |
+
font-family: inherit;
|
| 871 |
+
}
|
| 872 |
+
.mode-btn.active {
|
| 873 |
+
background: var(--gold-dim);
|
| 874 |
+
color: var(--gold);
|
| 875 |
+
}
|
| 876 |
+
|
| 877 |
+
/* Match cards */
|
| 878 |
+
.match-list {
|
| 879 |
+
display: flex;
|
| 880 |
+
flex-direction: column;
|
| 881 |
+
gap: 10px;
|
| 882 |
+
}
|
| 883 |
+
.match-card {
|
| 884 |
+
background: var(--bg-card);
|
| 885 |
+
border: 1px solid var(--border);
|
| 886 |
+
border-radius: 12px;
|
| 887 |
+
padding: 16px 18px;
|
| 888 |
+
transition: all var(--t-fast);
|
| 889 |
+
}
|
| 890 |
+
.match-card:hover { border-color: var(--border-light); transform: translateY(-1px); }
|
| 891 |
+
|
| 892 |
+
.match-card-top {
|
| 893 |
+
display: flex;
|
| 894 |
+
justify-content: space-between;
|
| 895 |
+
align-items: flex-start;
|
| 896 |
+
gap: 12px;
|
| 897 |
+
margin-bottom: 12px;
|
| 898 |
+
}
|
| 899 |
+
.match-cargo-name { font-size: 15px; font-weight: 700; color: var(--text-primary); margin-bottom: 5px; }
|
| 900 |
+
.match-ports { font-size: 13px; margin-bottom: 4px; }
|
| 901 |
+
.match-meta { font-size: 12px; }
|
| 902 |
+
|
| 903 |
+
.match-score-block { text-align: center; flex-shrink: 0; }
|
| 904 |
+
.match-score {
|
| 905 |
+
font-size: 28px;
|
| 906 |
+
font-weight: 800;
|
| 907 |
+
font-family: 'JetBrains Mono', monospace;
|
| 908 |
+
line-height: 1;
|
| 909 |
+
margin-bottom: 4px;
|
| 910 |
+
}
|
| 911 |
+
.match-score-label { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; }
|
| 912 |
+
|
| 913 |
+
.score-high { color: var(--green); }
|
| 914 |
+
.score-mid { color: var(--gold); }
|
| 915 |
+
.score-low { color: var(--text-muted); }
|
| 916 |
+
|
| 917 |
+
.match-score-bar-track {
|
| 918 |
+
height: 4px;
|
| 919 |
+
background: var(--bg-surface);
|
| 920 |
+
border-radius: 2px;
|
| 921 |
+
overflow: hidden;
|
| 922 |
+
}
|
| 923 |
+
.match-score-bar {
|
| 924 |
+
height: 100%;
|
| 925 |
+
border-radius: 2px;
|
| 926 |
+
transition: width 0.8s cubic-bezier(.4,0,.2,1);
|
| 927 |
+
}
|
| 928 |
+
.match-score-bar.score-high { background: linear-gradient(90deg, var(--green), #86efac); }
|
| 929 |
+
.match-score-bar.score-mid { background: linear-gradient(90deg, var(--gold), #fcd34d); }
|
| 930 |
+
.match-score-bar.score-low { background: var(--border-light); }
|
| 931 |
+
|
| 932 |
+
/* ── Split Modal Layout ────────────────────────────────────────── */
|
| 933 |
+
.modal-split {
|
| 934 |
+
display: grid;
|
| 935 |
+
grid-template-columns: 1fr 1fr;
|
| 936 |
+
gap: 20px;
|
| 937 |
+
max-height: 55vh;
|
| 938 |
+
}
|
| 939 |
+
@media (max-width: 768px) {
|
| 940 |
+
.modal-split {
|
| 941 |
+
grid-template-columns: 1fr;
|
| 942 |
+
max-height: 80vh;
|
| 943 |
+
}
|
| 944 |
+
}
|
| 945 |
+
|
| 946 |
+
.modal-split-left, .modal-split-right {
|
| 947 |
+
display: flex;
|
| 948 |
+
flex-direction: column;
|
| 949 |
+
height: 100%;
|
| 950 |
+
min-height: 0; /* allows scrolling inside flex item */
|
| 951 |
+
}
|
| 952 |
+
|
| 953 |
+
.modal-split-header {
|
| 954 |
+
font-size: 11px;
|
| 955 |
+
font-weight: 700;
|
| 956 |
+
text-transform: uppercase;
|
| 957 |
+
color: var(--text-label);
|
| 958 |
+
letter-spacing: 0.8px;
|
| 959 |
+
margin-bottom: 8px;
|
| 960 |
+
}
|
| 961 |
+
|
| 962 |
+
.modal-raw-body-pre {
|
| 963 |
+
background: var(--bg-base);
|
| 964 |
+
border: 1px solid var(--border);
|
| 965 |
+
border-radius: 8px;
|
| 966 |
+
padding: 16px;
|
| 967 |
+
font-size: 12px;
|
| 968 |
+
font-family: 'JetBrains Mono', monospace;
|
| 969 |
+
overflow-y: auto;
|
| 970 |
+
color: var(--text-secondary);
|
| 971 |
+
white-space: pre-wrap;
|
| 972 |
+
line-height: 1.6;
|
| 973 |
+
flex: 1;
|
| 974 |
+
}
|
| 975 |
+
|
| 976 |
+
.modal-parsed-panel {
|
| 977 |
+
background: var(--bg-base);
|
| 978 |
+
border: 1px solid var(--border);
|
| 979 |
+
border-radius: 8px;
|
| 980 |
+
padding: 16px;
|
| 981 |
+
overflow-y: auto;
|
| 982 |
+
flex: 1;
|
| 983 |
+
display: flex;
|
| 984 |
+
flex-direction: column;
|
| 985 |
+
gap: 12px;
|
| 986 |
+
}
|
| 987 |
+
|
| 988 |
+
.parsed-record-card {
|
| 989 |
+
background: var(--bg-surface);
|
| 990 |
+
border: 1px solid var(--border-light);
|
| 991 |
+
border-radius: 8px;
|
| 992 |
+
padding: 14px 16px;
|
| 993 |
+
display: flex;
|
| 994 |
+
flex-direction: column;
|
| 995 |
+
gap: 8px;
|
| 996 |
+
}
|
| 997 |
+
|
| 998 |
+
.parsed-record-title {
|
| 999 |
+
font-size: 13px;
|
| 1000 |
+
font-weight: 700;
|
| 1001 |
+
color: var(--gold);
|
| 1002 |
+
}
|
| 1003 |
+
|
| 1004 |
+
.parsed-record-card.cargo_vc .parsed-record-title {
|
| 1005 |
+
color: var(--blue);
|
| 1006 |
+
}
|
| 1007 |
+
|
| 1008 |
+
.parsed-record-card.cargo_tc .parsed-record-title {
|
| 1009 |
+
color: var(--purple);
|
| 1010 |
+
}
|
| 1011 |
+
|
| 1012 |
+
.parsed-field-grid {
|
| 1013 |
+
display: grid;
|
| 1014 |
+
grid-template-columns: repeat(2, 1fr);
|
| 1015 |
+
gap: 8px 12px;
|
| 1016 |
+
}
|
| 1017 |
+
|
| 1018 |
+
.parsed-field {
|
| 1019 |
+
display: flex;
|
| 1020 |
+
flex-direction: column;
|
| 1021 |
+
gap: 2px;
|
| 1022 |
+
}
|
| 1023 |
+
|
| 1024 |
+
.parsed-field label {
|
| 1025 |
+
font-size: 9px;
|
| 1026 |
+
text-transform: uppercase;
|
| 1027 |
+
color: var(--text-muted);
|
| 1028 |
+
font-weight: 600;
|
| 1029 |
+
letter-spacing: 0.5px;
|
| 1030 |
+
}
|
| 1031 |
+
|
| 1032 |
+
.parsed-field span {
|
| 1033 |
+
font-size: 12.5px;
|
| 1034 |
+
font-weight: 500;
|
| 1035 |
+
color: var(--text-primary);
|
| 1036 |
+
}
|
| 1037 |
+
|
| 1038 |
+
.parsed-field span.mono {
|
| 1039 |
+
font-family: 'JetBrains Mono', monospace;
|
| 1040 |
+
font-size: 11px;
|
| 1041 |
+
}
|
| 1042 |
+
|
| 1043 |
+
|
static/index.html
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 6 |
+
<title>ShipSeg — Shipping Email Intelligence Platform</title>
|
| 7 |
+
<meta name="description" content="Automated shipping email classification and data extraction for Tonnage, Voyage Charter, and Time Charter emails." />
|
| 8 |
+
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
| 9 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
| 10 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
|
| 11 |
+
<link rel="stylesheet" href="/css/styles.css" />
|
| 12 |
+
</head>
|
| 13 |
+
<body>
|
| 14 |
+
<!-- Sidebar -->
|
| 15 |
+
<aside class="sidebar" id="sidebar">
|
| 16 |
+
<div class="sidebar-logo">
|
| 17 |
+
<div class="logo-icon">⚓</div>
|
| 18 |
+
<span class="logo-text">ShipSeg</span>
|
| 19 |
+
</div>
|
| 20 |
+
|
| 21 |
+
<nav class="sidebar-nav">
|
| 22 |
+
<a href="#dashboard" class="nav-item active" id="nav-dashboard" data-view="dashboard">
|
| 23 |
+
<span class="nav-icon">◈</span>
|
| 24 |
+
<span class="nav-label">Dashboard</span>
|
| 25 |
+
</a>
|
| 26 |
+
<a href="#inbox" class="nav-item" id="nav-inbox" data-view="inbox">
|
| 27 |
+
<span class="nav-icon">✉</span>
|
| 28 |
+
<span class="nav-label">Inbox</span>
|
| 29 |
+
<span class="nav-badge" id="badge-inbox">0</span>
|
| 30 |
+
</a>
|
| 31 |
+
|
| 32 |
+
<div class="nav-section-label">EXTRACTED DATA</div>
|
| 33 |
+
<a href="#tonnage" class="nav-item" id="nav-tonnage" data-view="tonnage">
|
| 34 |
+
<span class="nav-icon">🚢</span>
|
| 35 |
+
<span class="nav-label">Tonnage</span>
|
| 36 |
+
<span class="nav-badge tonnage" id="badge-tonnage">0</span>
|
| 37 |
+
</a>
|
| 38 |
+
<a href="#cargo-vc" class="nav-item" id="nav-cargo-vc" data-view="cargo-vc">
|
| 39 |
+
<span class="nav-icon">📦</span>
|
| 40 |
+
<span class="nav-label">Cargo VC</span>
|
| 41 |
+
<span class="nav-badge vc" id="badge-vc">0</span>
|
| 42 |
+
</a>
|
| 43 |
+
<a href="#cargo-tc" class="nav-item" id="nav-cargo-tc" data-view="cargo-tc">
|
| 44 |
+
<span class="nav-icon">⏱</span>
|
| 45 |
+
<span class="nav-label">Cargo TC</span>
|
| 46 |
+
<span class="nav-badge tc" id="badge-tc">0</span>
|
| 47 |
+
</a>
|
| 48 |
+
|
| 49 |
+
<div class="nav-section-label">INTELLIGENCE</div>
|
| 50 |
+
<a href="#matching" class="nav-item" id="nav-matching" data-view="matching">
|
| 51 |
+
<span class="nav-icon">🔗</span>
|
| 52 |
+
<span class="nav-label">Matches</span>
|
| 53 |
+
</a>
|
| 54 |
+
<a href="#history" class="nav-item" id="nav-history" data-view="history">
|
| 55 |
+
<span class="nav-icon">📅</span>
|
| 56 |
+
<span class="nav-label">History</span>
|
| 57 |
+
</a>
|
| 58 |
+
</nav>
|
| 59 |
+
|
| 60 |
+
<div class="sidebar-footer">
|
| 61 |
+
<div class="sidebar-footer-info">
|
| 62 |
+
<div class="footer-dot"></div>
|
| 63 |
+
<span>System Online</span>
|
| 64 |
+
</div>
|
| 65 |
+
<div class="sidebar-footer-sub">No LLM APIs · Local ML Only</div>
|
| 66 |
+
</div>
|
| 67 |
+
</aside>
|
| 68 |
+
|
| 69 |
+
<!-- Main -->
|
| 70 |
+
<div class="main-wrapper">
|
| 71 |
+
<!-- Top bar -->
|
| 72 |
+
<header class="topbar">
|
| 73 |
+
<div class="topbar-left">
|
| 74 |
+
<h1 class="page-title" id="page-title">Dashboard</h1>
|
| 75 |
+
<div class="breadcrumb" id="breadcrumb">Overview</div>
|
| 76 |
+
</div>
|
| 77 |
+
<div class="topbar-right">
|
| 78 |
+
<button class="btn btn-ghost btn-sm" id="btn-upload-file" onclick="App.openUploadModal('file')" title="Upload .eml / .txt / .pdf">
|
| 79 |
+
<span class="btn-icon">📎</span> Upload File
|
| 80 |
+
</button>
|
| 81 |
+
<button class="btn btn-primary" id="btn-process-email" onclick="App.openUploadModal('paste')">
|
| 82 |
+
<span class="btn-icon">+</span> Process Email
|
| 83 |
+
</button>
|
| 84 |
+
</div>
|
| 85 |
+
</header>
|
| 86 |
+
|
| 87 |
+
<!-- Content area -->
|
| 88 |
+
<main class="content" id="app-content">
|
| 89 |
+
<div class="loading-spinner">
|
| 90 |
+
<div class="spinner"></div>
|
| 91 |
+
<p>Loading...</p>
|
| 92 |
+
</div>
|
| 93 |
+
</main>
|
| 94 |
+
</div>
|
| 95 |
+
|
| 96 |
+
<!-- Upload Modal -->
|
| 97 |
+
<div class="modal-overlay" id="modal-overlay" onclick="App.closeUploadModal(event)">
|
| 98 |
+
<div class="modal" id="upload-modal">
|
| 99 |
+
<div class="modal-header">
|
| 100 |
+
<h2 class="modal-title">Process New Email</h2>
|
| 101 |
+
<button class="modal-close" onclick="App.closeUploadModal(null, true)">✕</button>
|
| 102 |
+
</div>
|
| 103 |
+
|
| 104 |
+
<!-- Tab bar -->
|
| 105 |
+
<div class="modal-tabs" id="modal-tabs">
|
| 106 |
+
<button class="modal-tab active" id="tab-paste" onclick="App.switchTab('paste')">✏ Paste Text</button>
|
| 107 |
+
<button class="modal-tab" id="tab-file" onclick="App.switchTab('file')">📎 Upload File</button>
|
| 108 |
+
</div>
|
| 109 |
+
|
| 110 |
+
<div class="modal-body">
|
| 111 |
+
|
| 112 |
+
<!-- Paste tab -->
|
| 113 |
+
<div id="tab-content-paste">
|
| 114 |
+
<div class="form-group">
|
| 115 |
+
<label class="form-label" for="email-subject">Subject (optional)</label>
|
| 116 |
+
<input type="text" id="email-subject" class="form-input" placeholder="e.g. OPEN VESSELS – PACIFIC MAY 2026" />
|
| 117 |
+
</div>
|
| 118 |
+
<div class="form-group">
|
| 119 |
+
<label class="form-label" for="email-sender">Sender (optional)</label>
|
| 120 |
+
<input type="text" id="email-sender" class="form-input" placeholder="e.g. chartering@broker.com" />
|
| 121 |
+
</div>
|
| 122 |
+
<div class="form-group">
|
| 123 |
+
<label class="form-label" for="email-text">Email Body <span class="required">*</span></label>
|
| 124 |
+
<textarea id="email-text" class="form-textarea" rows="12" placeholder="Paste the full shipping email text here... e.g. MV SHENG AN HAI DWT 56564 OPEN XIAMEN, CHINA O/A 2ND JUNE 2026 ..."></textarea>
|
| 125 |
+
</div>
|
| 126 |
+
</div>
|
| 127 |
+
|
| 128 |
+
<!-- File upload tab -->
|
| 129 |
+
<div id="tab-content-file" style="display:none">
|
| 130 |
+
<div class="form-group">
|
| 131 |
+
<label class="form-label" for="upload-subject">Subject (optional)</label>
|
| 132 |
+
<input type="text" id="upload-subject" class="form-input" placeholder="Override subject from file" />
|
| 133 |
+
</div>
|
| 134 |
+
<div class="form-group">
|
| 135 |
+
<label class="form-label" for="upload-sender">Sender (optional)</label>
|
| 136 |
+
<input type="text" id="upload-sender" class="form-input" placeholder="Override sender from file" />
|
| 137 |
+
</div>
|
| 138 |
+
<div class="form-group">
|
| 139 |
+
<label class="form-label" for="upload-file-input">File <span class="required">*</span></label>
|
| 140 |
+
<div class="file-drop-zone" id="file-drop-zone" onclick="document.getElementById('upload-file-input').click()">
|
| 141 |
+
<div class="file-drop-icon">📎</div>
|
| 142 |
+
<div class="file-drop-text">Click to choose or drag & drop</div>
|
| 143 |
+
<div class="file-drop-sub">.eml · .txt · .pdf supported</div>
|
| 144 |
+
<div class="file-drop-name" id="file-drop-name" style="display:none"></div>
|
| 145 |
+
</div>
|
| 146 |
+
<input type="file" id="upload-file-input" accept=".eml,.txt,.pdf" style="display:none"
|
| 147 |
+
onchange="App.onFileSelected(this)" />
|
| 148 |
+
</div>
|
| 149 |
+
</div>
|
| 150 |
+
|
| 151 |
+
<!-- Classifier preview (shared) -->
|
| 152 |
+
<div class="classifier-preview" id="classifier-preview" style="display:none">
|
| 153 |
+
<div class="preview-label">Detected Category</div>
|
| 154 |
+
<div class="preview-badge" id="preview-badge">—</div>
|
| 155 |
+
<div class="preview-confidence" id="preview-confidence"></div>
|
| 156 |
+
</div>
|
| 157 |
+
|
| 158 |
+
<!-- Duplicate warning -->
|
| 159 |
+
<div class="duplicate-warning" id="duplicate-warning" style="display:none">
|
| 160 |
+
⚠ This email appears to be a duplicate and has been flagged accordingly.
|
| 161 |
+
</div>
|
| 162 |
+
|
| 163 |
+
</div>
|
| 164 |
+
<div class="modal-footer">
|
| 165 |
+
<button class="btn btn-ghost" onclick="App.closeUploadModal(null, true)">Cancel</button>
|
| 166 |
+
<button class="btn btn-primary" id="btn-submit-email" onclick="App.submitEmail()">
|
| 167 |
+
<span id="btn-submit-text">Classify & Extract</span>
|
| 168 |
+
</button>
|
| 169 |
+
</div>
|
| 170 |
+
</div>
|
| 171 |
+
</div>
|
| 172 |
+
|
| 173 |
+
<!-- Toast Container -->
|
| 174 |
+
<div id="toast-container" class="toast-container"></div>
|
| 175 |
+
|
| 176 |
+
<!-- Scripts -->
|
| 177 |
+
<script src="/js/utils.js"></script>
|
| 178 |
+
<script src="/js/api.js"></script>
|
| 179 |
+
<script src="/js/views/dashboard.js"></script>
|
| 180 |
+
<script src="/js/views/inbox.js"></script>
|
| 181 |
+
<script src="/js/views/tonnage.js"></script>
|
| 182 |
+
<script src="/js/views/cargo_vc.js"></script>
|
| 183 |
+
<script src="/js/views/cargo_tc.js"></script>
|
| 184 |
+
<script src="/js/views/matching.js"></script>
|
| 185 |
+
<script src="/js/views/history.js"></script>
|
| 186 |
+
<script src="/js/app.js"></script>
|
| 187 |
+
</body>
|
| 188 |
+
</html>
|
static/js/api.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* api.js — Fetch wrappers for all backend endpoints */
|
| 2 |
+
const API = {
|
| 3 |
+
BASE: '/api',
|
| 4 |
+
|
| 5 |
+
async _req(method, path, body = null, params = {}) {
|
| 6 |
+
const url = new URL(this.BASE + path, window.location.origin);
|
| 7 |
+
Object.entries(params).forEach(([k, v]) => { if (v !== undefined && v !== '') url.searchParams.set(k, v); });
|
| 8 |
+
const opts = { method, headers: { 'Content-Type': 'application/json' } };
|
| 9 |
+
if (body) opts.body = JSON.stringify(body);
|
| 10 |
+
const res = await fetch(url, opts);
|
| 11 |
+
const data = await res.json();
|
| 12 |
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
| 13 |
+
return data;
|
| 14 |
+
},
|
| 15 |
+
|
| 16 |
+
get: (path, params) => API._req('GET', path, null, params),
|
| 17 |
+
post: (path, body) => API._req('POST', path, body),
|
| 18 |
+
patch: (path, body) => API._req('PATCH', path, body),
|
| 19 |
+
delete: (path) => API._req('DELETE', path),
|
| 20 |
+
|
| 21 |
+
// ── Domain helpers ─────────────────────────────────────────────
|
| 22 |
+
stats: () => API.get('/stats'),
|
| 23 |
+
history: () => API.get('/history'),
|
| 24 |
+
emails: (p) => API.get('/emails', p),
|
| 25 |
+
emailById: (id) => API.get(`/emails/${id}`),
|
| 26 |
+
processEmail:(body) => API.post('/emails', body),
|
| 27 |
+
deleteEmail: (id) => API.delete(`/emails/${id}`),
|
| 28 |
+
|
| 29 |
+
// File upload (multipart)
|
| 30 |
+
uploadEmail: (formData) => {
|
| 31 |
+
return fetch('/api/emails/upload', { method: 'POST', body: formData })
|
| 32 |
+
.then(res => res.json().then(data => {
|
| 33 |
+
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
| 34 |
+
return data;
|
| 35 |
+
}));
|
| 36 |
+
},
|
| 37 |
+
|
| 38 |
+
tonnage: (p) => API.get('/tonnage', p),
|
| 39 |
+
updateTonnage: (id, b) => API.patch(`/tonnage/${id}`, b),
|
| 40 |
+
deleteTonnage: (id) => API.delete(`/tonnage/${id}`),
|
| 41 |
+
|
| 42 |
+
cargoVC: (p) => API.get('/cargo_vc', p),
|
| 43 |
+
updateCargoVC: (id, b) => API.patch(`/cargo_vc/${id}`, b),
|
| 44 |
+
deleteCargoVC: (id) => API.delete(`/cargo_vc/${id}`),
|
| 45 |
+
|
| 46 |
+
cargoTC: (p) => API.get('/cargo_tc', p),
|
| 47 |
+
updateCargoTC: (id, b) => API.patch(`/cargo_tc/${id}`, b),
|
| 48 |
+
deleteCargoTC: (id) => API.delete(`/cargo_tc/${id}`),
|
| 49 |
+
|
| 50 |
+
// Matching engine
|
| 51 |
+
matches: (p) => API.get('/matches', p),
|
| 52 |
+
|
| 53 |
+
// CSV export — triggers browser download
|
| 54 |
+
exportCSV(path, filename) {
|
| 55 |
+
const url = `/api${path}`;
|
| 56 |
+
const a = document.createElement('a');
|
| 57 |
+
a.href = url;
|
| 58 |
+
a.download = filename;
|
| 59 |
+
document.body.appendChild(a);
|
| 60 |
+
a.click();
|
| 61 |
+
document.body.removeChild(a);
|
| 62 |
+
},
|
| 63 |
+
exportTonnage: () => API.exportCSV('/tonnage/export', 'tonnage_export.csv'),
|
| 64 |
+
exportCargoVC: () => API.exportCSV('/cargo_vc/export', 'cargo_vc_export.csv'),
|
| 65 |
+
exportCargoTC: () => API.exportCSV('/cargo_tc/export', 'cargo_tc_export.csv'),
|
| 66 |
+
};
|
static/js/app.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* app.js — SPA router, upload modal logic */
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
// ── SPA Router ────────────────────────────────────────────────────
|
| 5 |
+
const VIEWS = {
|
| 6 |
+
'dashboard': { view: DashboardView, title: 'Dashboard', breadcrumb: 'Overview' },
|
| 7 |
+
'inbox': { view: InboxView, title: 'Email Inbox', breadcrumb: 'All Emails' },
|
| 8 |
+
'tonnage': { view: TonnageView, title: 'Tonnage', breadcrumb: 'Open Vessels' },
|
| 9 |
+
'cargo-vc': { view: CargoVCView, title: 'Cargo VC', breadcrumb: 'Voyage Charter Cargos' },
|
| 10 |
+
'cargo-tc': { view: CargoTCView, title: 'Cargo TC', breadcrumb: 'Time Charter Cargos' },
|
| 11 |
+
'matching': { view: MatchingView, title: 'Matching Engine', breadcrumb: 'Vessel ↔ Cargo Matches' },
|
| 12 |
+
'history': { view: HistoryView, title: 'Broker History', breadcrumb: 'Activity Timeline' },
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
+
const App = {
|
| 16 |
+
_current: 'dashboard',
|
| 17 |
+
_activeTab: 'paste', // 'paste' | 'file'
|
| 18 |
+
_selectedFile: null,
|
| 19 |
+
|
| 20 |
+
init() {
|
| 21 |
+
window.addEventListener('hashchange', () => this._handleRoute());
|
| 22 |
+
document.querySelectorAll('.nav-item').forEach(el => {
|
| 23 |
+
el.addEventListener('click', e => {
|
| 24 |
+
e.preventDefault();
|
| 25 |
+
this.navigate(el.dataset.view);
|
| 26 |
+
});
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
// Drag-and-drop on file zone
|
| 30 |
+
const zone = document.getElementById('file-drop-zone');
|
| 31 |
+
if (zone) {
|
| 32 |
+
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
|
| 33 |
+
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
|
| 34 |
+
zone.addEventListener('drop', e => {
|
| 35 |
+
e.preventDefault();
|
| 36 |
+
zone.classList.remove('drag-over');
|
| 37 |
+
const file = e.dataTransfer.files[0];
|
| 38 |
+
if (file) this._setFile(file);
|
| 39 |
+
});
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
this._handleRoute();
|
| 43 |
+
},
|
| 44 |
+
|
| 45 |
+
_handleRoute() {
|
| 46 |
+
const hash = window.location.hash.replace('#', '') || 'dashboard';
|
| 47 |
+
const key = VIEWS[hash] ? hash : 'dashboard';
|
| 48 |
+
this._render(key);
|
| 49 |
+
},
|
| 50 |
+
|
| 51 |
+
navigate(viewKey) {
|
| 52 |
+
window.location.hash = viewKey;
|
| 53 |
+
this._render(viewKey);
|
| 54 |
+
},
|
| 55 |
+
|
| 56 |
+
_render(key) {
|
| 57 |
+
this._current = key;
|
| 58 |
+
const def = VIEWS[key];
|
| 59 |
+
if (!def) return;
|
| 60 |
+
|
| 61 |
+
document.querySelectorAll('.nav-item').forEach(el => {
|
| 62 |
+
el.classList.toggle('active', el.dataset.view === key);
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
document.getElementById('page-title').textContent = def.title;
|
| 66 |
+
document.getElementById('breadcrumb').textContent = def.breadcrumb;
|
| 67 |
+
|
| 68 |
+
const content = document.getElementById('app-content');
|
| 69 |
+
content.innerHTML = def.view.render();
|
| 70 |
+
def.view.init();
|
| 71 |
+
},
|
| 72 |
+
|
| 73 |
+
updateBadges(stats) {
|
| 74 |
+
const t = stats.total_emails || 0;
|
| 75 |
+
const tv = stats.tonnage_records || 0;
|
| 76 |
+
const vc = stats.cargo_vc_records || 0;
|
| 77 |
+
const tc = stats.cargo_tc_records || 0;
|
| 78 |
+
document.getElementById('badge-inbox').textContent = t;
|
| 79 |
+
document.getElementById('badge-tonnage').textContent = tv;
|
| 80 |
+
document.getElementById('badge-vc').textContent = vc;
|
| 81 |
+
document.getElementById('badge-tc').textContent = tc;
|
| 82 |
+
},
|
| 83 |
+
|
| 84 |
+
// ── Upload modal ─────────────────────────────────────────────────
|
| 85 |
+
openUploadModal(tab = 'paste') {
|
| 86 |
+
document.getElementById('modal-overlay').classList.add('open');
|
| 87 |
+
document.getElementById('classifier-preview').style.display = 'none';
|
| 88 |
+
document.getElementById('duplicate-warning').style.display = 'none';
|
| 89 |
+
document.getElementById('email-subject').value = '';
|
| 90 |
+
document.getElementById('email-sender').value = '';
|
| 91 |
+
document.getElementById('email-text').value = '';
|
| 92 |
+
document.getElementById('upload-subject').value = '';
|
| 93 |
+
document.getElementById('upload-sender').value = '';
|
| 94 |
+
this._selectedFile = null;
|
| 95 |
+
document.getElementById('file-drop-name').style.display = 'none';
|
| 96 |
+
document.getElementById('file-drop-name').textContent = '';
|
| 97 |
+
this.switchTab(tab);
|
| 98 |
+
if (tab === 'paste') document.getElementById('email-text').focus();
|
| 99 |
+
},
|
| 100 |
+
|
| 101 |
+
closeUploadModal(event, force = false) {
|
| 102 |
+
if (force || !event || event.target === document.getElementById('modal-overlay')) {
|
| 103 |
+
document.getElementById('modal-overlay').classList.remove('open');
|
| 104 |
+
}
|
| 105 |
+
},
|
| 106 |
+
|
| 107 |
+
switchTab(tab) {
|
| 108 |
+
this._activeTab = tab;
|
| 109 |
+
document.getElementById('tab-content-paste').style.display = tab === 'paste' ? '' : 'none';
|
| 110 |
+
document.getElementById('tab-content-file').style.display = tab === 'file' ? '' : 'none';
|
| 111 |
+
document.getElementById('tab-paste').classList.toggle('active', tab === 'paste');
|
| 112 |
+
document.getElementById('tab-file').classList.toggle('active', tab === 'file');
|
| 113 |
+
document.getElementById('classifier-preview').style.display = 'none';
|
| 114 |
+
document.getElementById('duplicate-warning').style.display = 'none';
|
| 115 |
+
},
|
| 116 |
+
|
| 117 |
+
onFileSelected(input) {
|
| 118 |
+
const file = input.files[0];
|
| 119 |
+
if (file) this._setFile(file);
|
| 120 |
+
},
|
| 121 |
+
|
| 122 |
+
_setFile(file) {
|
| 123 |
+
this._selectedFile = file;
|
| 124 |
+
const nameEl = document.getElementById('file-drop-name');
|
| 125 |
+
nameEl.textContent = `📄 ${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
|
| 126 |
+
nameEl.style.display = 'block';
|
| 127 |
+
},
|
| 128 |
+
|
| 129 |
+
// ── Submit (paste tab) ───────────────────────────────────────────
|
| 130 |
+
async submitEmail() {
|
| 131 |
+
if (this._activeTab === 'file') {
|
| 132 |
+
return this._submitFile();
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
const text = document.getElementById('email-text').value.trim();
|
| 136 |
+
const subject = document.getElementById('email-subject').value.trim();
|
| 137 |
+
const sender = document.getElementById('email-sender').value.trim();
|
| 138 |
+
|
| 139 |
+
if (!text) { Toast.show('Please paste email text', 'error'); return; }
|
| 140 |
+
|
| 141 |
+
const btn = document.getElementById('btn-submit-email');
|
| 142 |
+
const btnText = document.getElementById('btn-submit-text');
|
| 143 |
+
btn.disabled = true;
|
| 144 |
+
btnText.textContent = 'Processing…';
|
| 145 |
+
|
| 146 |
+
try {
|
| 147 |
+
const result = await API.processEmail({ text, subject, sender });
|
| 148 |
+
this._showResult(result);
|
| 149 |
+
} catch(e) {
|
| 150 |
+
Toast.show('Error: ' + e.message, 'error');
|
| 151 |
+
} finally {
|
| 152 |
+
btn.disabled = false;
|
| 153 |
+
btnText.textContent = 'Classify & Extract';
|
| 154 |
+
}
|
| 155 |
+
},
|
| 156 |
+
|
| 157 |
+
// ── Submit (file tab) ────────────────────────────────────────────
|
| 158 |
+
async _submitFile() {
|
| 159 |
+
if (!this._selectedFile) { Toast.show('Please choose a file', 'error'); return; }
|
| 160 |
+
|
| 161 |
+
const btn = document.getElementById('btn-submit-email');
|
| 162 |
+
const btnText = document.getElementById('btn-submit-text');
|
| 163 |
+
btn.disabled = true;
|
| 164 |
+
btnText.textContent = 'Uploading…';
|
| 165 |
+
|
| 166 |
+
try {
|
| 167 |
+
const fd = new FormData();
|
| 168 |
+
fd.append('file', this._selectedFile);
|
| 169 |
+
const subject = document.getElementById('upload-subject').value.trim();
|
| 170 |
+
const sender = document.getElementById('upload-sender').value.trim();
|
| 171 |
+
if (subject) fd.append('subject', subject);
|
| 172 |
+
if (sender) fd.append('sender', sender);
|
| 173 |
+
|
| 174 |
+
const result = await API.uploadEmail(fd);
|
| 175 |
+
this._showResult(result);
|
| 176 |
+
} catch(e) {
|
| 177 |
+
Toast.show('Upload error: ' + e.message, 'error');
|
| 178 |
+
} finally {
|
| 179 |
+
btn.disabled = false;
|
| 180 |
+
btnText.textContent = 'Classify & Extract';
|
| 181 |
+
}
|
| 182 |
+
},
|
| 183 |
+
|
| 184 |
+
// ── Shared result handler ────────────────────────────────────────
|
| 185 |
+
_showResult(result) {
|
| 186 |
+
const preview = document.getElementById('classifier-preview');
|
| 187 |
+
const badge = document.getElementById('preview-badge');
|
| 188 |
+
const conf = document.getElementById('preview-confidence');
|
| 189 |
+
const dupWarn = document.getElementById('duplicate-warning');
|
| 190 |
+
|
| 191 |
+
preview.style.display = 'flex';
|
| 192 |
+
badge.textContent = catLabel(result.category).toUpperCase();
|
| 193 |
+
badge.style.color = {
|
| 194 |
+
tonnage: 'var(--gold)', cargo_vc: 'var(--blue)', cargo_tc: 'var(--purple)',
|
| 195 |
+
}[result.category] || 'var(--text-muted)';
|
| 196 |
+
conf.textContent = `${(result.confidence * 100).toFixed(0)}% confidence`;
|
| 197 |
+
|
| 198 |
+
if (result.is_duplicate) {
|
| 199 |
+
dupWarn.style.display = 'block';
|
| 200 |
+
Toast.show('⚠ Duplicate email detected and flagged', 'warning', 4500);
|
| 201 |
+
} else {
|
| 202 |
+
const count = result.extracted?.length || 0;
|
| 203 |
+
Toast.show(`✓ Classified as ${catLabel(result.category)} · ${count} record${count!==1?'s':''} extracted`, 'success');
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
setTimeout(() => {
|
| 207 |
+
this.closeUploadModal(null, true);
|
| 208 |
+
this.navigate(this._current === 'dashboard' ? 'dashboard' : this._current);
|
| 209 |
+
API.stats().then(s => this.updateBadges(s)).catch(() => {});
|
| 210 |
+
}, 1400);
|
| 211 |
+
},
|
| 212 |
+
};
|
| 213 |
+
|
| 214 |
+
// Boot
|
| 215 |
+
document.addEventListener('DOMContentLoaded', () => App.init());
|
static/js/utils.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* utils.js — Global helper utilities for ShipSeg */
|
| 2 |
+
|
| 3 |
+
function htmlEsc(str) {
|
| 4 |
+
return String(str ?? '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
| 5 |
+
}
|
| 6 |
+
|
| 7 |
+
function fmtDate(iso) {
|
| 8 |
+
if (!iso) return '—';
|
| 9 |
+
try {
|
| 10 |
+
return new Date(iso).toLocaleDateString('en-GB', { day:'numeric', month:'short', year:'2-digit', hour:'2-digit', minute:'2-digit' });
|
| 11 |
+
} catch { return iso; }
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
function catLabel(cat) {
|
| 15 |
+
return { tonnage:'Tonnage', cargo_vc:'Cargo VC', cargo_tc:'Cargo TC', unknown:'Unknown' }[cat] || cat;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
function debounce(fn, ms) {
|
| 19 |
+
let t;
|
| 20 |
+
return function(...args) { clearTimeout(t); t = setTimeout(() => fn.apply(this, args), ms); };
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
// ── Toast ─────────────────────────────────────────────────────────
|
| 24 |
+
const Toast = {
|
| 25 |
+
show(msg, type = 'info', duration = 3500) {
|
| 26 |
+
const icons = { success: '✓', error: '✕', info: 'ℹ', warning: '⚠' };
|
| 27 |
+
const el = document.createElement('div');
|
| 28 |
+
el.className = `toast ${type}`;
|
| 29 |
+
el.innerHTML = `<span class="toast-icon">${icons[type]||'ℹ'}</span><span class="toast-msg">${htmlEsc(msg)}</span>`;
|
| 30 |
+
const container = document.getElementById('toast-container');
|
| 31 |
+
container.appendChild(el);
|
| 32 |
+
setTimeout(() => {
|
| 33 |
+
el.style.opacity = '0';
|
| 34 |
+
el.style.transition = 'opacity 0.3s';
|
| 35 |
+
setTimeout(() => el.remove(), 300);
|
| 36 |
+
}, duration);
|
| 37 |
+
},
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
// ── Shared edit modal ─────────────────────────────────────────────
|
| 41 |
+
function showEditModal(title, fields, onSave) {
|
| 42 |
+
const existing = document.getElementById('edit-modal-overlay');
|
| 43 |
+
if (existing) existing.remove();
|
| 44 |
+
|
| 45 |
+
const overlay = document.createElement('div');
|
| 46 |
+
overlay.id = 'edit-modal-overlay';
|
| 47 |
+
overlay.className = 'modal-overlay open';
|
| 48 |
+
overlay.innerHTML = `
|
| 49 |
+
<div class="modal" style="max-width:560px">
|
| 50 |
+
<div class="modal-header">
|
| 51 |
+
<h2 class="modal-title">${htmlEsc(title)}</h2>
|
| 52 |
+
<button class="modal-close" onclick="document.getElementById('edit-modal-overlay').remove()">✕</button>
|
| 53 |
+
</div>
|
| 54 |
+
<div class="modal-body">
|
| 55 |
+
${fields.map(([key, label, val]) => `
|
| 56 |
+
<div class="form-group">
|
| 57 |
+
<label class="form-label" for="edit-${key}">${htmlEsc(label)}</label>
|
| 58 |
+
<input type="text" id="edit-${key}" class="form-input"
|
| 59 |
+
value="${htmlEsc(val||'')}" data-key="${key}" />
|
| 60 |
+
</div>`).join('')}
|
| 61 |
+
</div>
|
| 62 |
+
<div class="modal-footer">
|
| 63 |
+
<button class="btn btn-ghost" onclick="document.getElementById('edit-modal-overlay').remove()">Cancel</button>
|
| 64 |
+
<button class="btn btn-primary" id="edit-save-btn">Save Changes</button>
|
| 65 |
+
</div>
|
| 66 |
+
</div>`;
|
| 67 |
+
|
| 68 |
+
overlay.onclick = e => { if (e.target === overlay) overlay.remove(); };
|
| 69 |
+
document.body.appendChild(overlay);
|
| 70 |
+
|
| 71 |
+
document.getElementById('edit-save-btn').onclick = async () => {
|
| 72 |
+
const form = {};
|
| 73 |
+
overlay.querySelectorAll('[data-key]').forEach(el => {
|
| 74 |
+
form[el.dataset.key] = el.value.trim() || null;
|
| 75 |
+
});
|
| 76 |
+
const btn = document.getElementById('edit-save-btn');
|
| 77 |
+
btn.textContent = 'Saving…';
|
| 78 |
+
btn.disabled = true;
|
| 79 |
+
try {
|
| 80 |
+
await onSave(form);
|
| 81 |
+
overlay.remove();
|
| 82 |
+
} catch(e) {
|
| 83 |
+
Toast.show('Save failed: ' + e.message, 'error');
|
| 84 |
+
btn.textContent = 'Save Changes';
|
| 85 |
+
btn.disabled = false;
|
| 86 |
+
}
|
| 87 |
+
};
|
| 88 |
+
}
|
static/js/views/cargo_tc.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* cargo_tc.js — Time Charter cargo records view */
|
| 2 |
+
const CargoTCView = {
|
| 3 |
+
_page: 1, _total: 0, _perPage: 20, _search: '',
|
| 4 |
+
|
| 5 |
+
render() {
|
| 6 |
+
return `
|
| 7 |
+
<div class="fade-in">
|
| 8 |
+
<div class="table-card">
|
| 9 |
+
<div class="table-toolbar">
|
| 10 |
+
<div class="search-box">
|
| 11 |
+
<span class="search-icon">⌕</span>
|
| 12 |
+
<input type="text" class="search-input" id="tc-search"
|
| 13 |
+
placeholder="Search cargo or port…" oninput="CargoTCView.onSearch(this.value)" />
|
| 14 |
+
</div>
|
| 15 |
+
<div style="display:flex;gap:8px;align-items:center">
|
| 16 |
+
<span class="td-muted" id="tc-count" style="font-size:13px"></span>
|
| 17 |
+
<button class="btn btn-ghost btn-sm" onclick="API.exportCargoTC()" title="Export to CSV">⬇ Export CSV</button>
|
| 18 |
+
</div>
|
| 19 |
+
</div>
|
| 20 |
+
<div class="table-wrapper">
|
| 21 |
+
<table>
|
| 22 |
+
<thead><tr>
|
| 23 |
+
<th>Cargo</th>
|
| 24 |
+
<th>Delivery Port</th>
|
| 25 |
+
<th>Redelivery Port</th>
|
| 26 |
+
<th>Duration</th>
|
| 27 |
+
<th>Laycan</th>
|
| 28 |
+
<th>Type</th>
|
| 29 |
+
<th>Account</th>
|
| 30 |
+
<th>Actions</th>
|
| 31 |
+
</tr></thead>
|
| 32 |
+
<tbody id="tc-body">
|
| 33 |
+
<tr><td colspan="8"><div class="loading-spinner"><div class="spinner"></div></div></td></tr>
|
| 34 |
+
</tbody>
|
| 35 |
+
</table>
|
| 36 |
+
</div>
|
| 37 |
+
<div class="pagination" id="tc-pagination"></div>
|
| 38 |
+
</div>
|
| 39 |
+
</div>`;
|
| 40 |
+
},
|
| 41 |
+
|
| 42 |
+
async init() { this._page=1; this._search=''; await this.load(); },
|
| 43 |
+
|
| 44 |
+
async load() {
|
| 45 |
+
try {
|
| 46 |
+
const data = await API.cargoTC({ page:this._page, per_page:this._perPage, search:this._search });
|
| 47 |
+
this._total = data.total;
|
| 48 |
+
this._render(data.records, data.total);
|
| 49 |
+
} catch(e) { Toast.show('Failed to load Cargo TC: '+e.message,'error'); }
|
| 50 |
+
},
|
| 51 |
+
|
| 52 |
+
_render(records, total) {
|
| 53 |
+
const start=(this._page-1)*this._perPage+1, end=Math.min(this._page*this._perPage,total);
|
| 54 |
+
document.getElementById('tc-count').textContent = total ? `${start}–${end} of ${total} cargos` : 'No results';
|
| 55 |
+
|
| 56 |
+
const tbody=document.getElementById('tc-body');
|
| 57 |
+
if (!records.length) {
|
| 58 |
+
tbody.innerHTML = `<tr><td colspan="8"><div class="empty-state">
|
| 59 |
+
<div class="empty-icon">⏱</div>
|
| 60 |
+
<div class="empty-text">No Cargo TC records yet</div>
|
| 61 |
+
<div class="empty-sub">Process a time charter email to populate this table</div>
|
| 62 |
+
</div></td></tr>`;
|
| 63 |
+
} else {
|
| 64 |
+
tbody.innerHTML = records.map(r => `
|
| 65 |
+
<tr>
|
| 66 |
+
<td><span style="font-weight:600;color:var(--purple)">${htmlEsc(r.cargo_name||'—')}</span></td>
|
| 67 |
+
<td><span style="color:var(--green)">${htmlEsc(r.delivery_port||'—')}</span></td>
|
| 68 |
+
<td><span style="color:var(--gold)">${htmlEsc(r.redelivery_port||'—')}</span></td>
|
| 69 |
+
<td class="td-mono" style="font-size:12px">${htmlEsc(r.duration||'—')}</td>
|
| 70 |
+
<td class="td-muted">${htmlEsc(r.laycan||'—')}</td>
|
| 71 |
+
<td style="font-size:12px;color:var(--text-secondary)">${htmlEsc(r.cargo_type||'—')}</td>
|
| 72 |
+
<td class="td-muted" style="font-size:12px;max-width:130px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
|
| 73 |
+
title="${htmlEsc(r.account_name||'')}">${htmlEsc(r.account_name||'—')}</td>
|
| 74 |
+
<td>
|
| 75 |
+
<div class="action-cell">
|
| 76 |
+
<button class="btn btn-ghost btn-sm btn-icon-only" title="View Source Email" onclick="viewEmailSource(${r.email_id}, '${htmlEsc(r.cargo_name || 'Cargo TC')}')">✉</button>
|
| 77 |
+
<button class="btn btn-ghost btn-sm btn-icon-only" title="Edit" onclick="CargoTCView.edit(${r.id})">✎</button>
|
| 78 |
+
<button class="btn btn-danger btn-sm btn-icon-only" title="Delete" onclick="CargoTCView.delete(${r.id})">🗑</button>
|
| 79 |
+
</div>
|
| 80 |
+
</td>
|
| 81 |
+
</tr>`).join('');
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
const pages=Math.ceil(total/this._perPage);
|
| 85 |
+
const pg=document.getElementById('tc-pagination');
|
| 86 |
+
if(pages<=1){pg.innerHTML='';return;}
|
| 87 |
+
pg.innerHTML=`
|
| 88 |
+
<span>${total} total</span>
|
| 89 |
+
<div class="pagination-controls">
|
| 90 |
+
<button class="page-btn" ${this._page<=1?'disabled':''} onclick="CargoTCView.goPage(${this._page-1})">‹</button>
|
| 91 |
+
${Array.from({length:Math.min(pages,7)},(_,i)=>`
|
| 92 |
+
<button class="page-btn ${i+1===this._page?'active':''}" onclick="CargoTCView.goPage(${i+1})">${i+1}</button>`).join('')}
|
| 93 |
+
<button class="page-btn" ${this._page>=pages?'disabled':''} onclick="CargoTCView.goPage(${this._page+1})">›</button>
|
| 94 |
+
</div>`;
|
| 95 |
+
},
|
| 96 |
+
|
| 97 |
+
onSearch: debounce(function(v){ CargoTCView._search=v; CargoTCView._page=1; CargoTCView.load(); }, 350),
|
| 98 |
+
goPage(p) { this._page=p; this.load(); },
|
| 99 |
+
|
| 100 |
+
edit(id) {
|
| 101 |
+
API.get(`/cargo_tc/${id}`).then(r => {
|
| 102 |
+
const fields = [
|
| 103 |
+
['cargo_name','Cargo Name',r.cargo_name],
|
| 104 |
+
['delivery_port','Delivery Port',r.delivery_port],
|
| 105 |
+
['redelivery_port','Redelivery Port',r.redelivery_port],
|
| 106 |
+
['duration','Duration',r.duration],
|
| 107 |
+
['laycan','Laycan',r.laycan],
|
| 108 |
+
['cargo_type','Cargo Type',r.cargo_type],
|
| 109 |
+
['account_name','Account',r.account_name],
|
| 110 |
+
];
|
| 111 |
+
showEditModal('Edit Cargo TC Record', fields, async (form) => {
|
| 112 |
+
await API.updateCargoTC(id, form);
|
| 113 |
+
Toast.show('Record updated','success');
|
| 114 |
+
CargoTCView.load();
|
| 115 |
+
});
|
| 116 |
+
}).catch(e => Toast.show('Error: '+e.message,'error'));
|
| 117 |
+
},
|
| 118 |
+
|
| 119 |
+
async delete(id) {
|
| 120 |
+
if (!confirm('Delete this cargo TC record?')) return;
|
| 121 |
+
try { await API.deleteCargoTC(id); Toast.show('Deleted','success'); this.load(); }
|
| 122 |
+
catch(e) { Toast.show('Error: '+e.message,'error'); }
|
| 123 |
+
},
|
| 124 |
+
};
|
static/js/views/cargo_vc.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* cargo_vc.js — Voyage Charter cargo records view */
|
| 2 |
+
const CargoVCView = {
|
| 3 |
+
_page: 1, _total: 0, _perPage: 20, _search: '',
|
| 4 |
+
|
| 5 |
+
render() {
|
| 6 |
+
return `
|
| 7 |
+
<div class="fade-in">
|
| 8 |
+
<div class="table-card">
|
| 9 |
+
<div class="table-toolbar">
|
| 10 |
+
<div class="search-box">
|
| 11 |
+
<span class="search-icon">⌕</span>
|
| 12 |
+
<input type="text" class="search-input" id="vc-search"
|
| 13 |
+
placeholder="Search cargo or port…" oninput="CargoVCView.onSearch(this.value)" />
|
| 14 |
+
</div>
|
| 15 |
+
<div style="display:flex;gap:8px;align-items:center">
|
| 16 |
+
<span class="td-muted" id="vc-count" style="font-size:13px"></span>
|
| 17 |
+
<button class="btn btn-ghost btn-sm" onclick="API.exportCargoVC()" title="Export to CSV">⬇ Export CSV</button>
|
| 18 |
+
</div>
|
| 19 |
+
</div>
|
| 20 |
+
<div class="table-wrapper">
|
| 21 |
+
<table>
|
| 22 |
+
<thead><tr>
|
| 23 |
+
<th>Cargo</th>
|
| 24 |
+
<th>Quantity</th>
|
| 25 |
+
<th>Loading Port</th>
|
| 26 |
+
<th>Discharge Port</th>
|
| 27 |
+
<th>Laycan</th>
|
| 28 |
+
<th>Type</th>
|
| 29 |
+
<th>Account</th>
|
| 30 |
+
<th>Actions</th>
|
| 31 |
+
</tr></thead>
|
| 32 |
+
<tbody id="vc-body">
|
| 33 |
+
<tr><td colspan="8"><div class="loading-spinner"><div class="spinner"></div></div></td></tr>
|
| 34 |
+
</tbody>
|
| 35 |
+
</table>
|
| 36 |
+
</div>
|
| 37 |
+
<div class="pagination" id="vc-pagination"></div>
|
| 38 |
+
</div>
|
| 39 |
+
</div>`;
|
| 40 |
+
},
|
| 41 |
+
|
| 42 |
+
async init() { this._page=1; this._search=''; await this.load(); },
|
| 43 |
+
|
| 44 |
+
async load() {
|
| 45 |
+
try {
|
| 46 |
+
const data = await API.cargoVC({ page:this._page, per_page:this._perPage, search:this._search });
|
| 47 |
+
this._total = data.total;
|
| 48 |
+
this._render(data.records, data.total);
|
| 49 |
+
} catch(e) { Toast.show('Failed to load Cargo VC: '+e.message,'error'); }
|
| 50 |
+
},
|
| 51 |
+
|
| 52 |
+
_render(records, total) {
|
| 53 |
+
const start=(this._page-1)*this._perPage+1, end=Math.min(this._page*this._perPage,total);
|
| 54 |
+
document.getElementById('vc-count').textContent = total ? `${start}–${end} of ${total} cargos` : 'No results';
|
| 55 |
+
|
| 56 |
+
const tbody = document.getElementById('vc-body');
|
| 57 |
+
if (!records.length) {
|
| 58 |
+
tbody.innerHTML = `<tr><td colspan="8"><div class="empty-state">
|
| 59 |
+
<div class="empty-icon">📦</div>
|
| 60 |
+
<div class="empty-text">No Cargo VC records yet</div>
|
| 61 |
+
<div class="empty-sub">Process a voyage charter cargo email to populate this table</div>
|
| 62 |
+
</div></td></tr>`;
|
| 63 |
+
} else {
|
| 64 |
+
tbody.innerHTML = records.map(r => `
|
| 65 |
+
<tr>
|
| 66 |
+
<td><span style="font-weight:600;color:var(--blue)">${htmlEsc(r.cargo_name||'—')}</span></td>
|
| 67 |
+
<td class="td-mono" style="font-size:12px">${htmlEsc(r.quantity||'—')}</td>
|
| 68 |
+
<td><span style="color:var(--green)">${htmlEsc(r.loading_port||'—')}</span></td>
|
| 69 |
+
<td><span style="color:var(--gold)">${htmlEsc(r.discharge_port||'—')}</span></td>
|
| 70 |
+
<td class="td-muted">${htmlEsc(r.laycan||'—')}</td>
|
| 71 |
+
<td><span style="font-size:12px;color:var(--text-secondary)">${htmlEsc(r.cargo_type||'—')}</span></td>
|
| 72 |
+
<td class="td-muted" style="font-size:12px;max-width:130px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
|
| 73 |
+
title="${htmlEsc(r.account_name||'')}">${htmlEsc(r.account_name||'—')}</td>
|
| 74 |
+
<td>
|
| 75 |
+
<div class="action-cell">
|
| 76 |
+
<button class="btn btn-ghost btn-sm btn-icon-only" title="View Source Email" onclick="viewEmailSource(${r.email_id}, '${htmlEsc(r.cargo_name || 'Cargo VC')}')">✉</button>
|
| 77 |
+
<button class="btn btn-ghost btn-sm btn-icon-only" title="Edit" onclick="CargoVCView.edit(${r.id})">✎</button>
|
| 78 |
+
<button class="btn btn-danger btn-sm btn-icon-only" title="Delete" onclick="CargoVCView.delete(${r.id})">🗑</button>
|
| 79 |
+
</div>
|
| 80 |
+
</td>
|
| 81 |
+
</tr>`).join('');
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
const pages=Math.ceil(total/this._perPage);
|
| 85 |
+
const pg=document.getElementById('vc-pagination');
|
| 86 |
+
if(pages<=1){pg.innerHTML='';return;}
|
| 87 |
+
pg.innerHTML=`
|
| 88 |
+
<span>${total} total</span>
|
| 89 |
+
<div class="pagination-controls">
|
| 90 |
+
<button class="page-btn" ${this._page<=1?'disabled':''} onclick="CargoVCView.goPage(${this._page-1})">‹</button>
|
| 91 |
+
${Array.from({length:Math.min(pages,7)},(_,i)=>`
|
| 92 |
+
<button class="page-btn ${i+1===this._page?'active':''}" onclick="CargoVCView.goPage(${i+1})">${i+1}</button>`).join('')}
|
| 93 |
+
<button class="page-btn" ${this._page>=pages?'disabled':''} onclick="CargoVCView.goPage(${this._page+1})">›</button>
|
| 94 |
+
</div>`;
|
| 95 |
+
},
|
| 96 |
+
|
| 97 |
+
onSearch: debounce(function(v){ CargoVCView._search=v; CargoVCView._page=1; CargoVCView.load(); }, 350),
|
| 98 |
+
goPage(p) { this._page=p; this.load(); },
|
| 99 |
+
|
| 100 |
+
edit(id) {
|
| 101 |
+
API.get(`/cargo_vc/${id}`).then(r => {
|
| 102 |
+
const fields = [
|
| 103 |
+
['cargo_name','Cargo Name',r.cargo_name],
|
| 104 |
+
['quantity','Quantity',r.quantity],
|
| 105 |
+
['loading_port','Loading Port',r.loading_port],
|
| 106 |
+
['discharge_port','Discharge Port',r.discharge_port],
|
| 107 |
+
['laycan','Laycan',r.laycan],
|
| 108 |
+
['cargo_type','Cargo Type',r.cargo_type],
|
| 109 |
+
['account_name','Account',r.account_name],
|
| 110 |
+
];
|
| 111 |
+
showEditModal('Edit Cargo VC Record', fields, async (form) => {
|
| 112 |
+
await API.updateCargoVC(id, form);
|
| 113 |
+
Toast.show('Record updated','success');
|
| 114 |
+
CargoVCView.load();
|
| 115 |
+
});
|
| 116 |
+
}).catch(e => Toast.show('Error: '+e.message,'error'));
|
| 117 |
+
},
|
| 118 |
+
|
| 119 |
+
async delete(id) {
|
| 120 |
+
if (!confirm('Delete this cargo VC record?')) return;
|
| 121 |
+
try { await API.deleteCargoVC(id); Toast.show('Deleted','success'); this.load(); }
|
| 122 |
+
catch(e) { Toast.show('Error: '+e.message,'error'); }
|
| 123 |
+
},
|
| 124 |
+
};
|
static/js/views/dashboard.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* dashboard.js — Overview dashboard view */
|
| 2 |
+
const DashboardView = {
|
| 3 |
+
_stats: null,
|
| 4 |
+
|
| 5 |
+
render() {
|
| 6 |
+
return `
|
| 7 |
+
<div class="fade-in">
|
| 8 |
+
<div class="stats-grid" id="stats-grid">
|
| 9 |
+
${[0,1,2,3].map(() => `
|
| 10 |
+
<div class="stat-card">
|
| 11 |
+
<div class="stat-header"><span class="stat-label">Loading…</span></div>
|
| 12 |
+
<div class="stat-number" style="color:var(--text-muted)">—</div>
|
| 13 |
+
</div>`).join('')}
|
| 14 |
+
</div>
|
| 15 |
+
|
| 16 |
+
<div class="two-col">
|
| 17 |
+
<div>
|
| 18 |
+
<div class="section-header">
|
| 19 |
+
<h2 class="section-title">Recent Emails</h2>
|
| 20 |
+
<a href="#inbox" class="btn btn-ghost btn-sm" onclick="App.navigate('inbox')">View all →</a>
|
| 21 |
+
</div>
|
| 22 |
+
<div class="table-card">
|
| 23 |
+
<div class="table-wrapper">
|
| 24 |
+
<table id="recent-table">
|
| 25 |
+
<thead><tr>
|
| 26 |
+
<th>Subject</th><th>Category</th><th>Confidence</th><th>Date</th>
|
| 27 |
+
</tr></thead>
|
| 28 |
+
<tbody id="recent-body">
|
| 29 |
+
<tr><td colspan="4" class="empty-state">
|
| 30 |
+
<div class="empty-icon">✉</div>
|
| 31 |
+
<div class="empty-text">Loading recent emails…</div>
|
| 32 |
+
</td></tr>
|
| 33 |
+
</tbody>
|
| 34 |
+
</table>
|
| 35 |
+
</div>
|
| 36 |
+
</div>
|
| 37 |
+
</div>
|
| 38 |
+
|
| 39 |
+
<div>
|
| 40 |
+
<div class="section-header">
|
| 41 |
+
<h2 class="section-title">Category Breakdown</h2>
|
| 42 |
+
</div>
|
| 43 |
+
<div class="card">
|
| 44 |
+
<div id="chart-area">
|
| 45 |
+
<div class="loading-spinner" style="height:120px">
|
| 46 |
+
<div class="spinner"></div>
|
| 47 |
+
</div>
|
| 48 |
+
</div>
|
| 49 |
+
</div>
|
| 50 |
+
|
| 51 |
+
<div class="section-header" style="margin-top:20px">
|
| 52 |
+
<h2 class="section-title">Quick Actions</h2>
|
| 53 |
+
</div>
|
| 54 |
+
<div class="card" style="display:flex;flex-direction:column;gap:10px">
|
| 55 |
+
<button class="btn btn-primary" onclick="App.openUploadModal()" style="width:100%;justify-content:center">
|
| 56 |
+
<span class="btn-icon">+</span> Process New Email
|
| 57 |
+
</button>
|
| 58 |
+
<button class="btn btn-ghost" onclick="App.navigate('tonnage')" style="width:100%;justify-content:center">
|
| 59 |
+
🚢 View All Tonnage Records
|
| 60 |
+
</button>
|
| 61 |
+
<button class="btn btn-ghost" onclick="App.navigate('cargo-vc')" style="width:100%;justify-content:center">
|
| 62 |
+
📦 View All Cargo VC Records
|
| 63 |
+
</button>
|
| 64 |
+
<button class="btn btn-ghost" onclick="App.navigate('cargo-tc')" style="width:100%;justify-content:center">
|
| 65 |
+
⏱ View All Cargo TC Records
|
| 66 |
+
</button>
|
| 67 |
+
</div>
|
| 68 |
+
</div>
|
| 69 |
+
</div>
|
| 70 |
+
</div>`;
|
| 71 |
+
},
|
| 72 |
+
|
| 73 |
+
async init() {
|
| 74 |
+
try {
|
| 75 |
+
const stats = await API.stats();
|
| 76 |
+
this._stats = stats;
|
| 77 |
+
this._renderStats(stats);
|
| 78 |
+
this._renderRecent(stats.recent || []);
|
| 79 |
+
this._renderChart(stats);
|
| 80 |
+
App.updateBadges(stats);
|
| 81 |
+
} catch (e) {
|
| 82 |
+
Toast.show('Failed to load stats: ' + e.message, 'error');
|
| 83 |
+
}
|
| 84 |
+
},
|
| 85 |
+
|
| 86 |
+
_renderStats(s) {
|
| 87 |
+
document.getElementById('stats-grid').innerHTML = `
|
| 88 |
+
<div class="stat-card green">
|
| 89 |
+
<div class="stat-header">
|
| 90 |
+
<span class="stat-label">Total Emails</span>
|
| 91 |
+
<span class="stat-icon">✉</span>
|
| 92 |
+
</div>
|
| 93 |
+
<div class="stat-number">${s.total_emails}</div>
|
| 94 |
+
<div class="stat-sub">All ingested emails</div>
|
| 95 |
+
</div>
|
| 96 |
+
<div class="stat-card gold">
|
| 97 |
+
<div class="stat-header">
|
| 98 |
+
<span class="stat-label">Tonnage</span>
|
| 99 |
+
<span class="stat-icon">🚢</span>
|
| 100 |
+
</div>
|
| 101 |
+
<div class="stat-number">${s.tonnage_records}</div>
|
| 102 |
+
<div class="stat-sub">Vessel records</div>
|
| 103 |
+
</div>
|
| 104 |
+
<div class="stat-card blue">
|
| 105 |
+
<div class="stat-header">
|
| 106 |
+
<span class="stat-label">Cargo VC</span>
|
| 107 |
+
<span class="stat-icon">📦</span>
|
| 108 |
+
</div>
|
| 109 |
+
<div class="stat-number">${s.cargo_vc_records}</div>
|
| 110 |
+
<div class="stat-sub">Voyage charter cargos</div>
|
| 111 |
+
</div>
|
| 112 |
+
<div class="stat-card purple">
|
| 113 |
+
<div class="stat-header">
|
| 114 |
+
<span class="stat-label">Cargo TC</span>
|
| 115 |
+
<span class="stat-icon">⏱</span>
|
| 116 |
+
</div>
|
| 117 |
+
<div class="stat-number">${s.cargo_tc_records}</div>
|
| 118 |
+
<div class="stat-sub">Time charter cargos</div>
|
| 119 |
+
</div>`;
|
| 120 |
+
},
|
| 121 |
+
|
| 122 |
+
_renderRecent(emails) {
|
| 123 |
+
const tbody = document.getElementById('recent-body');
|
| 124 |
+
if (!emails.length) {
|
| 125 |
+
tbody.innerHTML = `<tr><td colspan="4">
|
| 126 |
+
<div class="empty-state">
|
| 127 |
+
<div class="empty-icon">✉</div>
|
| 128 |
+
<div class="empty-text">No emails yet</div>
|
| 129 |
+
<div class="empty-sub">Click "Process Email" to get started</div>
|
| 130 |
+
</div>
|
| 131 |
+
</td></tr>`;
|
| 132 |
+
return;
|
| 133 |
+
}
|
| 134 |
+
tbody.innerHTML = emails.map(e => `
|
| 135 |
+
<tr>
|
| 136 |
+
<td style="max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
|
| 137 |
+
title="${htmlEsc(e.subject || '')}">${htmlEsc(e.subject || 'No Subject')}</td>
|
| 138 |
+
<td><span class="badge badge-${e.category}">${catLabel(e.category)}</span></td>
|
| 139 |
+
<td><span class="conf-pill">${(e.confidence*100).toFixed(0)}%</span></td>
|
| 140 |
+
<td class="td-muted">${fmtDate(e.created_at)}</td>
|
| 141 |
+
</tr>`).join('');
|
| 142 |
+
},
|
| 143 |
+
|
| 144 |
+
_renderChart(s) {
|
| 145 |
+
const total = s.total_emails || 1;
|
| 146 |
+
const cats = [
|
| 147 |
+
{ key: 'tonnage', label: 'Tonnage', color: 'gold', val: (s.by_category.tonnage || 0) },
|
| 148 |
+
{ key: 'cargo_vc', label: 'Cargo VC', color: 'blue', val: (s.by_category.cargo_vc || 0) },
|
| 149 |
+
{ key: 'cargo_tc', label: 'Cargo TC', color: 'purple', val: (s.by_category.cargo_tc || 0) },
|
| 150 |
+
];
|
| 151 |
+
document.getElementById('chart-area').innerHTML = cats.map(c => `
|
| 152 |
+
<div class="chart-bar-row">
|
| 153 |
+
<span class="chart-bar-label">${c.label}</span>
|
| 154 |
+
<div class="chart-bar-track">
|
| 155 |
+
<div class="chart-bar-fill ${c.color}" style="width:0%" data-pct="${Math.round(c.val/total*100)}"></div>
|
| 156 |
+
</div>
|
| 157 |
+
<span class="chart-bar-count">${c.val}</span>
|
| 158 |
+
</div>`).join('');
|
| 159 |
+
// Animate bars after render
|
| 160 |
+
requestAnimationFrame(() => {
|
| 161 |
+
document.querySelectorAll('.chart-bar-fill').forEach(el => {
|
| 162 |
+
el.style.width = el.dataset.pct + '%';
|
| 163 |
+
});
|
| 164 |
+
});
|
| 165 |
+
},
|
| 166 |
+
};
|
static/js/views/history.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* history.js — Per-broker / per-sender activity tracking */
|
| 2 |
+
const HistoryView = {
|
| 3 |
+
_data: [],
|
| 4 |
+
|
| 5 |
+
render() {
|
| 6 |
+
return `
|
| 7 |
+
<div class="fade-in">
|
| 8 |
+
<div class="section-header" style="margin-bottom:16px">
|
| 9 |
+
<h2 class="section-title">Broker Activity Timeline</h2>
|
| 10 |
+
<span class="td-muted" id="history-count" style="font-size:13px"></span>
|
| 11 |
+
</div>
|
| 12 |
+
<div class="table-card">
|
| 13 |
+
<div class="table-wrapper">
|
| 14 |
+
<table>
|
| 15 |
+
<thead><tr>
|
| 16 |
+
<th>#</th>
|
| 17 |
+
<th>Broker / Sender</th>
|
| 18 |
+
<th>Emails</th>
|
| 19 |
+
<th>Tonnage</th>
|
| 20 |
+
<th>Cargo VC</th>
|
| 21 |
+
<th>Cargo TC</th>
|
| 22 |
+
<th>Unknown</th>
|
| 23 |
+
<th>Last Seen</th>
|
| 24 |
+
</tr></thead>
|
| 25 |
+
<tbody id="history-body">
|
| 26 |
+
<tr><td colspan="8"><div class="loading-spinner"><div class="spinner"></div></div></td></tr>
|
| 27 |
+
</tbody>
|
| 28 |
+
</table>
|
| 29 |
+
</div>
|
| 30 |
+
</div>
|
| 31 |
+
</div>`;
|
| 32 |
+
},
|
| 33 |
+
|
| 34 |
+
async init() {
|
| 35 |
+
await this.load();
|
| 36 |
+
},
|
| 37 |
+
|
| 38 |
+
async load() {
|
| 39 |
+
try {
|
| 40 |
+
const data = await API.history();
|
| 41 |
+
this._data = data.history || [];
|
| 42 |
+
this._render();
|
| 43 |
+
} catch(e) {
|
| 44 |
+
Toast.show('Failed to load history: ' + e.message, 'error');
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
|
| 48 |
+
_render() {
|
| 49 |
+
const tbody = document.getElementById('history-body');
|
| 50 |
+
const countEl = document.getElementById('history-count');
|
| 51 |
+
countEl.textContent = `${this._data.length} broker${this._data.length !== 1 ? 's' : ''}`;
|
| 52 |
+
|
| 53 |
+
if (!this._data.length) {
|
| 54 |
+
tbody.innerHTML = `<tr><td colspan="8">
|
| 55 |
+
<div class="empty-state">
|
| 56 |
+
<div class="empty-icon">📅</div>
|
| 57 |
+
<div class="empty-text">No broker history yet</div>
|
| 58 |
+
<div class="empty-sub">Process some emails to see activity here</div>
|
| 59 |
+
</div></td></tr>`;
|
| 60 |
+
return;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
tbody.innerHTML = this._data.map((row, i) => {
|
| 64 |
+
const cats = row.categories || {};
|
| 65 |
+
const tonnage = cats.tonnage || 0;
|
| 66 |
+
const cargoVc = cats.cargo_vc || 0;
|
| 67 |
+
const cargoTc = cats.cargo_tc || 0;
|
| 68 |
+
const unknown = cats.unknown || 0;
|
| 69 |
+
return `
|
| 70 |
+
<tr>
|
| 71 |
+
<td class="td-muted td-mono">${i + 1}</td>
|
| 72 |
+
<td>
|
| 73 |
+
<div style="font-weight:500">${htmlEsc(row.sender || '—')}</div>
|
| 74 |
+
</td>
|
| 75 |
+
<td><span class="conf-pill">${row.total}</span></td>
|
| 76 |
+
<td>${tonnage ? `<span class="badge badge-tonnage">${tonnage}</span>` : '<span class="td-muted">—</span>'}</td>
|
| 77 |
+
<td>${cargoVc ? `<span class="badge badge-cargo_vc">${cargoVc}</span>` : '<span class="td-muted">—</span>'}</td>
|
| 78 |
+
<td>${cargoTc ? `<span class="badge badge-cargo_tc">${cargoTc}</span>` : '<span class="td-muted">—</span>'}</td>
|
| 79 |
+
<td>${unknown ? `<span class="td-muted">${unknown}</span>` : '<span class="td-muted">—</span>'}</td>
|
| 80 |
+
<td class="td-muted">${fmtDate(row.last_seen)}</td>
|
| 81 |
+
</tr>`;
|
| 82 |
+
}).join('');
|
| 83 |
+
},
|
| 84 |
+
};
|
static/js/views/inbox.js
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* inbox.js — All emails view with category filter */
|
| 2 |
+
const InboxView = {
|
| 3 |
+
_page: 1,
|
| 4 |
+
_total: 0,
|
| 5 |
+
_perPage: 20,
|
| 6 |
+
_category: '',
|
| 7 |
+
_search: '',
|
| 8 |
+
|
| 9 |
+
render() {
|
| 10 |
+
return `
|
| 11 |
+
<div class="fade-in">
|
| 12 |
+
<div class="cat-bar" id="cat-bar">
|
| 13 |
+
<button class="cat-pill active-all" data-cat="" onclick="InboxView.filterCat('')">
|
| 14 |
+
<span class="cat-pill-dot" style="background:var(--text-secondary)"></span> All
|
| 15 |
+
</button>
|
| 16 |
+
<button class="cat-pill" data-cat="tonnage" onclick="InboxView.filterCat('tonnage')">
|
| 17 |
+
<span class="cat-pill-dot" style="background:var(--gold)"></span> Tonnage
|
| 18 |
+
</button>
|
| 19 |
+
<button class="cat-pill" data-cat="cargo_vc" onclick="InboxView.filterCat('cargo_vc')">
|
| 20 |
+
<span class="cat-pill-dot" style="background:var(--blue)"></span> Cargo VC
|
| 21 |
+
</button>
|
| 22 |
+
<button class="cat-pill" data-cat="cargo_tc" onclick="InboxView.filterCat('cargo_tc')">
|
| 23 |
+
<span class="cat-pill-dot" style="background:var(--purple)"></span> Cargo TC
|
| 24 |
+
</button>
|
| 25 |
+
</div>
|
| 26 |
+
|
| 27 |
+
<div class="table-card">
|
| 28 |
+
<div class="table-toolbar">
|
| 29 |
+
<div class="search-box">
|
| 30 |
+
<span class="search-icon">⌕</span>
|
| 31 |
+
<input type="text" class="search-input" id="inbox-search"
|
| 32 |
+
placeholder="Search emails…" oninput="InboxView.onSearch(this.value)" />
|
| 33 |
+
</div>
|
| 34 |
+
<span class="td-muted" id="inbox-count" style="font-size:13px"></span>
|
| 35 |
+
</div>
|
| 36 |
+
|
| 37 |
+
<div class="table-wrapper">
|
| 38 |
+
<table>
|
| 39 |
+
<thead><tr>
|
| 40 |
+
<th>#</th>
|
| 41 |
+
<th>Subject</th>
|
| 42 |
+
<th>Sender</th>
|
| 43 |
+
<th>Category</th>
|
| 44 |
+
<th>Confidence</th>
|
| 45 |
+
<th>Received</th>
|
| 46 |
+
<th>Actions</th>
|
| 47 |
+
</tr></thead>
|
| 48 |
+
<tbody id="inbox-body">
|
| 49 |
+
<tr><td colspan="7"><div class="loading-spinner"><div class="spinner"></div></div></td></tr>
|
| 50 |
+
</tbody>
|
| 51 |
+
</table>
|
| 52 |
+
</div>
|
| 53 |
+
<div class="pagination" id="inbox-pagination"></div>
|
| 54 |
+
</div>
|
| 55 |
+
</div>`;
|
| 56 |
+
},
|
| 57 |
+
|
| 58 |
+
async init() {
|
| 59 |
+
this._page = 1;
|
| 60 |
+
this._category = '';
|
| 61 |
+
this._search = '';
|
| 62 |
+
await this.load();
|
| 63 |
+
},
|
| 64 |
+
|
| 65 |
+
async load() {
|
| 66 |
+
try {
|
| 67 |
+
const data = await API.emails({
|
| 68 |
+
page: this._page,
|
| 69 |
+
per_page: this._perPage,
|
| 70 |
+
category: this._category,
|
| 71 |
+
search: this._search,
|
| 72 |
+
});
|
| 73 |
+
this._total = data.total;
|
| 74 |
+
this._render(data.emails, data.total);
|
| 75 |
+
} catch (e) {
|
| 76 |
+
Toast.show('Failed to load emails: ' + e.message, 'error');
|
| 77 |
+
}
|
| 78 |
+
},
|
| 79 |
+
|
| 80 |
+
_render(emails, total) {
|
| 81 |
+
const start = (this._page - 1) * this._perPage + 1;
|
| 82 |
+
const end = Math.min(this._page * this._perPage, total);
|
| 83 |
+
document.getElementById('inbox-count').textContent =
|
| 84 |
+
total ? `Showing ${start}–${end} of ${total}` : 'No results';
|
| 85 |
+
|
| 86 |
+
const tbody = document.getElementById('inbox-body');
|
| 87 |
+
if (!emails.length) {
|
| 88 |
+
tbody.innerHTML = `<tr><td colspan="7">
|
| 89 |
+
<div class="empty-state">
|
| 90 |
+
<div class="empty-icon">✉</div>
|
| 91 |
+
<div class="empty-text">No emails found</div>
|
| 92 |
+
<div class="empty-sub">Try a different filter or process a new email</div>
|
| 93 |
+
</div></td></tr>`;
|
| 94 |
+
} else {
|
| 95 |
+
tbody.innerHTML = emails.map(e => `
|
| 96 |
+
<tr>
|
| 97 |
+
<td class="td-muted td-mono">#${e.id}</td>
|
| 98 |
+
<td style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
|
| 99 |
+
title="${htmlEsc(e.subject||'')}">${htmlEsc(e.subject || 'No Subject')}</td>
|
| 100 |
+
<td class="td-muted" style="font-size:12px">${htmlEsc(e.sender || '—')}</td>
|
| 101 |
+
<td><span class="badge badge-${e.category}">${catLabel(e.category)}</span></td>
|
| 102 |
+
<td><span class="conf-pill">${(e.confidence*100).toFixed(0)}%</span></td>
|
| 103 |
+
<td class="td-muted">${fmtDate(e.created_at)}</td>
|
| 104 |
+
<td>
|
| 105 |
+
<div class="action-cell">
|
| 106 |
+
<button class="btn btn-ghost btn-sm btn-icon-only" title="View raw"
|
| 107 |
+
onclick="InboxView.viewRaw(${e.id},'${htmlEsc(e.subject||'Email')}')">👁</button>
|
| 108 |
+
<button class="btn btn-danger btn-sm btn-icon-only" title="Delete"
|
| 109 |
+
onclick="InboxView.deleteEmail(${e.id})">🗑</button>
|
| 110 |
+
</div>
|
| 111 |
+
</td>
|
| 112 |
+
</tr>`).join('');
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
// Pagination
|
| 116 |
+
const pages = Math.ceil(total / this._perPage);
|
| 117 |
+
const pg = document.getElementById('inbox-pagination');
|
| 118 |
+
if (pages <= 1) { pg.innerHTML = ''; return; }
|
| 119 |
+
pg.innerHTML = `
|
| 120 |
+
<span>${total} total</span>
|
| 121 |
+
<div class="pagination-controls">
|
| 122 |
+
<button class="page-btn" ${this._page<=1?'disabled':''} onclick="InboxView.goPage(${this._page-1})">‹</button>
|
| 123 |
+
${Array.from({length:Math.min(pages,7)},(_,i)=>{
|
| 124 |
+
const p=i+1;
|
| 125 |
+
return `<button class="page-btn ${p===this._page?'active':''}" onclick="InboxView.goPage(${p})">${p}</button>`;
|
| 126 |
+
}).join('')}
|
| 127 |
+
<button class="page-btn" ${this._page>=pages?'disabled':''} onclick="InboxView.goPage(${this._page+1})">›</button>
|
| 128 |
+
</div>`;
|
| 129 |
+
},
|
| 130 |
+
|
| 131 |
+
filterCat(cat) {
|
| 132 |
+
this._category = cat;
|
| 133 |
+
this._page = 1;
|
| 134 |
+
document.querySelectorAll('#cat-bar .cat-pill').forEach(el => {
|
| 135 |
+
el.className = 'cat-pill' + (el.dataset.cat === cat ? ` active-${cat||'all'}` : '');
|
| 136 |
+
});
|
| 137 |
+
this.load();
|
| 138 |
+
},
|
| 139 |
+
|
| 140 |
+
onSearch: debounce(function(val) {
|
| 141 |
+
InboxView._search = val;
|
| 142 |
+
InboxView._page = 1;
|
| 143 |
+
InboxView.load();
|
| 144 |
+
}, 350),
|
| 145 |
+
|
| 146 |
+
goPage(p) { this._page = p; this.load(); },
|
| 147 |
+
|
| 148 |
+
async viewRaw(id, subject) {
|
| 149 |
+
try {
|
| 150 |
+
const email = await API.emailById(id);
|
| 151 |
+
|
| 152 |
+
let parsedHtml = '';
|
| 153 |
+
if (email.tonnage && email.tonnage.length > 0) {
|
| 154 |
+
parsedHtml += email.tonnage.map(t => `
|
| 155 |
+
<div class="parsed-record-card tonnage">
|
| 156 |
+
<div class="parsed-record-title">🚢 Vessel: ${htmlEsc(t.vessel_name)}</div>
|
| 157 |
+
<div class="parsed-field-grid">
|
| 158 |
+
<div class="parsed-field"><label>Size</label><span class="mono">${htmlEsc(t.vessel_size || '—')}</span></div>
|
| 159 |
+
<div class="parsed-field"><label>Open Port</label><span>${htmlEsc(t.open_port || '—')}</span></div>
|
| 160 |
+
<div class="parsed-field"><label>Open Date</label><span>${htmlEsc(t.open_date || '—')}</span></div>
|
| 161 |
+
<div class="parsed-field"><label>Type</label><span>${htmlEsc(t.vessel_type || '—')}</span></div>
|
| 162 |
+
<div class="parsed-field"><label>Flag</label><span>${htmlEsc(t.flag || '—')}</span></div>
|
| 163 |
+
<div class="parsed-field"><label>Built</label><span class="mono">${htmlEsc(t.built_year || '—')}</span></div>
|
| 164 |
+
</div>
|
| 165 |
+
</div>`).join('');
|
| 166 |
+
}
|
| 167 |
+
if (email.cargo_vc && email.cargo_vc.length > 0) {
|
| 168 |
+
parsedHtml += email.cargo_vc.map(c => `
|
| 169 |
+
<div class="parsed-record-card cargo_vc">
|
| 170 |
+
<div class="parsed-record-title">📦 Voyage Cargo: ${htmlEsc(c.cargo_name || 'Bulk Cargo')}</div>
|
| 171 |
+
<div class="parsed-field-grid">
|
| 172 |
+
<div class="parsed-field"><label>Quantity</label><span class="mono">${htmlEsc(c.quantity || '—')}</span></div>
|
| 173 |
+
<div class="parsed-field"><label>Load Port</label><span>${htmlEsc(c.loading_port || '—')}</span></div>
|
| 174 |
+
<div class="parsed-field"><label>Disch Port</label><span>${htmlEsc(c.discharge_port || '—')}</span></div>
|
| 175 |
+
<div class="parsed-field"><label>Laycan</label><span>${htmlEsc(c.laycan || '—')}</span></div>
|
| 176 |
+
<div class="parsed-field"><label>Type</label><span>${htmlEsc(c.cargo_type || '—')}</span></div>
|
| 177 |
+
</div>
|
| 178 |
+
</div>`).join('');
|
| 179 |
+
}
|
| 180 |
+
if (email.cargo_tc && email.cargo_tc.length > 0) {
|
| 181 |
+
parsedHtml += email.cargo_tc.map(c => `
|
| 182 |
+
<div class="parsed-record-card cargo_tc">
|
| 183 |
+
<div class="parsed-record-title">⏱ Time Charter: ${htmlEsc(c.cargo_name || 'TCT Requirement')}</div>
|
| 184 |
+
<div class="parsed-field-grid">
|
| 185 |
+
<div class="parsed-field"><label>Delivery</label><span>${htmlEsc(c.delivery_port || '—')}</span></div>
|
| 186 |
+
<div class="parsed-field"><label>Redelivery</label><span>${htmlEsc(c.redelivery_port || '—')}</span></div>
|
| 187 |
+
<div class="parsed-field"><label>Duration</label><span class="mono">${htmlEsc(c.duration || '—')}</span></div>
|
| 188 |
+
<div class="parsed-field"><label>Laycan</label><span>${htmlEsc(c.laycan || '—')}</span></div>
|
| 189 |
+
<div class="parsed-field"><label>Type</label><span>${htmlEsc(c.cargo_type || '—')}</span></div>
|
| 190 |
+
</div>
|
| 191 |
+
</div>`).join('');
|
| 192 |
+
}
|
| 193 |
+
if (!parsedHtml) {
|
| 194 |
+
parsedHtml = `
|
| 195 |
+
<div class="empty-state" style="padding: 24px 0">
|
| 196 |
+
<div class="empty-icon">📭</div>
|
| 197 |
+
<div class="empty-text" style="font-size:13px">No records extracted</div>
|
| 198 |
+
<div class="empty-sub">This email was classified but no fields were matched by regex.</div>
|
| 199 |
+
</div>`;
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
// If this email is a duplicate, add info about the original email it duplicated
|
| 203 |
+
let dupInfoHtml = '';
|
| 204 |
+
if (email.is_duplicate) {
|
| 205 |
+
dupInfoHtml = `
|
| 206 |
+
<div class="duplicate-warning" style="margin: 0 0 16px 0; display: block;">
|
| 207 |
+
⚠ Duplicate of previous email.
|
| 208 |
+
</div>`;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
const modal = document.createElement('div');
|
| 212 |
+
modal.className = 'modal-overlay open';
|
| 213 |
+
modal.innerHTML = `
|
| 214 |
+
<div class="modal" style="max-width:960px">
|
| 215 |
+
<div class="modal-header">
|
| 216 |
+
<h2 class="modal-title" style="font-size:15px">${htmlEsc(subject)}</h2>
|
| 217 |
+
<button class="modal-close" onclick="this.closest('.modal-overlay').remove()">✕</button>
|
| 218 |
+
</div>
|
| 219 |
+
<div class="modal-body" style="padding: 20px 24px;">
|
| 220 |
+
<div style="margin-bottom:16px;display:flex;gap:10px;align-items:center;flex-wrap:wrap">
|
| 221 |
+
<span class="badge badge-${email.category}">${catLabel(email.category)}</span>
|
| 222 |
+
<span class="conf-pill">${(email.confidence*100).toFixed(0)}% confidence</span>
|
| 223 |
+
<span class="td-muted" style="font-size:12px">From: ${htmlEsc(email.sender||'')}</span>
|
| 224 |
+
</div>
|
| 225 |
+
${dupInfoHtml}
|
| 226 |
+
<div class="modal-split">
|
| 227 |
+
<div class="modal-split-left">
|
| 228 |
+
<div class="modal-split-header">Raw Email Body</div>
|
| 229 |
+
<pre class="modal-raw-body-pre">${htmlEsc(email.raw_body||'')}</pre>
|
| 230 |
+
</div>
|
| 231 |
+
<div class="modal-split-right">
|
| 232 |
+
<div class="modal-split-header">Extracted Structured Data</div>
|
| 233 |
+
<div class="modal-parsed-panel">${parsedHtml}</div>
|
| 234 |
+
</div>
|
| 235 |
+
</div>
|
| 236 |
+
</div>
|
| 237 |
+
</div>`;
|
| 238 |
+
modal.onclick = e => { if (e.target === modal) modal.remove(); };
|
| 239 |
+
document.body.appendChild(modal);
|
| 240 |
+
} catch (e) {
|
| 241 |
+
Toast.show('Error loading email: ' + e.message, 'error');
|
| 242 |
+
}
|
| 243 |
+
},
|
| 244 |
+
|
| 245 |
+
async deleteEmail(id) {
|
| 246 |
+
if (!confirm('Delete this email and all its extracted data?')) return;
|
| 247 |
+
try {
|
| 248 |
+
await API.deleteEmail(id);
|
| 249 |
+
Toast.show('Email deleted', 'success');
|
| 250 |
+
this.load();
|
| 251 |
+
} catch (e) {
|
| 252 |
+
Toast.show('Delete failed: ' + e.message, 'error');
|
| 253 |
+
}
|
| 254 |
+
},
|
| 255 |
+
};
|
| 256 |
+
|
| 257 |
+
window.viewEmailSource = function(id, title) {
|
| 258 |
+
InboxView.viewRaw(id, title || 'Source Email');
|
| 259 |
+
};
|
static/js/views/matching.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* matching.js — Vessel ↔ Cargo matching engine view */
|
| 2 |
+
const MatchingView = {
|
| 3 |
+
_vessels: [],
|
| 4 |
+
_selectedVessel: null,
|
| 5 |
+
_mode: 'vc', // 'vc' | 'tc'
|
| 6 |
+
|
| 7 |
+
render() {
|
| 8 |
+
return `
|
| 9 |
+
<div class="fade-in">
|
| 10 |
+
<div class="two-col matching-layout">
|
| 11 |
+
|
| 12 |
+
<!-- LEFT: Vessel selector -->
|
| 13 |
+
<div>
|
| 14 |
+
<div class="section-header">
|
| 15 |
+
<h2 class="section-title">Open Vessels</h2>
|
| 16 |
+
<div class="mode-toggle" id="match-mode-toggle">
|
| 17 |
+
<button class="mode-btn active" id="mode-vc" onclick="MatchingView.setMode('vc')">vs Cargo VC</button>
|
| 18 |
+
<button class="mode-btn" id="mode-tc" onclick="MatchingView.setMode('tc')">vs Cargo TC</button>
|
| 19 |
+
</div>
|
| 20 |
+
</div>
|
| 21 |
+
<div class="table-card vessel-list" id="vessel-list">
|
| 22 |
+
<div class="loading-spinner"><div class="spinner"></div></div>
|
| 23 |
+
</div>
|
| 24 |
+
</div>
|
| 25 |
+
|
| 26 |
+
<!-- RIGHT: Match results -->
|
| 27 |
+
<div>
|
| 28 |
+
<div class="section-header">
|
| 29 |
+
<h2 class="section-title" id="match-title">Select a vessel to see matches</h2>
|
| 30 |
+
</div>
|
| 31 |
+
<div id="match-results">
|
| 32 |
+
<div class="empty-state" style="padding:48px 24px">
|
| 33 |
+
<div class="empty-icon">🔗</div>
|
| 34 |
+
<div class="empty-text">No vessel selected</div>
|
| 35 |
+
<div class="empty-sub">Click any vessel on the left to see ranked cargo matches</div>
|
| 36 |
+
</div>
|
| 37 |
+
</div>
|
| 38 |
+
</div>
|
| 39 |
+
|
| 40 |
+
</div>
|
| 41 |
+
</div>`;
|
| 42 |
+
},
|
| 43 |
+
|
| 44 |
+
async init() {
|
| 45 |
+
this._selectedVessel = null;
|
| 46 |
+
await this._loadVessels();
|
| 47 |
+
},
|
| 48 |
+
|
| 49 |
+
async _loadVessels() {
|
| 50 |
+
try {
|
| 51 |
+
const data = await API.tonnage({ per_page: 100 });
|
| 52 |
+
this._vessels = data.records || [];
|
| 53 |
+
this._renderVesselList();
|
| 54 |
+
} catch(e) {
|
| 55 |
+
Toast.show('Failed to load vessels: ' + e.message, 'error');
|
| 56 |
+
}
|
| 57 |
+
},
|
| 58 |
+
|
| 59 |
+
_renderVesselList() {
|
| 60 |
+
const el = document.getElementById('vessel-list');
|
| 61 |
+
if (!this._vessels.length) {
|
| 62 |
+
el.innerHTML = `<div class="empty-state"><div class="empty-icon">🚢</div><div class="empty-text">No vessel records yet</div></div>`;
|
| 63 |
+
return;
|
| 64 |
+
}
|
| 65 |
+
el.innerHTML = this._vessels.map(v => `
|
| 66 |
+
<div class="vessel-card ${this._selectedVessel === v.id ? 'selected' : ''}"
|
| 67 |
+
id="vessel-card-${v.id}"
|
| 68 |
+
onclick="MatchingView.selectVessel(${v.id})">
|
| 69 |
+
<div class="vessel-card-name">${htmlEsc(v.vessel_name || '—')}</div>
|
| 70 |
+
<div class="vessel-card-meta">
|
| 71 |
+
<span style="color:var(--blue)">${htmlEsc(v.open_port || '—')}</span>
|
| 72 |
+
<span class="td-muted">·</span>
|
| 73 |
+
<span class="td-muted">${htmlEsc(v.open_date || '—')}</span>
|
| 74 |
+
<span class="td-muted">·</span>
|
| 75 |
+
<span class="td-mono" style="font-size:11px">${htmlEsc(v.vessel_size || '—')}</span>
|
| 76 |
+
</div>
|
| 77 |
+
</div>`).join('');
|
| 78 |
+
},
|
| 79 |
+
|
| 80 |
+
setMode(mode) {
|
| 81 |
+
this._mode = mode;
|
| 82 |
+
document.getElementById('mode-vc').classList.toggle('active', mode === 'vc');
|
| 83 |
+
document.getElementById('mode-tc').classList.toggle('active', mode === 'tc');
|
| 84 |
+
if (this._selectedVessel) this.selectVessel(this._selectedVessel);
|
| 85 |
+
},
|
| 86 |
+
|
| 87 |
+
async selectVessel(id) {
|
| 88 |
+
this._selectedVessel = id;
|
| 89 |
+
// Highlight selection
|
| 90 |
+
document.querySelectorAll('.vessel-card').forEach(el => el.classList.remove('selected'));
|
| 91 |
+
const card = document.getElementById(`vessel-card-${id}`);
|
| 92 |
+
if (card) card.classList.add('selected');
|
| 93 |
+
|
| 94 |
+
const vessel = this._vessels.find(v => v.id === id);
|
| 95 |
+
const title = document.getElementById('match-title');
|
| 96 |
+
if (vessel) title.textContent = `Matches for ${vessel.vessel_name}`;
|
| 97 |
+
|
| 98 |
+
const resultsEl = document.getElementById('match-results');
|
| 99 |
+
resultsEl.innerHTML = `<div class="loading-spinner" style="height:120px"><div class="spinner"></div></div>`;
|
| 100 |
+
|
| 101 |
+
try {
|
| 102 |
+
const mode = this._mode === 'vc' ? 'tonnage_to_vc' : 'tonnage_to_tc';
|
| 103 |
+
const data = await API.matches({ mode, id });
|
| 104 |
+
const matches = data.matches || [];
|
| 105 |
+
this._renderMatches(matches, this._mode);
|
| 106 |
+
} catch(e) {
|
| 107 |
+
Toast.show('Match error: ' + e.message, 'error');
|
| 108 |
+
resultsEl.innerHTML = `<div class="empty-state"><div class="empty-text">Error loading matches</div></div>`;
|
| 109 |
+
}
|
| 110 |
+
},
|
| 111 |
+
|
| 112 |
+
_renderMatches(matches, mode) {
|
| 113 |
+
const el = document.getElementById('match-results');
|
| 114 |
+
if (!matches.length) {
|
| 115 |
+
el.innerHTML = `<div class="empty-state" style="padding:48px 24px">
|
| 116 |
+
<div class="empty-icon">📭</div>
|
| 117 |
+
<div class="empty-text">No cargo records to match against</div>
|
| 118 |
+
<div class="empty-sub">Process some cargo emails first</div>
|
| 119 |
+
</div>`;
|
| 120 |
+
return;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
el.innerHTML = `<div class="match-list">` + matches.map(m => {
|
| 124 |
+
const cargo = m.cargo_vc || m.cargo_tc;
|
| 125 |
+
const score = m.score;
|
| 126 |
+
const scoreClass = score >= 70 ? 'score-high' : score >= 40 ? 'score-mid' : 'score-low';
|
| 127 |
+
const scoreLabel = score >= 70 ? 'Strong' : score >= 40 ? 'Possible' : 'Weak';
|
| 128 |
+
|
| 129 |
+
const port = mode === 'vc'
|
| 130 |
+
? `<span style="color:var(--green)">${htmlEsc(cargo.loading_port || '—')}</span> → <span style="color:var(--gold)">${htmlEsc(cargo.discharge_port || '—')}</span>`
|
| 131 |
+
: `<span style="color:var(--green)">${htmlEsc(cargo.delivery_port || '—')}</span> → <span style="color:var(--gold)">${htmlEsc(cargo.redelivery_port || '—')}</span>`;
|
| 132 |
+
|
| 133 |
+
return `
|
| 134 |
+
<div class="match-card">
|
| 135 |
+
<div class="match-card-top">
|
| 136 |
+
<div>
|
| 137 |
+
<div class="match-cargo-name">${htmlEsc(cargo.cargo_name || 'Unknown Cargo')}</div>
|
| 138 |
+
<div class="match-ports">${port}</div>
|
| 139 |
+
<div class="match-meta td-muted">
|
| 140 |
+
Laycan: ${htmlEsc(cargo.laycan || '—')}
|
| 141 |
+
${mode === 'vc' && cargo.quantity ? ` · ${htmlEsc(cargo.quantity)}` : ''}
|
| 142 |
+
${mode === 'tc' && cargo.duration ? ` · ${htmlEsc(cargo.duration)}` : ''}
|
| 143 |
+
${cargo.account_name ? ` · ${htmlEsc(cargo.account_name)}` : ''}
|
| 144 |
+
</div>
|
| 145 |
+
</div>
|
| 146 |
+
<div class="match-score-block">
|
| 147 |
+
<div class="match-score ${scoreClass}">${score}</div>
|
| 148 |
+
<div class="match-score-label ${scoreClass}">${scoreLabel}</div>
|
| 149 |
+
</div>
|
| 150 |
+
</div>
|
| 151 |
+
<div class="match-score-bar-track">
|
| 152 |
+
<div class="match-score-bar ${scoreClass}" style="width:${score}%"></div>
|
| 153 |
+
</div>
|
| 154 |
+
</div>`;
|
| 155 |
+
}).join('') + '</div>';
|
| 156 |
+
},
|
| 157 |
+
};
|
static/js/views/tonnage.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* tonnage.js — Tonnage vessel records view */
|
| 2 |
+
const TonnageView = {
|
| 3 |
+
_page: 1, _total: 0, _perPage: 20, _search: '',
|
| 4 |
+
|
| 5 |
+
render() {
|
| 6 |
+
return `
|
| 7 |
+
<div class="fade-in">
|
| 8 |
+
<div class="table-card">
|
| 9 |
+
<div class="table-toolbar">
|
| 10 |
+
<div class="search-box">
|
| 11 |
+
<span class="search-icon">⌕</span>
|
| 12 |
+
<input type="text" class="search-input" id="tonnage-search"
|
| 13 |
+
placeholder="Search vessel or port…" oninput="TonnageView.onSearch(this.value)" />
|
| 14 |
+
</div>
|
| 15 |
+
<div style="display:flex;gap:8px;align-items:center">
|
| 16 |
+
<span class="td-muted" id="tonnage-count" style="font-size:13px"></span>
|
| 17 |
+
<button class="btn btn-ghost btn-sm" onclick="API.exportTonnage()" title="Export to CSV">⬇ Export CSV</button>
|
| 18 |
+
</div>
|
| 19 |
+
</div>
|
| 20 |
+
<div class="table-wrapper">
|
| 21 |
+
<table>
|
| 22 |
+
<thead><tr>
|
| 23 |
+
<th>Vessel Name</th>
|
| 24 |
+
<th>DWT / Size</th>
|
| 25 |
+
<th>Open Port</th>
|
| 26 |
+
<th>Open Date</th>
|
| 27 |
+
<th>Flag</th>
|
| 28 |
+
<th>Built</th>
|
| 29 |
+
<th>Type</th>
|
| 30 |
+
<th>Account</th>
|
| 31 |
+
<th>Actions</th>
|
| 32 |
+
</tr></thead>
|
| 33 |
+
<tbody id="tonnage-body">
|
| 34 |
+
<tr><td colspan="9"><div class="loading-spinner"><div class="spinner"></div></div></td></tr>
|
| 35 |
+
</tbody>
|
| 36 |
+
</table>
|
| 37 |
+
</div>
|
| 38 |
+
<div class="pagination" id="tonnage-pagination"></div>
|
| 39 |
+
</div>
|
| 40 |
+
</div>`;
|
| 41 |
+
},
|
| 42 |
+
|
| 43 |
+
async init() { this._page = 1; this._search = ''; await this.load(); },
|
| 44 |
+
|
| 45 |
+
async load() {
|
| 46 |
+
try {
|
| 47 |
+
const data = await API.tonnage({ page: this._page, per_page: this._perPage, search: this._search });
|
| 48 |
+
this._total = data.total;
|
| 49 |
+
this._render(data.records, data.total);
|
| 50 |
+
} catch (e) { Toast.show('Failed to load tonnage: ' + e.message, 'error'); }
|
| 51 |
+
},
|
| 52 |
+
|
| 53 |
+
_render(records, total) {
|
| 54 |
+
const start = (this._page-1)*this._perPage+1, end = Math.min(this._page*this._perPage,total);
|
| 55 |
+
document.getElementById('tonnage-count').textContent = total ? `${start}–${end} of ${total} vessels` : 'No results';
|
| 56 |
+
|
| 57 |
+
const tbody = document.getElementById('tonnage-body');
|
| 58 |
+
if (!records.length) {
|
| 59 |
+
tbody.innerHTML = `<tr><td colspan="9"><div class="empty-state">
|
| 60 |
+
<div class="empty-icon">🚢</div>
|
| 61 |
+
<div class="empty-text">No tonnage records yet</div>
|
| 62 |
+
<div class="empty-sub">Process a tonnage email to see vessel data here</div>
|
| 63 |
+
</div></td></tr>`;
|
| 64 |
+
} else {
|
| 65 |
+
tbody.innerHTML = records.map(r => `
|
| 66 |
+
<tr>
|
| 67 |
+
<td>
|
| 68 |
+
<span style="font-weight:600;color:var(--gold)">${htmlEsc(r.vessel_name||'—')}</span>
|
| 69 |
+
${r.class_society ? `<br><span class="td-muted" style="font-size:11px">${htmlEsc(r.class_society)}</span>` : ''}
|
| 70 |
+
</td>
|
| 71 |
+
<td class="td-mono">${htmlEsc(r.vessel_size||'—')}</td>
|
| 72 |
+
<td>
|
| 73 |
+
<span style="color:var(--blue)">${htmlEsc(r.open_port||'—')}</span>
|
| 74 |
+
</td>
|
| 75 |
+
<td class="td-muted">${htmlEsc(r.open_date||'—')}</td>
|
| 76 |
+
<td class="td-muted">${htmlEsc(r.flag||'—')}</td>
|
| 77 |
+
<td class="td-mono">${htmlEsc(r.built_year||'—')}</td>
|
| 78 |
+
<td><span style="font-size:12px;color:var(--text-secondary)">${htmlEsc(r.vessel_type||'—')}</span></td>
|
| 79 |
+
<td class="td-muted" style="font-size:12px;max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
|
| 80 |
+
title="${htmlEsc(r.account_name||'')}">${htmlEsc(r.account_name||'—')}</td>
|
| 81 |
+
<td>
|
| 82 |
+
<div class="action-cell">
|
| 83 |
+
<button class="btn btn-ghost btn-sm btn-icon-only" title="View Source Email" onclick="viewEmailSource(${r.email_id}, '${htmlEsc(r.vessel_name || 'Vessel')}')">✉</button>
|
| 84 |
+
<button class="btn btn-ghost btn-sm btn-icon-only" title="Edit" onclick="TonnageView.edit(${r.id})">✎</button>
|
| 85 |
+
<button class="btn btn-danger btn-sm btn-icon-only" title="Delete" onclick="TonnageView.delete(${r.id})">🗑</button>
|
| 86 |
+
</div>
|
| 87 |
+
</td>
|
| 88 |
+
</tr>`).join('');
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
const pages = Math.ceil(total/this._perPage);
|
| 92 |
+
const pg = document.getElementById('tonnage-pagination');
|
| 93 |
+
if (pages <= 1) { pg.innerHTML=''; return; }
|
| 94 |
+
pg.innerHTML = `
|
| 95 |
+
<span>${total} total</span>
|
| 96 |
+
<div class="pagination-controls">
|
| 97 |
+
<button class="page-btn" ${this._page<=1?'disabled':''} onclick="TonnageView.goPage(${this._page-1})">‹</button>
|
| 98 |
+
${Array.from({length:Math.min(pages,7)},(_,i)=>`
|
| 99 |
+
<button class="page-btn ${i+1===this._page?'active':''}" onclick="TonnageView.goPage(${i+1})">${i+1}</button>`).join('')}
|
| 100 |
+
<button class="page-btn" ${this._page>=pages?'disabled':''} onclick="TonnageView.goPage(${this._page+1})">›</button>
|
| 101 |
+
</div>`;
|
| 102 |
+
},
|
| 103 |
+
|
| 104 |
+
onSearch: debounce(function(v){ TonnageView._search=v; TonnageView._page=1; TonnageView.load(); }, 350),
|
| 105 |
+
goPage(p) { this._page=p; this.load(); },
|
| 106 |
+
|
| 107 |
+
edit(id) {
|
| 108 |
+
// Find record in DOM — re-fetch via API is cleaner
|
| 109 |
+
API.get(`/tonnage/${id}`).then(r => {
|
| 110 |
+
const fields = [
|
| 111 |
+
['vessel_name','Vessel Name',r.vessel_name],
|
| 112 |
+
['open_port','Open Port',r.open_port],
|
| 113 |
+
['open_date','Open Date',r.open_date],
|
| 114 |
+
['vessel_size','Vessel Size (DWT)',r.vessel_size],
|
| 115 |
+
['vessel_type','Vessel Type',r.vessel_type],
|
| 116 |
+
['flag','Flag',r.flag],
|
| 117 |
+
['built_year','Built Year',r.built_year],
|
| 118 |
+
['account_name','Account',r.account_name],
|
| 119 |
+
];
|
| 120 |
+
showEditModal('Edit Tonnage Record', fields, async (form) => {
|
| 121 |
+
await API.updateTonnage(id, form);
|
| 122 |
+
Toast.show('Record updated', 'success');
|
| 123 |
+
TonnageView.load();
|
| 124 |
+
});
|
| 125 |
+
}).catch(e => Toast.show('Error: '+e.message,'error'));
|
| 126 |
+
},
|
| 127 |
+
|
| 128 |
+
async delete(id) {
|
| 129 |
+
if (!confirm('Delete this tonnage record?')) return;
|
| 130 |
+
try { await API.deleteTonnage(id); Toast.show('Deleted','success'); this.load(); }
|
| 131 |
+
catch(e) { Toast.show('Error: '+e.message,'error'); }
|
| 132 |
+
},
|
| 133 |
+
};
|
tests/test_pipeline.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import pytest
|
| 3 |
+
from classification.classifier import classify
|
| 4 |
+
from extraction.tonnage_extractor import extract_tonnage
|
| 5 |
+
from extraction.cargo_vc_extractor import extract_cargo_vc
|
| 6 |
+
from extraction.cargo_tc_extractor import extract_cargo_tc
|
| 7 |
+
from routes.matching import _port_score, _size_score, _date_score
|
| 8 |
+
from routes.emails import _fingerprint
|
| 9 |
+
|
| 10 |
+
def test_classifier():
|
| 11 |
+
# Tonnage text
|
| 12 |
+
tonnage_text = "OUR DIRECT OWS OPEN AS FOLLOWS: MV SARONIC CHAMPION DWT 93000 OPEN VUNG ANG 08-12 JUNE"
|
| 13 |
+
cat, conf = classify(tonnage_text)
|
| 14 |
+
assert cat == "tonnage"
|
| 15 |
+
assert conf > 0.4
|
| 16 |
+
|
| 17 |
+
# Cargo VC text
|
| 18 |
+
vc_text = "LOAD PORT: KOH SI CHANG, DISCHARGE PORT: KANDLA, LAYCAN: MID JULY, 20000 MTS COAL"
|
| 19 |
+
cat, conf = classify(vc_text)
|
| 20 |
+
assert cat == "cargo_vc"
|
| 21 |
+
|
| 22 |
+
# Cargo TC text
|
| 23 |
+
tc_text = "A/C SeaSchiffe, 1 TCT with Steels, Delivery: ECI, Laycan: 15-18 July, Redel: Med"
|
| 24 |
+
cat, conf = classify(tc_text)
|
| 25 |
+
assert cat == "cargo_tc"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_tonnage_extractor():
|
| 29 |
+
text = "MV SARONIC CHAMPION DWT 93000 OPEN VUNG ANG O/A 08-12 JUNE"
|
| 30 |
+
vessels = extract_tonnage(text, 1)
|
| 31 |
+
assert len(vessels) == 1
|
| 32 |
+
v = vessels[0]
|
| 33 |
+
assert v["vessel_name"] == "SARONIC CHAMPION"
|
| 34 |
+
assert "93000" in v["vessel_size"]
|
| 35 |
+
assert v["open_port"] == "VUNG ANG"
|
| 36 |
+
assert v["open_date"] == "08-12 JUNE"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_cargo_vc_extractor():
|
| 40 |
+
text = """
|
| 41 |
+
15,000 - 20,000 MTS COAL
|
| 42 |
+
LOAD PORT: KOH SI CHANG
|
| 43 |
+
DISCHARGE PORT: KANDLA
|
| 44 |
+
LAYCAN: MID JULY 2026
|
| 45 |
+
"""
|
| 46 |
+
cargos = extract_cargo_vc(text, 1)
|
| 47 |
+
assert len(cargos) == 1
|
| 48 |
+
c = cargos[0]
|
| 49 |
+
assert c["cargo_name"] == "COAL"
|
| 50 |
+
assert c["loading_port"] == "KOH SI CHANG"
|
| 51 |
+
assert c["discharge_port"] == "KANDLA"
|
| 52 |
+
assert c["laycan"] == "MID JULY 2026"
|
| 53 |
+
assert "15,000" in c["quantity"]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_cargo_tc_extractor():
|
| 57 |
+
text = """
|
| 58 |
+
* Delivery: ECI
|
| 59 |
+
* Laycan: 15-18 July
|
| 60 |
+
* Redel: Med via GOA
|
| 61 |
+
* Duration: abt 35-40 days wog
|
| 62 |
+
* 1 TCT with Steels
|
| 63 |
+
"""
|
| 64 |
+
cargos = extract_cargo_tc(text, 1)
|
| 65 |
+
assert len(cargos) == 1
|
| 66 |
+
c = cargos[0]
|
| 67 |
+
assert c["delivery_port"] == "ECI"
|
| 68 |
+
assert c["redelivery_port"] == "Med via GOA"
|
| 69 |
+
assert c["duration"] == "35-40 days"
|
| 70 |
+
assert c["laycan"] == "15-18 July"
|
| 71 |
+
assert c["cargo_name"] == "Steels"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_matching_scores():
|
| 75 |
+
# Exact port match
|
| 76 |
+
assert _port_score("Kandla", "Kandla") == 50
|
| 77 |
+
# Token prefix match
|
| 78 |
+
assert _port_score("Kandla Port", "Kandla") == 35
|
| 79 |
+
|
| 80 |
+
# Size score
|
| 81 |
+
assert _size_score("50000 DWT", "45000 MTS") == 20
|
| 82 |
+
|
| 83 |
+
# Date score
|
| 84 |
+
assert _date_score("OPEN XIAMEN O/A 2ND JUNE 2026", "LC 10-17 JUNE") == 30
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_deduplication():
|
| 88 |
+
t1 = "Hello, this is a test email body for deduplication checking."
|
| 89 |
+
t2 = "hello, this is a test email body for deduplication checking. "
|
| 90 |
+
assert _fingerprint(t1) == _fingerprint(t2)
|