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32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
import os
import json
from datetime import datetime
from typing import Dict, List, Optional, Union

import docx
from docx.shared import Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE

import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from openpyxl.utils import get_column_letter

from sqlalchemy.orm import Session
from app.db.models import Document

# Doküman çıktı dizini
OUTPUT_DIR = os.path.join(os.getcwd(), 'uploads')
os.makedirs(OUTPUT_DIR, exist_ok=True)

def create_word_document(data: Dict, template_type: str = 'maliyet_raporu') -> str:
    """
    Verilen verilerle Word dokümanı oluşturur
    
    Args:
        data: Doküman içeriği için veriler
        template_type: Şablon türü (maliyet_raporu, teklif, vs.)
        
    Returns:
        Oluşturulan dosyanın yolu
    """
    doc = docx.Document()
    
    # Stil oluştur
    styles = doc.styles
    
    # Başlık stili
    if 'Başlık' not in styles:
        style = styles.add_style('Başlık', WD_STYLE_TYPE.PARAGRAPH)
        font = style.font
        font.name = 'Arial'
        font.size = Pt(16)
        font.bold = True
    
    # Alt başlık stili
    if 'Alt Başlık' not in styles:
        style = styles.add_style('Alt Başlık', WD_STYLE_TYPE.PARAGRAPH)
        font = style.font
        font.name = 'Arial'
        font.size = Pt(14)
        font.bold = True
    
    # Normal metin stili
    if 'Normal Metin' not in styles:
        style = styles.add_style('Normal Metin', WD_STYLE_TYPE.PARAGRAPH)
        font = style.font
        font.name = 'Arial'
        font.size = Pt(11)
    
    # Tablo başlık stili
    if 'Tablo Başlık' not in styles:
        style = styles.add_style('Tablo Başlık', WD_STYLE_TYPE.PARAGRAPH)
        font = style.font
        font.name = 'Arial'
        font.size = Pt(11)
        font.bold = True
    
    # Şablon türüne göre doküman oluştur
    if template_type == 'maliyet_raporu':
        _create_cost_report_word(doc, data)
    elif template_type == 'teklif':
        _create_offer_word(doc, data)
    else:
        # Varsayılan şablon
        _create_default_word(doc, data)
    
    # Dosyayı kaydet
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    filename = f"{timestamp}_{template_type}.docx"
    file_path = os.path.join(OUTPUT_DIR, filename)
    doc.save(file_path)
    
    return file_path

def _create_cost_report_word(doc, data):
    """
    Maliyet raporu Word dokümanı oluşturur
    """
    # Başlık
    heading = doc.add_paragraph("MALİYET RAPORU", style='Başlık')
    heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    # Tarih
    date_paragraph = doc.add_paragraph(f"Tarih: {datetime.now().strftime('%d.%m.%Y')}", style='Normal Metin')
    date_paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    
    doc.add_paragraph()
    
    # Proje bilgileri
    if 'proje_bilgileri' in data:
        doc.add_paragraph("PROJE BİLGİLERİ", style='Alt Başlık')
        for key, value in data['proje_bilgileri'].items():
            doc.add_paragraph(f"{key}: {value}", style='Normal Metin')
        doc.add_paragraph()
    
    # İşçilik maliyetleri
    if 'iscilik_maliyetleri' in data:
        doc.add_paragraph("İŞÇİLİK MALİYETLERİ", style='Alt Başlık')
        
        # Tablo oluştur
        table = doc.add_table(rows=1, cols=4)
        table.style = 'Table Grid'
        
        # Tablo başlıkları
        header_cells = table.rows[0].cells
        header_cells[0].text = "Pozisyon"
        header_cells[1].text = "Saat Ücreti (TL)"
        header_cells[2].text = "Süre (Saat)"
        header_cells[3].text = "Toplam (TL)"
        
        # Başlık hücrelerini kalın yap
        for cell in header_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True
        
        # Verileri tabloya ekle
        for item in data['iscilik_maliyetleri']:
            row_cells = table.add_row().cells
            row_cells[0].text = item.get('pozisyon', '')
            row_cells[1].text = str(item.get('saat_ucreti', 0))
            row_cells[2].text = str(item.get('sure', 0))
            row_cells[3].text = str(item.get('toplam', 0))
        
        # Toplam satırı
        if 'iscilik_toplam' in data:
            row_cells = table.add_row().cells
            row_cells[0].text = "TOPLAM"
            row_cells[0].merge(row_cells[2])
            row_cells[3].text = str(data['iscilik_toplam'])
            
            # Toplam satırını kalın yap
            for cell in [row_cells[0], row_cells[3]]:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.bold = True
        
        doc.add_paragraph()
    
    # Malzeme maliyetleri
    if 'malzeme_maliyetleri' in data:
        doc.add_paragraph("MALZEME MALİYETLERİ", style='Alt Başlık')
        
        # Tablo oluştur
        table = doc.add_table(rows=1, cols=5)
        table.style = 'Table Grid'
        
        # Tablo başlıkları
        header_cells = table.rows[0].cells
        header_cells[0].text = "Malzeme"
        header_cells[1].text = "Birim Fiyat (TL)"
        header_cells[2].text = "Miktar"
        header_cells[3].text = "Birim"
        header_cells[4].text = "Toplam (TL)"
        
        # Başlık hücrelerini kalın yap
        for cell in header_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True
        
        # Verileri tabloya ekle
        for item in data['malzeme_maliyetleri']:
            row_cells = table.add_row().cells
            row_cells[0].text = item.get('malzeme', '')
            row_cells[1].text = str(item.get('birim_fiyat', 0))
            row_cells[2].text = str(item.get('miktar', 0))
            row_cells[3].text = item.get('birim', '')
            row_cells[4].text = str(item.get('toplam', 0))
        
        # Toplam satırı
        if 'malzeme_toplam' in data:
            row_cells = table.add_row().cells
            row_cells[0].text = "TOPLAM"
            row_cells[0].merge(row_cells[3])
            row_cells[4].text = str(data['malzeme_toplam'])
            
            # Toplam satırını kalın yap
            for cell in [row_cells[0], row_cells[4]]:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.bold = True
        
        doc.add_paragraph()
    
    # Toplam maliyet
    if 'toplam_maliyet' in data:
        doc.add_paragraph("TOPLAM MALİYET", style='Alt Başlık')
        
        # Tablo oluştur
        table = doc.add_table(rows=1, cols=2)
        table.style = 'Table Grid'
        
        # Tablo başlıkları
        header_cells = table.rows[0].cells
        header_cells[0].text = "Maliyet Kalemi"
        header_cells[1].text = "Tutar (TL)"
        
        # Başlık hücrelerini kalın yap
        for cell in header_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True
        
        # İşçilik toplamı
        if 'iscilik_toplam' in data:
            row_cells = table.add_row().cells
            row_cells[0].text = "İşçilik Maliyeti"
            row_cells[1].text = str(data['iscilik_toplam'])
        
        # Malzeme toplamı
        if 'malzeme_toplam' in data:
            row_cells = table.add_row().cells
            row_cells[0].text = "Malzeme Maliyeti"
            row_cells[1].text = str(data['malzeme_toplam'])
        
        # Diğer maliyetler
        if 'diger_maliyetler' in data:
            for key, value in data['diger_maliyetler'].items():
                row_cells = table.add_row().cells
                row_cells[0].text = key
                row_cells[1].text = str(value)
        
        # Toplam maliyet
        row_cells = table.add_row().cells
        row_cells[0].text = "TOPLAM MALİYET"
        row_cells[1].text = str(data['toplam_maliyet'])
        
        # Toplam satırını kalın yap
        for cell in row_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True
        
        doc.add_paragraph()
    
    # Kar marjı ve teklif fiyatı
    if 'kar_marji' in data and 'teklif_fiyati' in data:
        doc.add_paragraph("TEKLİF BİLGİLERİ", style='Alt Başlık')
        
        # Tablo oluştur
        table = doc.add_table(rows=1, cols=2)
        table.style = 'Table Grid'
        
        # Tablo başlıkları
        header_cells = table.rows[0].cells
        header_cells[0].text = "Kalem"
        header_cells[1].text = "Değer"
        
        # Başlık hücrelerini kalın yap
        for cell in header_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True
        
        # Toplam maliyet
        row_cells = table.add_row().cells
        row_cells[0].text = "Toplam Maliyet (TL)"
        row_cells[1].text = str(data['toplam_maliyet'])
        
        # Kar marjı
        row_cells = table.add_row().cells
        row_cells[0].text = "Kar Marjı (%)"
        row_cells[1].text = str(data['kar_marji'])
        
        # Kar tutarı
        if 'kar_tutari' in data:
            row_cells = table.add_row().cells
            row_cells[0].text = "Kar Tutarı (TL)"
            row_cells[1].text = str(data['kar_tutari'])
        
        # Teklif fiyatı
        row_cells = table.add_row().cells
        row_cells[0].text = "TEKLİF FİYATI (TL)"
        row_cells[1].text = str(data['teklif_fiyati'])
        
        # Teklif fiyatı satırını kalın yap
        for cell in row_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True

def _create_offer_word(doc, data):
    """
    Teklif Word dokümanı oluşturur
    """
    # Başlık
    heading = doc.add_paragraph("TEKLİF", style='Başlık')
    heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    # Tarih ve referans
    date_paragraph = doc.add_paragraph(f"Tarih: {datetime.now().strftime('%d.%m.%Y')}", style='Normal Metin')
    date_paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    
    if 'referans_no' in data:
        ref_paragraph = doc.add_paragraph(f"Referans No: {data['referans_no']}", style='Normal Metin')
        ref_paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    
    doc.add_paragraph()
    
    # Müşteri bilgileri
    if 'musteri_bilgileri' in data:
        doc.add_paragraph("MÜŞTERİ BİLGİLERİ", style='Alt Başlık')
        for key, value in data['musteri_bilgileri'].items():
            doc.add_paragraph(f"{key}: {value}", style='Normal Metin')
        doc.add_paragraph()
    
    # Proje bilgileri
    if 'proje_bilgileri' in data:
        doc.add_paragraph("PROJE BİLGİLERİ", style='Alt Başlık')
        for key, value in data['proje_bilgileri'].items():
            doc.add_paragraph(f"{key}: {value}", style='Normal Metin')
        doc.add_paragraph()
    
    # Teklif detayları
    if 'teklif_detaylari' in data:
        doc.add_paragraph("TEKLİF DETAYLARI", style='Alt Başlık')
        
        # Tablo oluştur
        table = doc.add_table(rows=1, cols=5)
        table.style = 'Table Grid'
        
        # Tablo başlıkları
        header_cells = table.rows[0].cells
        header_cells[0].text = "Kalem"
        header_cells[1].text = "Açıklama"
        header_cells[2].text = "Miktar"
        header_cells[3].text = "Birim Fiyat (TL)"
        header_cells[4].text = "Toplam (TL)"
        
        # Başlık hücrelerini kalın yap
        for cell in header_cells:
            for paragraph in cell.paragraphs:
                for run in paragraph.runs:
                    run.font.bold = True
        
        # Verileri tabloya ekle
        for item in data['teklif_detaylari']:
            row_cells = table.add_row().cells
            row_cells[0].text = item.get('kalem', '')
            row_cells[1].text = item.get('aciklama', '')
            row_cells[2].text = str(item.get('miktar', 0))
            row_cells[3].text = str(item.get('birim_fiyat', 0))
            row_cells[4].text = str(item.get('toplam', 0))
        
        # Toplam satırı
        if 'toplam_fiyat' in data:
            row_cells = table.add_row().cells
            row_cells[0].text = "TOPLAM"
            row_cells[0].merge(row_cells[3])
            row_cells[4].text = str(data['toplam_fiyat'])
            
            # Toplam satırını kalın yap
            for cell in [row_cells[0], row_cells[4]]:
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.bold = True
        
        doc.add_paragraph()
    
    # Ödeme ve teslimat koşulları
    if 'odeme_kosullari' in data or 'teslimat_kosullari' in data:
        doc.add_paragraph("ÖDEME VE TESLİMAT KOŞULLARI", style='Alt Başlık')
        
        if 'odeme_kosullari' in data:
            doc.add_paragraph("Ödeme Koşulları:", style='Tablo Başlık')
            doc.add_paragraph(data['odeme_kosullari'], style='Normal Metin')
        
        if 'teslimat_kosullari' in data:
            doc.add_paragraph("Teslimat Koşulları:", style='Tablo Başlık')
            doc.add_paragraph(data['teslimat_kosullari'], style='Normal Metin')
        
        doc.add_paragraph()
    
    # Geçerlilik süresi
    if 'gecerlilik_suresi' in data:
        doc.add_paragraph("GEÇERLİLİK SÜRESİ", style='Alt Başlık')
        doc.add_paragraph(data['gecerlilik_suresi'], style='Normal Metin')
        doc.add_paragraph()
    
    # İmza
    doc.add_paragraph("Saygılarımızla,", style='Normal Metin')
    doc.add_paragraph()
    doc.add_paragraph()
    doc.add_paragraph("[İmza]", style='Normal Metin')
    
    if 'firma_bilgileri' in data:
        for key, value in data['firma_bilgileri'].items():
            doc.add_paragraph(f"{value}", style='Normal Metin')

def _create_default_word(doc, data):
    """
    Varsayılan Word dokümanı oluşturur
    """
    # Başlık
    heading = doc.add_paragraph(data.get('baslik', 'DOKÜMAN'), style='Başlık')
    heading.alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    # Tarih
    date_paragraph = doc.add_paragraph(f"Tarih: {datetime.now().strftime('%d.%m.%Y')}", style='Normal Metin')
    date_paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
    
    doc.add_paragraph()
    
    # İçerik
    if 'icerik' in data:
        for item in data['icerik']:
            if item.get('tip') == 'baslik':
                doc.add_paragraph(item.get('metin', ''), style='Alt Başlık')
            elif item.get('tip') == 'paragraf':
                doc.add_paragraph(item.get('metin', ''), style='Normal Metin')
            elif item.get('tip') == 'liste':
                for liste_item in item.get('liste_ogeler', []):
                    paragraph = doc.add_paragraph(style='List Bullet')
                    paragraph.add_run(liste_item)

def create_excel_document(data: Dict, template_type: str = 'maliyet_raporu') -> str:
    """
    Verilen verilerle Excel dokümanı oluşturur
    
    Args:
        data: Doküman içeriği için veriler
        template_type: Şablon türü (maliyet_raporu, teklif, vs.)
        
    Returns:
        Oluşturulan dosyanın yolu
    """
    wb = openpyxl.Workbook()
    
    # Şablon türüne göre doküman oluştur
    if template_type == 'maliyet_raporu':
        _create_cost_report_excel(wb, data)
    elif template_type == 'teklif':
        _create_offer_excel(wb, data)
    else:
        # Varsayılan şablon
        _create_default_excel(wb, data)
    
    # Dosyayı kaydet
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    filename = f"{timestamp}_{template_type}.xlsx"
    file_path = os.path.join(OUTPUT_DIR, filename)
    wb.save(file_path)
    
    return file_path

def _create_cost_report_excel(wb, data):
    """
    Maliyet raporu Excel dokümanı oluşturur
    """
    # Varsayılan sayfayı sil
    if 'Sheet' in wb.sheetnames:
        del wb['Sheet']
    
    # Sayfalar oluştur
    ws_summary = wb.create_sheet("Özet")
    ws_labor = wb.create_sheet("İşçilik Maliyetleri")
    ws_material = wb.create_sheet("Malzeme Maliyetleri")
    
    # Stil tanımlamaları
    header_font = Font(name='Arial', size=12, bold=True)
    normal_font = Font(name='Arial', size=11)
    total_font = Font(name='Arial', size=11, bold=True)
    
    header_fill = PatternFill(start_color="DDDDDD", end_color="DDDDDD", fill_type="solid")
    total_fill = PatternFill(start_color="EEEEEE", end_color="EEEEEE", fill_type="solid")
    
    center_align = Alignment(horizontal='center', vertical='center')
    right_align = Alignment(horizontal='right', vertical='center')
    
    thin_border = Border(
        left=Side(style='thin'),
        right=Side(style='thin'),
        top=Side(style='thin'),
        bottom=Side(style='thin')
    )
    
    # Özet sayfası
    ws_summary.column_dimensions['A'].width = 30
    ws_summary.column_dimensions['B'].width = 15
    
    # Başlık
    ws_summary.merge_cells('A1:B1')
    ws_summary['A1'] = "MALİYET RAPORU"
    ws_summary['A1'].font = Font(name='Arial', size=14, bold=True)
    ws_summary['A1'].alignment = center_align
    
    # Tarih
    ws_summary['A2'] = "Tarih:"
    ws_summary['B2'] = datetime.now().strftime('%d.%m.%Y')
    ws_summary['A2'].font = normal_font
    ws_summary['B2'].font = normal_font
    
    # Proje bilgileri
    row = 4
    if 'proje_bilgileri' in data:
        ws_summary['A3'] = "PROJE BİLGİLERİ"
        ws_summary['A3'].font = header_font
        
        for key, value in data['proje_bilgileri'].items():
            ws_summary[f'A{row}'] = key
            ws_summary[f'B{row}'] = value
            ws_summary[f'A{row}'].font = normal_font
            ws_summary[f'B{row}'].font = normal_font
            row += 1
    
    row += 1
    
    # Toplam maliyet tablosu
    ws_summary[f'A{row}'] = "TOPLAM MALİYET"
    ws_summary[f'A{row}'].font = header_font
    row += 1
    
    # Tablo başlıkları
    ws_summary[f'A{row}'] = "Maliyet Kalemi"
    ws_summary[f'B{row}'] = "Tutar (TL)"
    ws_summary[f'A{row}'].font = header_font
    ws_summary[f'B{row}'].font = header_font
    ws_summary[f'A{row}'].fill = header_fill
    ws_summary[f'B{row}'].fill = header_fill
    ws_summary[f'A{row}'].border = thin_border
    ws_summary[f'B{row}'].border = thin_border
    row += 1
    
    # İşçilik toplamı
    if 'iscilik_toplam' in data:
        ws_summary[f'A{row}'] = "İşçilik Maliyeti"
        ws_summary[f'B{row}'] = data['iscilik_toplam']
        ws_summary[f'A{row}'].font = normal_font
        ws_summary[f'B{row}'].font = normal_font
        ws_summary[f'A{row}'].border = thin_border
        ws_summary[f'B{row}'].border = thin_border
        row += 1
    
    # Malzeme toplamı
    if 'malzeme_toplam' in data:
        ws_summary[f'A{row}'] = "Malzeme Maliyeti"
        ws_summary[f'B{row}'] = data['malzeme_toplam']
        ws_summary[f'A{row}'].font = normal_font
        ws_summary[f'B{row}'].font = normal_font
        ws_summary[f'A{row}'].border = thin_border
        ws_summary[f'B{row}'].border = thin_border
        row += 1
    
    # Diğer maliyetler
    if 'diger_maliyetler' in data:
        for key, value in data['diger_maliyetler'].items():
            ws_summary[f'A{row}'] = key
            ws_summary[f'B{row}'] = value
            ws_summary[f'A{row}'].font = normal_font
            ws_summary[f'B{row}'].font = normal_font
            ws_summary[f'A{row}'].border = thin_border
            ws_summary[f'B{row}'].border = thin_border
            row += 1
    
    # Toplam maliyet
    if 'toplam_maliyet' in data:
        ws_summary[f'A{row}'] = "TOPLAM MALİYET"
        ws_summary[f'B{row}'] = data['toplam_maliyet']
        ws_summary[f'A{row}'].font = total_font
        ws_summary[f'B{row}'].font = total_font
        ws_summary[f'A{row}'].fill = total_fill
        ws_summary[f'B{row}'].fill = total_fill
        ws_summary[f'A{row}'].border = thin_border
        ws_summary[f'B{row}'].border = thin_border
        row += 2
    
    # Kar marjı ve teklif fiyatı
    if 'kar_marji' in data and 'teklif_fiyati' in data:
        ws_summary[f'A{row}'] = "TEKLİF BİLGİLERİ"
        ws_summary[f'A{row}'].font = header_font
        row += 1
        
        # Tablo başlıkları
        ws_summary[f'A{row}'] = "Kalem"
        ws_summary[f'B{row}'] = "Değer"
        ws_summary[f'A{row}'].font = header_font
        ws_summary[f'B{row}'].font = header_font
        ws_summary[f'A{row}'].fill = header_fill
        ws_summary[f'B{row}'].fill = header_fill
        ws_summary[f'A{row}'].border = thin_border
        ws_summary[f'B{row}'].border = thin_border
        row += 1
        
        # Toplam maliyet
        ws_summary[f'A{row}'] = "Toplam Maliyet (TL)"
        ws_summary[f'B{row}'] = data['toplam_maliyet']
        ws_summary[f'A{row}'].font = normal_font
        ws_summary[f'B{row}'].font = normal_font
        ws_summary[f'A{row}'].border = thin_border
        ws_summary[f'B{row}'].border = thin_border
        row += 1
        
        # Kar marjı
        ws_summary[f'A{row}'] = "Kar Marjı (%)"
        ws_summary[f'B{row}'] = data['kar_marji']
        ws_summary[f'A{row}'].font = normal_font
        ws_summary[f'B{row}'].font = normal_font
        ws_summary[f'A{row}'].border = thin_border
        ws_summary[f'B{row}'].border = thin_border
        row += 1
        
        # Kar tutarı
        if 'kar_tutari' in data:
            ws_summary[f'A{row}'] = "Kar Tutarı (TL)"
            ws_summary[f'B{row}'] = data['kar_tutari']
            ws_summary[f'A{row}'].font = normal_font
            ws_summary[f'B{row}'].font = normal_font
            ws_summary[f'A{row}'].border = thin_border
            ws_summary[f'B{row}'].border = thin_border
            row += 1
        
        # Teklif fiyatı
        ws_summary[f'A{row}'] = "TEKLİF FİYATI (TL)"
        ws_summary[f'B{row}'] = data['teklif_fiyati']
        ws_summary[f'A{row}'].font = total_font
        ws_summary[f'B{row}'].font = total_font
        ws_summary[f'A{row}'].fill = total_fill
        ws_summary[f'B{row}'].fill = total_fill
        ws_summary[f'A{row}'].border = thin_border
        ws_summary[f'B{row}'].border = thin_border
    
    # İşçilik maliyetleri sayfası
    if 'iscilik_maliyetleri' in data:
        ws_labor.column_dimensions['A'].width = 30
        ws_labor.column_dimensions['B'].width = 15
        ws_labor.column_dimensions['C'].width = 15
        ws_labor.column_dimensions['D'].width = 15
        
        # Başlık
        ws_labor.merge_cells('A1:D1')
        ws_labor['A1'] = "İŞÇİLİK MALİYETLERİ"
        ws_labor['A1'].font = Font(name='Arial', size=14, bold=True)
        ws_labor['A1'].alignment = center_align
        
        # Tablo başlıkları
        ws_labor['A3'] = "Pozisyon"
        ws_labor['B3'] = "Saat Ücreti (TL)"
        ws_labor['C3'] = "Süre (Saat)"
        ws_labor['D3'] = "Toplam (TL)"
        
        for col in ['A', 'B', 'C', 'D']:
            ws_labor[f'{col}3'].font = header_font
            ws_labor[f'{col}3'].fill = header_fill
            ws_labor[f'{col}3'].border = thin_border
        
        # Verileri tabloya ekle
        row = 4
        for item in data['iscilik_maliyetleri']:
            ws_labor[f'A{row}'] = item.get('pozisyon', '')
            ws_labor[f'B{row}'] = item.get('saat_ucreti', 0)
            ws_labor[f'C{row}'] = item.get('sure', 0)
            ws_labor[f'D{row}'] = item.get('toplam', 0)
            
            for col in ['A', 'B', 'C', 'D']:
                ws_labor[f'{col}{row}'].font = normal_font
                ws_labor[f'{col}{row}'].border = thin_border
            
            row += 1
        
        # Toplam satırı
        if 'iscilik_toplam' in data:
            ws_labor[f'A{row}'] = "TOPLAM"
            ws_labor[f'D{row}'] = data['iscilik_toplam']
            
            ws_labor.merge_cells(f'A{row}:C{row}')
            
            for col in ['A', 'D']:
                ws_labor[f'{col}{row}'].font = total_font
                ws_labor[f'{col}{row}'].fill = total_fill
                ws_labor[f'{col}{row}'].border = thin_border
    
    # Malzeme maliyetleri sayfası
    if 'malzeme_maliyetleri' in data:
        ws_material.column_dimensions['A'].width = 30
        ws_material.column_dimensions['B'].width = 15
        ws_material.column_dimensions['C'].width = 15
        ws_material.column_dimensions['D'].width = 15
        ws_material.column_dimensions['E'].width = 15
        
        # Başlık
        ws_material.merge_cells('A1:E1')
        ws_material['A1'] = "MALZEME MALİYETLERİ"
        ws_material['A1'].font = Font(name='Arial', size=14, bold=True)
        ws_material['A1'].alignment = center_align
        
        # Tablo başlıkları
        ws_material['A3'] = "Malzeme"
        ws_material['B3'] = "Birim Fiyat (TL)"
        ws_material['C3'] = "Miktar"
        ws_material['D3'] = "Birim"
        ws_material['E3'] = "Toplam (TL)"
        
        for col in ['A', 'B', 'C', 'D', 'E']:
            ws_material[f'{col}3'].font = header_font
            ws_material[f'{col}3'].fill = header_fill
            ws_material[f'{col}3'].border = thin_border
        
        # Verileri tabloya ekle
        row = 4
        for item in data['malzeme_maliyetleri']:
            ws_material[f'A{row}'] = item.get('malzeme', '')
            ws_material[f'B{row}'] = item.get('birim_fiyat', 0)
            ws_material[f'C{row}'] = item.get('miktar', 0)
            ws_material[f'D{row}'] = item.get('birim', '')
            ws_material[f'E{row}'] = item.get('toplam', 0)
            
            for col in ['A', 'B', 'C', 'D', 'E']:
                ws_material[f'{col}{row}'].font = normal_font
                ws_material[f'{col}{row}'].border = thin_border
            
            row += 1
        
        # Toplam satırı
        if 'malzeme_toplam' in data:
            ws_material[f'A{row}'] = "TOPLAM"
            ws_material[f'E{row}'] = data['malzeme_toplam']
            
            ws_material.merge_cells(f'A{row}:D{row}')
            
            for col in ['A', 'E']:
                ws_material[f'{col}{row}'].font = total_font
                ws_material[f'{col}{row}'].fill = total_fill
                ws_material[f'{col}{row}'].border = thin_border

def _create_offer_excel(wb, data):
    """
    Teklif Excel dokümanı oluşturur
    """
    # Varsayılan sayfayı sil
    if 'Sheet' in wb.sheetnames:
        del wb['Sheet']
    
    # Sayfalar oluştur
    ws_offer = wb.create_sheet("Teklif")
    ws_details = wb.create_sheet("Detaylar")
    
    # Stil tanımlamaları
    header_font = Font(name='Arial', size=12, bold=True)
    normal_font = Font(name='Arial', size=11)
    total_font = Font(name='Arial', size=11, bold=True)
    
    header_fill = PatternFill(start_color="DDDDDD", end_color="DDDDDD", fill_type="solid")
    total_fill = PatternFill(start_color="EEEEEE", end_color="EEEEEE", fill_type="solid")
    
    center_align = Alignment(horizontal='center', vertical='center')
    right_align = Alignment(horizontal='right', vertical='center')
    
    thin_border = Border(
        left=Side(style='thin'),
        right=Side(style='thin'),
        top=Side(style='thin'),
        bottom=Side(style='thin')
    )
    
    # Teklif sayfası
    ws_offer.column_dimensions['A'].width = 30
    ws_offer.column_dimensions['B'].width = 15
    ws_offer.column_dimensions['C'].width = 15
    ws_offer.column_dimensions['D'].width = 15
    ws_offer.column_dimensions['E'].width = 15
    
    # Başlık
    ws_offer.merge_cells('A1:E1')
    ws_offer['A1'] = "TEKLİF"
    ws_offer['A1'].font = Font(name='Arial', size=14, bold=True)
    ws_offer['A1'].alignment = center_align
    
    # Tarih ve referans
    ws_offer['D2'] = "Tarih:"
    ws_offer['E2'] = datetime.now().strftime('%d.%m.%Y')
    ws_offer['D2'].font = normal_font
    ws_offer['E2'].font = normal_font
    
    if 'referans_no' in data:
        ws_offer['D3'] = "Referans No:"
        ws_offer['E3'] = data['referans_no']
        ws_offer['D3'].font = normal_font
        ws_offer['E3'].font = normal_font
    
    # Müşteri bilgileri
    row = 5
    if 'musteri_bilgileri' in data:
        ws_offer['A4'] = "MÜŞTERİ BİLGİLERİ"
        ws_offer['A4'].font = header_font
        
        for key, value in data['musteri_bilgileri'].items():
            ws_offer[f'A{row}'] = key
            ws_offer[f'B{row}'] = value
            ws_offer[f'A{row}'].font = normal_font
            ws_offer[f'B{row}'].font = normal_font
            row += 1
    
    row += 1
    
    # Proje bilgileri
    if 'proje_bilgileri' in data:
        ws_offer[f'A{row}'] = "PROJE BİLGİLERİ"
        ws_offer[f'A{row}'].font = header_font
        row += 1
        
        for key, value in data['proje_bilgileri'].items():
            ws_offer[f'A{row}'] = key
            ws_offer[f'B{row}'] = value
            ws_offer[f'A{row}'].font = normal_font
            ws_offer[f'B{row}'].font = normal_font
            row += 1
    
    row += 1
    
    # Teklif detayları
    if 'teklif_detaylari' in data:
        ws_offer[f'A{row}'] = "TEKLİF DETAYLARI"
        ws_offer[f'A{row}'].font = header_font
        row += 1
        
        # Tablo başlıkları
        ws_offer[f'A{row}'] = "Kalem"
        ws_offer[f'B{row}'] = "Açıklama"
        ws_offer[f'C{row}'] = "Miktar"
        ws_offer[f'D{row}'] = "Birim Fiyat (TL)"
        ws_offer[f'E{row}'] = "Toplam (TL)"
        
        for col in ['A', 'B', 'C', 'D', 'E']:
            ws_offer[f'{col}{row}'].font = header_font
            ws_offer[f'{col}{row}'].fill = header_fill
            ws_offer[f'{col}{row}'].border = thin_border
        
        row += 1
        
        # Verileri tabloya ekle
        for item in data['teklif_detaylari']:
            ws_offer[f'A{row}'] = item.get('kalem', '')
            ws_offer[f'B{row}'] = item.get('aciklama', '')
            ws_offer[f'C{row}'] = item.get('miktar', 0)
            ws_offer[f'D{row}'] = item.get('birim_fiyat', 0)
            ws_offer[f'E{row}'] = item.get('toplam', 0)
            
            for col in ['A', 'B', 'C', 'D', 'E']:
                ws_offer[f'{col}{row}'].font = normal_font
                ws_offer[f'{col}{row}'].border = thin_border
            
            row += 1
        
        # Toplam satırı
        if 'toplam_fiyat' in data:
            ws_offer[f'A{row}'] = "TOPLAM"
            ws_offer[f'E{row}'] = data['toplam_fiyat']
            
            ws_offer.merge_cells(f'A{row}:D{row}')
            
            for col in ['A', 'E']:
                ws_offer[f'{col}{row}'].font = total_font
                ws_offer[f'{col}{row}'].fill = total_fill
                ws_offer[f'{col}{row}'].border = thin_border
    
    # Detaylar sayfası
    ws_details.column_dimensions['A'].width = 30
    ws_details.column_dimensions['B'].width = 50
    
    # Başlık
    ws_details.merge_cells('A1:B1')
    ws_details['A1'] = "TEKLİF DETAYLARI"
    ws_details['A1'].font = Font(name='Arial', size=14, bold=True)
    ws_details['A1'].alignment = center_align
    
    row = 3
    
    # Ödeme ve teslimat koşulları
    if 'odeme_kosullari' in data or 'teslimat_kosullari' in data:
        ws_details[f'A{row}'] = "ÖDEME VE TESLİMAT KOŞULLARI"
        ws_details[f'A{row}'].font = header_font
        row += 1
        
        if 'odeme_kosullari' in data:
            ws_details[f'A{row}'] = "Ödeme Koşulları:"
            ws_details[f'A{row}'].font = Font(name='Arial', size=11, bold=True)
            row += 1
            
            ws_details[f'A{row}'] = data['odeme_kosullari']
            ws_details[f'A{row}'].font = normal_font
            row += 2
        
        if 'teslimat_kosullari' in data:
            ws_details[f'A{row}'] = "Teslimat Koşulları:"
            ws_details[f'A{row}'].font = Font(name='Arial', size=11, bold=True)
            row += 1
            
            ws_details[f'A{row}'] = data['teslimat_kosullari']
            ws_details[f'A{row}'].font = normal_font
            row += 2
    
    # Geçerlilik süresi
    if 'gecerlilik_suresi' in data:
        ws_details[f'A{row}'] = "GEÇERLİLİK SÜRESİ"
        ws_details[f'A{row}'].font = header_font
        row += 1
        
        ws_details[f'A{row}'] = data['gecerlilik_suresi']
        ws_details[f'A{row}'].font = normal_font
        row += 2
    
    # Firma bilgileri
    if 'firma_bilgileri' in data:
        ws_details[f'A{row}'] = "FİRMA BİLGİLERİ"
        ws_details[f'A{row}'].font = header_font
        row += 1
        
        for key, value in data['firma_bilgileri'].items():
            ws_details[f'A{row}'] = value
            ws_details[f'A{row}'].font = normal_font
            row += 1

def _create_default_excel(wb, data):
    """
    Varsayılan Excel dokümanı oluşturur
    """
    # Varsayılan sayfayı al
    ws = wb.active
    ws.title = "Doküman"
    
    # Stil tanımlamaları
    header_font = Font(name='Arial', size=12, bold=True)
    normal_font = Font(name='Arial', size=11)
    
    center_align = Alignment(horizontal='center', vertical='center')
    
    # Başlık
    ws.merge_cells('A1:D1')
    ws['A1'] = data.get('baslik', 'DOKÜMAN')
    ws['A1'].font = Font(name='Arial', size=14, bold=True)
    ws['A1'].alignment = center_align
    
    # Tarih
    ws['D2'] = "Tarih:"
    ws['E2'] = datetime.now().strftime('%d.%m.%Y')
    ws['D2'].font = normal_font
    ws['E2'].font = normal_font
    
    # İçerik
    row = 4
    if 'icerik' in data:
        for item in data['icerik']:
            if item.get('tip') == 'baslik':
                ws[f'A{row}'] = item.get('metin', '')
                ws[f'A{row}'].font = header_font
                row += 1
            elif item.get('tip') == 'paragraf':
                ws[f'A{row}'] = item.get('metin', '')
                ws[f'A{row}'].font = normal_font
                row += 1
            elif item.get('tip') == 'liste':
                for liste_item in item.get('liste_ogeler', []):
                    ws[f'A{row}'] = "• " + liste_item
                    ws[f'A{row}'].font = normal_font
                    row += 1

def save_document_to_db(db: Session, filename, content_type, file_path, file_size, document_type, template_type):
    """
    Oluşturulan doküman bilgilerini veritabanına kaydet
    """
    document = Document(
        filename=filename,
        content_type=content_type,
        file_path=file_path,
        file_size=file_size,
        document_type=document_type,
        template_type=template_type
    )
    
    db.add(document)
    db.commit()
    db.refresh(document)
    return document