File size: 14,046 Bytes
1b4b6d2
369b6c9
1b4b6d2
369b6c9
 
 
 
 
1b4b6d2
 
 
369b6c9
 
1b4b6d2
369b6c9
 
 
 
 
 
 
1b4b6d2
 
369b6c9
 
 
1b4b6d2
 
369b6c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
369b6c9
1b4b6d2
 
369b6c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
369b6c9
1b4b6d2
369b6c9
1b4b6d2
369b6c9
 
1b4b6d2
369b6c9
1b4b6d2
 
fa156f3
 
 
 
 
 
70d9304
 
fa156f3
 
 
 
 
 
0f63461
 
fa156f3
 
 
 
70d9304
fa156f3
 
 
 
 
 
 
 
 
 
369b6c9
 
 
 
 
 
 
 
 
 
 
 
41dd6f3
bf94a94
 
41dd6f3
369b6c9
41dd6f3
 
369b6c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41dd6f3
369b6c9
 
 
 
 
 
 
41dd6f3
369b6c9
 
41dd6f3
 
369b6c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41dd6f3
 
369b6c9
 
 
 
 
 
 
 
 
 
 
 
 
fa156f3
 
 
369b6c9
 
 
 
 
 
 
 
 
 
1b4b6d2
 
369b6c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b4b6d2
 
 
 
369b6c9
 
 
1b4b6d2
 
369b6c9
 
 
1b4b6d2
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import React, { useState, useEffect } from 'react';
import { Folder, Calendar, ArrowRight, Trash2, FileSpreadsheet, LayoutList, CheckCircle2, Clock } from 'lucide-react';

export default function Projects({ token, isArabic, onSelectProject, onNavigate, initialTab }) {
  const [activeTab, setActiveTab] = useState(initialTab || 'qto');
  const [qtoProjects, setQtoProjects] = useState([]);
  const [progProjects, setProgProjects] = useState([]);
  const [cfProjects, setCfProjects] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setActiveTab(initialTab || 'qto');
  }, [initialTab]);

  useEffect(() => {
    if (activeTab === 'qto' && qtoProjects.length === 0) fetchQto();
    else if (activeTab === 'programme' && progProjects.length === 0) fetchProg();
    else if (activeTab === 'cashflow' && cfProjects.length === 0) fetchCf();
  }, [activeTab]);

  const fetchQto = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/projects", { headers: { 'Authorization': `Bearer ${token}` } });
      if (res.ok) setQtoProjects(await res.json());
    } catch (err) { console.error(err); } finally { setLoading(false); }
  };

  const fetchProg = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/modules/programme", { headers: { 'Authorization': `Bearer ${token}` } });
      if (res.ok) setProgProjects(await res.json());
    } catch (err) { console.error(err); } finally { setLoading(false); }
  };

  const fetchCf = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/modules/cashflow", { headers: { 'Authorization': `Bearer ${token}` } });
      if (res.ok) setCfProjects(await res.json());
    } catch (err) { console.error(err); } finally { setLoading(false); }
  };

  const handleDeleteQto = async (id, e) => {
    e.stopPropagation();
    if (!confirm(isArabic ? 'هل أنت متأكد من رغبتك في حذف هذا المشروع نهائياً؟' : 'Are you sure you want to delete this project permanently?')) return;
    try {
      const res = await fetch(`/api/projects/${id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` } });
      if (res.ok) setQtoProjects(prev => prev.filter(p => p.id !== id));
    } catch (err) { console.error(err); }
  };

  const handleDeleteModule = async (feature, id, e) => {
    e.stopPropagation();
    if (!confirm(isArabic ? 'هل أنت متأكد؟' : 'Are you sure?')) return;
    try {
      const res = await fetch(`/api/modules/${feature}/item/${id}`, { method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` } });
      if (res.ok) {
        if (feature === 'programme') setProgProjects(prev => prev.filter(p => p.id !== id));
        else setCfProjects(prev => prev.filter(p => p.id !== id));
      }
    } catch (err) { console.error(err); }
  };

  const handleLoadModule = async (feature, id) => {
    try {
      const res = await fetch(`/api/modules/${feature}/item/${id}`, { headers: { Authorization: `Bearer ${token}` } });
      if (res.ok) {
        const data = await res.json();
        onNavigate(feature, { loadData: { id: data.id, config: data.config } });
      }
    } catch (err) { console.error(err); }
  };

  const handleExportModuleExcel = async (feature, id, e) => {
    e.stopPropagation();
    // Default configs for fallback
    const DEFAULT_CFG = {
      buaPerFloor: 400, complexityFactor: 1.0, hasPool: false, hasDemolition: false,
      contractValueAed: 1500000, advancePaymentPct: 10, retentionPct: 10, retentionReleaseAtCompletionPct: 50,
      vatPct: 5, certificationPeriodDays: 30, paymentPeriodDays: 30, defectsLiabilityMonths: 12, contractorCostRatio: 0.85,
      startISO: new Date().toISOString().split('T')[0]
    };
    try {
      const res = await fetch(`/api/modules/${feature}/item/${id}`, { headers: { Authorization: `Bearer ${token}` } });
      if (res.ok) {
        const data = await res.json();
        const cfg = { ...DEFAULT_CFG, ...data.config };
        const { buildActivityList } = await import('../engine/durationEngine');
        const { runScheduler } = await import('../engine/scheduler');
        const acts = buildActivityList(cfg);
        const out = runScheduler(cfg, acts);
        if (feature === 'programme') {
          const mod = await import('../engine/programmeExcel');
          mod.exportProgrammeToExcel(out, cfg.projectName || 'Project');
        } else {
          const { computeCashFlow } = await import('../engine/cashflow');
          const resObj = computeCashFlow(cfg, out.monthly);
          const mod = await import('../engine/cashflowExcel');
          mod.exportCashFlowToExcel(cfg, resObj, cfg.projectName || 'Project');
        }
      }
    } catch (err) { console.error(err); }
  };

  const renderQto = () => (
    loading && qtoProjects.length === 0 ? (
      <div style={{ textAlign: 'center', padding: '40px' }}>
        <div className="spin-anim" style={{ width: '30px', height: '30px', border: '3px solid var(--border-color)', borderTopColor: 'var(--primary)', borderRadius: '50%', margin: '0 auto 10px' }}></div>
        <p>{isArabic ? 'جاري جلب المشاريع...' : 'Fetching projects history...'}</p>
      </div>
    ) : qtoProjects.length === 0 ? (
      <div style={{ textAlign: 'center', padding: '50px', backgroundColor: 'var(--bg-secondary)', borderRadius: '12px', border: '1px solid var(--border-color)' }}>
        <p style={{ color: 'var(--text-secondary)' }}>{isArabic ? 'لا توجد مشاريع سابقة حالياً.' : 'No previous projects found.'}</p>
      </div>
    ) : (
      <div style={{ display: 'flex', flexDirection: 'column', gap: '15px' }}>
        {qtoProjects.map((proj) => {
          const step = proj.current_step || 8;
          const isDone = step >= 7;
          return (
          <div 
            key={proj.id} className="glass-card" onClick={isDone ? undefined : () => { onSelectProject(proj); onNavigate('workflow'); }}
            style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: isDone ? 'default' : 'pointer' }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
              <div style={{ width: '45px', height: '45px', borderRadius: '10px', backgroundColor: 'rgba(59, 130, 246, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--primary)' }}>
                <Folder size={22} />
              </div>
              <div>
                <h4 style={{ fontSize: '1.05rem', fontWeight: 700, color: 'var(--text-primary)' }}>{proj.name}</h4>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginTop: '4px', fontSize: '0.85rem', color: 'var(--text-muted)' }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}><Calendar size={12} /> {proj.date}</span>
                  <span>•</span>
                  <span>{isArabic ? `الخطوة ${proj.current_step || 8} من 8` : `Step ${proj.current_step || 8} of 8`}</span>
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
              {isDone && (
                <button className="btn btn-secondary" onClick={(e) => { e.stopPropagation(); window.open(`/api/workflow/export/excel?project_id=${proj.id}&Authorization=Bearer ${token}`); }} style={{ padding: '8px', borderRadius: '50%', color: 'var(--success)', borderColor: 'transparent' }} title={isArabic ? "تحميل إكسل" : "Download Excel"}>
                  <FileSpreadsheet size={18} />
                </button>
              )}
              <button className="btn btn-secondary" onClick={(e) => handleDeleteQto(proj.id, e)} style={{ padding: '8px', borderRadius: '50%', color: 'var(--error)', borderColor: 'transparent' }}>
                <Trash2 size={16} />
              </button>
              {!isDone && <ArrowRight size={18} color="var(--text-muted)" style={{ transform: isArabic ? 'rotate(180deg)' : 'none' }} />}
            </div>
          </div>
          );
        })}
      </div>
    )
  );

  const renderModule = (items, feature) => (
    loading && items.length === 0 ? (
      <div style={{ textAlign: 'center', padding: '40px' }}>
        <div className="spin-anim" style={{ width: '30px', height: '30px', border: '3px solid var(--border-color)', borderTopColor: 'var(--primary)', borderRadius: '50%', margin: '0 auto 10px' }}></div>
        <p>{isArabic ? 'جاري جلب المشاريع...' : 'Fetching projects history...'}</p>
      </div>
    ) : items.length === 0 ? (
      <div style={{ textAlign: 'center', padding: '50px', backgroundColor: 'var(--bg-secondary)', borderRadius: '12px', border: '1px solid var(--border-color)' }}>
        <p style={{ color: 'var(--text-secondary)' }}>{isArabic ? 'لا توجد مشاريع سابقة حالياً.' : 'No previous projects found.'}</p>
      </div>
    ) : (
      <div style={{ display: 'flex', flexDirection: 'column', gap: '15px' }}>
        {items.map((proj) => (
          <div 
            key={proj.id} className="glass-card"
            style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
              <div style={{ width: '45px', height: '45px', borderRadius: '10px', backgroundColor: feature === 'programme' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(245, 158, 11, 0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: feature === 'programme' ? 'var(--success)' : 'var(--warning)' }}>
                {feature === 'programme' ? <Clock size={22} /> : <CheckCircle2 size={22} />}
              </div>
              <div>
                <h4 style={{ fontSize: '1.05rem', fontWeight: 700, color: 'var(--text-primary)' }}>{proj.name}</h4>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginTop: '4px', fontSize: '0.85rem', color: 'var(--text-muted)' }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}><Calendar size={12} /> {proj.date}</span>
                </div>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
              <button className="btn btn-secondary" onClick={(e) => handleExportModuleExcel(feature, proj.id, e)} style={{ padding: '8px', borderRadius: '50%', color: 'var(--success)', borderColor: 'transparent' }} title={isArabic ? "تحميل إكسل" : "Download Excel"}>
                <FileSpreadsheet size={18} />
              </button>
              <button className="btn btn-secondary" onClick={(e) => handleDeleteModule(feature, proj.id, e)} style={{ padding: '8px', borderRadius: '50%', color: 'var(--error)', borderColor: 'transparent' }}>
                <Trash2 size={16} />
              </button>
            </div>
          </div>
        ))}
      </div>
    )
  );

  return (
    <div style={{ padding: '30px', textAlign: isArabic ? 'right' : 'left', direction: isArabic ? 'rtl' : 'ltr' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
        
        {/* Tabs */}
        <div style={{ display: 'flex', gap: '10px', overflowX: 'auto', paddingBottom: '10px' }}>
          <button 
            className={`btn ${activeTab === 'qto' ? 'btn-primary' : 'btn-secondary'}`}
            onClick={() => setActiveTab('qto')}
            style={{ display: 'flex', alignItems: 'center', gap: '8px', borderRadius: '8px', padding: '10px 20px', whiteSpace: 'nowrap' }}
          >
            <LayoutList size={18} />
            {isArabic ? 'حصر الكميات (QTO)' : 'QTO History'}
          </button>
          <button 
            className={`btn ${activeTab === 'programme' ? 'btn-primary' : 'btn-secondary'}`}
            onClick={() => setActiveTab('programme')}
            style={{ display: 'flex', alignItems: 'center', gap: '8px', borderRadius: '8px', padding: '10px 20px', whiteSpace: 'nowrap', backgroundColor: activeTab === 'programme' ? 'var(--success)' : undefined, color: activeTab === 'programme' ? '#fff' : undefined, borderColor: activeTab === 'programme' ? 'var(--success)' : undefined }}
          >
            <Clock size={18} />
            {isArabic ? 'جدول زمني' : 'Work Programme'}
          </button>
          <button 
            className={`btn ${activeTab === 'cashflow' ? 'btn-primary' : 'btn-secondary'}`}
            onClick={() => setActiveTab('cashflow')}
            style={{ display: 'flex', alignItems: 'center', gap: '8px', borderRadius: '8px', padding: '10px 20px', whiteSpace: 'nowrap', backgroundColor: activeTab === 'cashflow' ? 'var(--warning)' : undefined, color: activeTab === 'cashflow' ? '#fff' : undefined, borderColor: activeTab === 'cashflow' ? 'var(--warning)' : undefined }}
          >
            <CheckCircle2 size={18} />
            {isArabic ? 'التدفق النقدي' : 'Cash Flow'}
          </button>
        </div>

        {/* History List */}
        <div className="glass-panel" style={{ padding: '25px' }}>
          <h3 style={{ fontSize: '1.25rem', fontWeight: 700, marginBottom: '20px', display: 'flex', alignItems: 'center', gap: '10px' }}>
            <Folder size={20} color="var(--primary)" />
            {activeTab === 'qto' && (isArabic ? 'مشاريع حصر الكميات السابقة' : 'Takeoff History')}
            {activeTab === 'programme' && (isArabic ? 'تاريخ الجداول الزمنية' : 'Work Programme History')}
            {activeTab === 'cashflow' && (isArabic ? 'التدفقات النقدية السابقة' : 'Cash Flow History')}
          </h3>

          {activeTab === 'qto' && renderQto()}
          {activeTab === 'programme' && renderModule(progProjects, 'programme')}
          {activeTab === 'cashflow' && renderModule(cfProjects, 'cashflow')}
        </div>
      </div>
    </div>
  );
}