프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / ID2.Manager / ID2.Manager.Dapper / Repository / DocumentRepository.cs @ 378846cd

이력 | 보기 | 이력해설 | 다운로드 (34.5 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6

    
7
using System.Data;
8
using System.ComponentModel;
9
using System.Reflection;
10

    
11
using ID2.Manager.Data.Models;
12

    
13
using Dapper;
14

    
15
using Newtonsoft.Json;
16

    
17
namespace ID2.Manager.Dapper.Repository
18
{
19
    public class DocumentRepository : BaseRepository
20
    {
21
        public DocumentRepository(string connectionStr) : base(connectionStr) { }
22

    
23
        public IEnumerable<Documents> GetAllDocuments(List<string> projectGroupIDs)
24
        {
25
            var dynamicParameters = new DynamicParameters();
26
            StringBuilder sbWhere = new StringBuilder();
27
            var parameters = new Dictionary<string, object>();
28
            if (projectGroupIDs.Count > 0)
29
            {
30
                sbWhere.Append(" and doc.RefProjectCode in (select Code from dbo.Projects where ParentID in @RefGroupIDs) ");
31
                parameters.Add("RefGroupIDs", projectGroupIDs);
32
            }
33

    
34
            try
35
            {
36
                string query = $@"
37
select   doc.*
38
from     dbo.Documents doc
39
where    doc.IsDeleted=0 {sbWhere}
40
order by doc.Seq;";
41

    
42
                if (parameters.Count > 0)
43
                {
44
                    dynamicParameters.AddDynamicParams(parameters);
45
                }
46

    
47
                return Query<Documents>(query, dynamicParameters);
48
            }
49
            catch (Exception ex)
50
            {
51
                throw ex;
52
            }
53
        }
54
        static string GetDescriptionFromAttribute(MemberInfo member)
55
        {
56
            if (member == null) return null;
57

    
58
            var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
59
            return (attrib?.Description ?? member.Name).ToLower();
60
        }
61

    
62

    
63
        public (IEnumerable<Documents> dwgs, int totalCnt) GetDocuments(List<string> projectGroupIDs, List<string> dateTypes, DateTime? frDate, DateTime? toDate,  string team, string projectCode, string personIncharge, string jobLevel, string documentNo, string isToIsDiscussion, string isFrReviewStatus, string id2Status, string id2Issues, string avevaStatus, string avevaIssues, string prodIsResult, string clientIsResult, string isGateWay, string isRegSystem)
64
        {
65
            var map = new CustomPropertyTypeMap(typeof(AttFileInfo), (type, columnName)
66
     => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName.ToLower()));
67
            SqlMapper.SetTypeMap(typeof(AttFileInfo), map);
68

    
69

    
70
            var dynamicParameters = new DynamicParameters();
71
            dynamicParameters.Add("Total", dbType: DbType.Int32, direction: ParameterDirection.Output);
72

    
73
            StringBuilder sbWhere = new StringBuilder();
74
            StringBuilder sbTotalWhere = new StringBuilder();
75
            var parameters = new Dictionary<string, object>();
76
            if (dateTypes.Count > 0 && (frDate != null || toDate != null))
77
            {
78
                List<string> subWheres = new List<string>();
79
                foreach (string dateType in dateTypes)
80
                {
81
                    StringBuilder sbSubWhere = new StringBuilder();
82
                    if (frDate != null)
83
                    {
84
                        sbSubWhere.Insert(0, $@"convert(datetime, '{Convert.ToDateTime(frDate).AddDays(-1):yyyy-MM-dd 23:59:59.997}') < doc.{dateType}");
85
                    }
86
                    if (toDate != null)
87
                    {
88
                        if (frDate != null)
89
                            sbSubWhere.Append($@" and ");
90
                        sbSubWhere.Append($@"doc.{dateType} < convert(datetime, '{Convert.ToDateTime(toDate).AddDays(1):yyyy-MM-dd 00:00:00.000}')");
91
                    }
92

    
93
                    if (sbSubWhere.Length > 0)
94
                    {
95
                        subWheres.Add("(" + sbSubWhere.ToString() + ")");
96
                    }
97
                }
98

    
99
                if (subWheres.Count > 0)
100
                {
101
                    sbWhere.Append(" and (" + string.Join(" or ", subWheres) + ") ");
102
                }
103
            }
104
            if (!string.IsNullOrEmpty(team))
105
            {
106
                sbWhere.Append(" and prj.Team=@Team ");
107
                parameters.Add("Team", team);
108
            }
109
            if (projectCode == null)
110
            {
111
                sbWhere.Append(" and prj.Code is null ");
112
                sbTotalWhere.Append(" and doc.RefProjectCode in (select Code from dbo.Projects where ParentID in @RefGroupIDs) ");
113
                parameters.Add("RefGroupIDs", projectGroupIDs);
114
            }
115
            else if (projectCode.Equals(string.Empty))
116
            {
117
                sbWhere.Append(" and doc.RefProjectCode in (select Code from dbo.Projects where ParentID in @RefGroupIDs) ");
118
                sbTotalWhere.Append(" and doc.RefProjectCode in (select Code from dbo.Projects where ParentID in @RefGroupIDs) ");
119
                parameters.Add("RefGroupIDs", projectGroupIDs);
120
            }
121
            else
122
            {
123
                sbTotalWhere.Append(" and doc.RefProjectCode in (select Code from dbo.Projects where ParentID in @RefGroupIDs) ");
124
                parameters.Add("RefGroupIDs", projectGroupIDs);
125

    
126
                sbWhere.Append(" and doc.RefProjectCode=@RefProjectCode ");
127
                parameters.Add("RefProjectCode", projectCode);
128
            }
129
            if (!string.IsNullOrEmpty(personIncharge))
130
            {
131
                sbWhere.Append(" and (doc.PersonInCharge=@PersonInCharge or doc.AVEVAPersonInCharge=@PersonInCharge) ");
132
                parameters.Add("PersonInCharge", personIncharge);
133
                parameters.Add("AVEVAPersonInCharge", personIncharge);
134
            }
135
            if (!string.IsNullOrEmpty(jobLevel))
136
            {
137
                sbWhere.Append(" and doc.JobLevel=@JobLevel ");
138
                parameters.Add("JobLevel", jobLevel);
139
            }
140
            if (!string.IsNullOrEmpty(documentNo))
141
            {
142
                sbWhere.Append(" and doc.DocumentNo like '%' + @DocumentNo +'%' ");
143
                parameters.Add("DocumentNo", documentNo);
144
            }
145

    
146
            if (!string.IsNullOrEmpty(isToIsDiscussion))
147
            {
148
                sbWhere.Append(" and doc.ToIsDiscussion=@ToIsDiscussion ");
149
                parameters.Add("ToIsDiscussion", isToIsDiscussion);
150
            }
151

    
152
            if (!string.IsNullOrEmpty(isFrReviewStatus))
153
            {
154
                sbWhere.Append(" and doc.FrReviewStatus=@FrReviewStatus ");
155
                parameters.Add("FrReviewStatus", isFrReviewStatus);
156
            }
157

    
158
            if (!string.IsNullOrEmpty(id2Status))
159
            {
160
                sbWhere.Append(" and doc.ID2Status=@ID2Status ");
161
                parameters.Add("ID2Status", id2Status);
162
            }
163

    
164
            if (!string.IsNullOrEmpty(id2Issues))
165
            {
166
                sbWhere.Append(" and (case when isnull(ltrim(rtrim(doc.ID2Issues)),'') = '' then 'No' else 'Yes' end)=@ID2Issues ");
167
                parameters.Add("ID2Issues", id2Issues);
168
            }
169
            
170
            if (!string.IsNullOrEmpty(avevaStatus))
171
            {
172
                sbWhere.Append(" and doc.AVEVAStatus=@AVEVAStatus ");
173
                parameters.Add("AVEVAStatus", avevaStatus);
174
            }
175

    
176
            if (!string.IsNullOrEmpty(avevaIssues))
177
            {
178
                sbWhere.Append(" and (case when isnull(ltrim(rtrim(doc.AVEVAIssues)),'') = '' then 'No' else 'Yes' end)=@AVEVAIssues ");
179
                parameters.Add("AVEVAIssues", avevaIssues);
180
            }
181

    
182
            if (!string.IsNullOrEmpty(prodIsResult))
183
            {
184
                sbWhere.Append(" and doc.ProdIsResult=@ProdIsResult ");
185
                parameters.Add("ProdIsResult", prodIsResult);
186
            }
187
            if (!string.IsNullOrEmpty(clientIsResult))
188
            {
189
                sbWhere.Append(" and doc.ClientIsResult=@ClientIsResult ");
190
                parameters.Add("ClientIsResult", clientIsResult);
191
            }
192
            if (!string.IsNullOrEmpty(isGateWay))
193
            {
194
                sbWhere.Append(" and doc.DTIsGateWay=@DTIsGateWay ");
195
                parameters.Add("DTIsGateWay", isGateWay);
196
            }
197
            if (!string.IsNullOrEmpty(isRegSystem))
198
            {
199
                sbWhere.Append(" and doc.DTIsRegSystem=@DTIsRegSystem ");
200
                parameters.Add("DTIsRegSystem", isRegSystem);
201
            }
202

    
203
            try
204
            {
205
                if (parameters.Count > 0)
206
                {
207
                    dynamicParameters.AddDynamicParams(parameters);
208
                }
209

    
210
                string query = $@"
211
select   doc.*
212
		,prj.Team
213
from     dbo.Documents doc
214
             left outer join dbo.Projects prj on doc.RefProjectCode=prj.Code
215
where    doc.IsDeleted=0 {sbWhere}
216
order by doc.Seq;
217

    
218
select files.*
219
from   dbo.AttachFIles files
220
           inner join
221
           (
222
	           select   doc.DocID
223
	           from     dbo.Documents doc
224
					        left outer join dbo.Projects prj on doc.RefProjectCode=prj.Code
225
	           where    doc.IsDeleted=0 {sbWhere}
226
           ) doc on files.RefID=doc.DocID;
227

    
228
select PROJECT_NO
229
      ,DOCUMENT_ID
230
      ,PAGENUMBER
231
      ,[Text] as [TEXT]
232
      ,CREATE_DATE
233
      ,[NAME] as CREATE_USER
234
from   ViewMarkupData;
235

    
236
select @Total=count(*) from dbo.Documents doc where doc.IsDeleted=0 {sbTotalWhere};";
237
                var results = QueryMultiple(query, dynamicParameters);
238

    
239
                var docs = results.Read<Documents>();
240
                var docFiles = results.Read<AttFileInfo>();
241
                var markupData = results.Read<MarkupText>();
242
                int totalCount = dynamicParameters.Get<int>("Total");
243

    
244
                var docFileGroups = docFiles.GroupBy(g => g.RefID)
245
                                            .Select(x => new
246
                                            {
247
                                                RefDocID = x.Key,
248
                                                List = x.AsEnumerable<AttFileInfo>().ToList(),
249
                                                ToCaptureCount = x.Where(y => y.Category.Equals("toreview")).Count(),
250
                                                FrCaptureCount = x.Where(y => y.Category.Equals("frreview")).Count(),
251
                                                ID2CaptureCount = x.Where(y => y.Category.Equals("id2work")).Count()
252
                                            });
253
                var markupGroups = markupData.GroupBy(g => new { g.PROJECT_NO, g.DOCUMENT_ID })
254
                                             .Select(x => new
255
                                             {
256
                                                 x.Key.PROJECT_NO,
257
                                                 x.Key.DOCUMENT_ID,
258
                                                 List = x.Where(y => y.TEXT != null && y.CREATE_DATE != null && y.CREATE_USER != null).OrderByDescending(o => o.CREATE_DATE).ToList() //x.AsEnumerable<MarkupText>().ToList()
259
                                             });
260

    
261
                var ret = (from d in docs
262
                           join fg in docFileGroups on d.DocID equals fg.RefDocID into dfg
263
                           from fdata in dfg.DefaultIfEmpty()
264
                           join mg in markupGroups on new { pj = d.RefProjectCode, dn = d.DocumentNo } equals new { pj = mg.PROJECT_NO, dn = mg.DOCUMENT_ID } into dmg
265
                           from mdata in dmg.DefaultIfEmpty()
266
                           select new { d, fdata, mdata }).Select(x =>
267
                           {
268
                               x.d.ToCapture = x.fdata?.ToCaptureCount ?? x.d.ToCapture;
269
                               x.d.FrCapture = x.fdata?.FrCaptureCount ?? x.d.FrCapture;
270
                               x.d.ID2Capture = x.fdata?.ID2CaptureCount ?? x.d.ID2Capture;
271
                               x.d.Markups = x.mdata?.List.Count > 0 ? x.mdata.List : x.d.Markups;
272
                               x.d.AttFiles = x.fdata?.List ?? new List<AttFileInfo>();
273
                               x.d.ConvertStatus = (x.mdata == null ? x.d.ConvertStatus : 4);
274
                               return x.d;
275
                           });
276

    
277
                return (ret, totalCount);
278
            }
279
            catch (Exception ex)
280
            {
281
                throw ex;
282
            }
283
        }
284

    
285
        public int ExistsDocument(string projectGroupID, List<string> newDwgNos)
286
        {
287
            int existCount = 0;
288

    
289
            int paramMaxCount = 2000;
290
            int execCount = (newDwgNos.Count / paramMaxCount) + 1;
291

    
292
            for (int i = 0; i < execCount; i++)
293
            {
294
                var dynamicParameters = new DynamicParameters();
295
                StringBuilder sbWhere = new StringBuilder();
296
                var parameters = new Dictionary<string, object>();
297
                if (!string.IsNullOrEmpty(projectGroupID))
298
                {
299
                    sbWhere.Append(" and doc.RefProjectCode in (select Code from dbo.Projects where ParentID=@RefGroupID) ");
300
                    parameters.Add("RefGroupID", projectGroupID);
301
                }
302

    
303
                var limitDwgNos = newDwgNos.Skip(paramMaxCount * i).Take(paramMaxCount).ToList();
304
                sbWhere.Append($@" and doc.DocumentNo in @limitDwgNos ");
305
                parameters.Add("limitDwgNos", limitDwgNos);
306

    
307
                try
308
                {
309
                    string query = $@"
310
select   count(*) cnt
311
from     dbo.Documents doc
312
where    doc.IsDeleted=0 {sbWhere}";
313

    
314
                    if (parameters.Count > 0)
315
                    {
316
                        dynamicParameters.AddDynamicParams(parameters);
317
                    }
318

    
319
                    existCount += ExecuteScalar<int>(query, dynamicParameters);
320
                }
321
                catch (Exception ex)
322
                {
323
                    throw ex;
324
                }
325
            }
326

    
327
            return existCount;
328
        }
329

    
330
//        public bool ExistsNotRegID2ProjectDocuments()
331
//        {
332
//            try
333
//            {
334
//                string query = $@"
335
//select top 1 *
336
//from   dbo.Documents doc
337
//where  doc.IsDeleted=0
338
//   and doc.RefProjectCode not in (select Code from dbo.Projects prj);";
339

    
340
//                bool isRet = ExecuteScalar<int>(query, null) > 0;
341

    
342
//                return isRet;
343
//            }
344
//            catch (Exception ex)
345
//            {
346
//                throw ex;
347
//            }
348
//        }
349

    
350
        public bool SetDocumentData(List<string> projectGroupIDs, List<Documents> docList, List<string> delDocList, string userId)
351
        {
352
            bool isSuccess = false;
353

    
354
            try
355
            {
356
                using (var transaction = base.BeginTransaction())
357
                {
358
                    string query = string.Empty;
359

    
360
                    if (delDocList.Count > 0)
361
                    {
362
                        int paramMaxCount = 2000;
363
                        int execCount = (delDocList.Count / paramMaxCount) + 1;
364

    
365
                        for (int i = 0; i < execCount; i++)
366
                        {
367
                            var dynamicParameters = new DynamicParameters();
368
                            StringBuilder sbWhere = new StringBuilder();
369
                            var parameters = new Dictionary<string, object>();
370

    
371
                            parameters.Add("DeletedUser", userId);
372

    
373
                            var limitDwgNos = delDocList.Skip(paramMaxCount * i).Take(paramMaxCount).ToList();
374
                            sbWhere.Append($@" and DocID in @limitDwgNos ");
375
                            parameters.Add("limitDwgNos", limitDwgNos);
376

    
377
                            query = $@"
378
update dbo.Documents
379
set    IsDeleted=1
380
      ,DeletedDate=getdate()
381
      ,DeletedUser=@DeletedUser
382
where  IsDeleted=0 {sbWhere}";
383
                            if (parameters.Count > 0)
384
                            {
385
                                dynamicParameters.AddDynamicParams(parameters);
386
                            }
387

    
388
                            base.Execute(query, dynamicParameters, transaction);
389
                        }
390
                    }
391

    
392
                    foreach (Documents doc in docList)
393
                    {
394
                        if (string.IsNullOrEmpty(doc.DocID))
395
                        {
396
                            doc.RegisteredUser = userId;
397
                            doc.ModifiedUser = userId;
398

    
399
                            query = $@"
400
if exists(select * from dbo.Documents where RefProjectCode=@RefProjectCode and DocumentNo=@DocumentNo and IsDeleted=0)
401
begin
402
    --update
403
    update dbo.Documents
404
    set    RevisonNo=case when isnull(@RevisonNo,'')='' then '0' else @RevisonNo end
405
          ,System=@System
406
          ,SubSystemCode=@SubSystemCode
407
          ,JobLevel=@JobLevel
408
          ,Simularity=@Simularity
409
          ,Simularity2=@Simularity2
410
          ,PersonInCharge=@PersonInCharge
411
          ,Worker=@Worker
412
          ,ModifiedDate=getdate()
413
          ,ModifiedUser=@ModifiedUser
414
          ,ToIsDiscussion=@ToIsDiscussion
415
          ,ToRemarks=@ToRemarks
416
          ,ToCreator=@ToCreator
417
          ,FrReviewStatus=@FrReviewStatus
418
          ,FrRemarks=@FrRemarks
419
          ,FrCreator=@FrCreator
420
          ,ID2StartDate=@ID2StartDate
421
          ,ID2EndDate=@ID2EndDate
422
          ,ID2Status=@ID2Status
423
          ,ID2Issues=@ID2Issues
424
          ,ReplyModifications=@ReplyModifications
425
          ,ReplyRequester=@ReplyRequester
426
          ,IsConvert=@IsConvert
427
          ,AVEVAPersonInCharge=@AVEVAPersonInCharge
428
          ,AVEVAWorker=@AVEVAWorker
429
          ,AVEVAConvertDate=@AVEVAConvertDate
430
          ,AVEVAReviewDate=@AVEVAReviewDate
431
          ,AVEVAWorkDate=@AVEVAWorkDate
432
          ,AVEVAStatus=@AVEVAStatus
433
          ,AVEVAIssues=@AVEVAIssues
434
          ,ProdReviewer=@ProdReviewer
435
          ,ProdIsResult=@ProdIsResult
436
          ,ProdRemarks=@ProdRemarks
437
          ,ClientReviewer=@ClientReviewer
438
          ,ClientIsResult=@ClientIsResult
439
          ,ClientRemarks=@ClientRemarks
440
          ,DTIsGateWay=@DTIsGateWay
441
          ,DTIsImport=@DTIsImport
442
          ,DTIsRegSystem=@DTIsRegSystem
443
          ,DTRemarks=@DTRemarks
444
    where  RefProjectCode=@RefProjectCode and DocumentNo=@DocumentNo and IsDeleted=0
445

    
446
    if @@rowcount > 0
447
    begin
448
        select @DocID
449
    end
450
    else
451
    begin
452
        select ''
453
    end
454
end
455
else
456
begin
457
    --insert
458
    declare @tbdoc table(docid varchar(36))
459
    insert into dbo.Documents
460
    (
461
         DocID
462
        ,DocumentNo
463
        ,RevisonNo
464
        ,System
465
        ,SubSystemCode
466
        ,RefProjectCode
467
        ,JobLevel
468
        ,Simularity
469
        ,Simularity2
470
        ,PersonInCharge
471
        ,Worker
472
        ,RegisteredDate
473
        ,RegisteredUser
474
        ,ToIsDiscussion
475
        ,ToRemarks
476
        ,ToCreator
477
        ,FrReviewStatus
478
        ,FrRemarks
479
        ,FrCreator
480
        ,ID2StartDate
481
        ,ID2EndDate
482
        ,ID2Status
483
        ,ID2Issues
484
        ,ReplyModifications
485
        ,ReplyRequester
486
        ,IsConvert
487
        ,AVEVAPersonInCharge
488
        ,AVEVAWorker
489
        ,AVEVAConvertDate
490
        ,AVEVAReviewDate
491
        ,AVEVAWorkDate
492
        ,AVEVAStatus
493
        ,AVEVAIssues
494
        ,ProdReviewer
495
        ,ProdIsResult
496
        ,ProdRemarks
497
        ,ClientReviewer
498
        ,ClientIsResult
499
        ,ClientRemarks
500
        ,DTIsGateWay
501
        ,DTIsImport
502
        ,DTIsRegSystem
503
        ,DTRemarks
504
    )
505
    output inserted.DocID into @tbdoc
506
    values 
507
    (
508
         lower(newid())
509
        ,@DocumentNo
510
        ,case when isnull(@RevisonNo,'')='' then '0' else @RevisonNo end
511
        ,@System
512
        ,@SubSystemCode
513
        ,@RefProjectCode
514
        ,@JobLevel
515
        ,@Simularity
516
        ,@Simularity2
517
        ,@PersonInCharge
518
        ,@Worker
519
        ,getdate()
520
        ,@RegisteredUser
521
        ,@ToIsDiscussion
522
        ,@ToRemarks
523
        ,@ToCreator
524
        ,@FrReviewStatus
525
        ,@FrRemarks
526
        ,@FrCreator
527
        ,@ID2StartDate
528
        ,@ID2EndDate
529
        ,@ID2Status
530
        ,@ID2Issues
531
        ,@ReplyModifications
532
        ,@ReplyRequester
533
        ,@IsConvert
534
        ,@AVEVAPersonInCharge
535
        ,@AVEVAWorker
536
        ,@AVEVAConvertDate
537
        ,@AVEVAReviewDate
538
        ,@AVEVAWorkDate
539
        ,@AVEVAStatus
540
        ,@AVEVAIssues
541
        ,@ProdReviewer
542
        ,@ProdIsResult
543
        ,@ProdRemarks
544
        ,@ClientReviewer
545
        ,@ClientIsResult
546
        ,@ClientRemarks
547
        ,@DTIsGateWay
548
        ,@DTIsImport
549
        ,@DTIsRegSystem
550
        ,@DTRemarks
551
    )
552

    
553
    if @@rowcount > 0
554
    begin
555
        select docid from @tbdoc
556
    end
557
    else
558
    begin
559
        select ''
560
    end
561
end";
562
                        }
563
                        else
564
                        {
565
                            doc.ModifiedUser = userId;
566
                            query = $@"
567
update dbo.Documents
568
set    RevisonNo=case when isnull(@RevisonNo,'')='' then '0' else @RevisonNo end
569
      ,System=@System
570
      ,SubSystemCode=@SubSystemCode
571
      ,RefProjectCode=@RefProjectCode
572
      ,JobLevel=@JobLevel
573
      ,Simularity=@Simularity
574
      ,Simularity2=@Simularity2
575
      ,PersonInCharge=@PersonInCharge
576
      ,Worker=@Worker
577
      ,ModifiedDate=getdate()
578
      ,ModifiedUser=@ModifiedUser
579
      ,ToIsDiscussion=@ToIsDiscussion
580
      ,ToRemarks=@ToRemarks
581
      ,ToCreator=@ToCreator
582
      ,FrReviewStatus=@FrReviewStatus
583
      ,FrRemarks=@FrRemarks
584
      ,FrCreator=@FrCreator
585
      ,ID2StartDate=@ID2StartDate
586
      ,ID2EndDate=@ID2EndDate
587
      ,ID2Status=@ID2Status
588
      ,ID2Issues=@ID2Issues
589
      ,ReplyModifications=@ReplyModifications
590
      ,ReplyRequester=@ReplyRequester
591
      ,IsConvert=@IsConvert
592
      ,AVEVAPersonInCharge=@AVEVAPersonInCharge
593
      ,AVEVAWorker=@AVEVAWorker
594
      ,AVEVAConvertDate=@AVEVAConvertDate
595
      ,AVEVAReviewDate=@AVEVAReviewDate
596
      ,AVEVAWorkDate=@AVEVAWorkDate
597
      ,AVEVAStatus=@AVEVAStatus
598
      ,AVEVAIssues=@AVEVAIssues
599
      ,ProdReviewer=@ProdReviewer
600
      ,ProdIsResult=@ProdIsResult
601
      ,ProdRemarks=@ProdRemarks
602
      ,ClientReviewer=@ClientReviewer
603
      ,ClientIsResult=@ClientIsResult
604
      ,ClientRemarks=@ClientRemarks
605
      ,DTIsGateWay=@DTIsGateWay
606
      ,DTIsImport=@DTIsImport
607
      ,DTIsRegSystem=@DTIsRegSystem
608
      ,DTRemarks=@DTRemarks
609
where  DocID=@DocID
610

    
611
if @@rowcount > 0
612
begin
613
    select @DocID
614
end
615
else
616
begin
617
    select ''
618
end;";
619
                        }
620
                        string refID = base.QueryFirstOrDefault<string>(query, doc, transaction);
621

    
622
                        if (doc.AttFiles != null && doc.AttFiles.Count > 0)
623
                        {
624
                            string attDelIDList = string.Join("','", doc.AttFiles.Where(x => !string.IsNullOrEmpty(x.FileID)).Select(x => x.FileID).ToList());
625

    
626
                            if (!string.IsNullOrEmpty(refID) && attDelIDList.Length > 0)
627
                            {
628
                                query = $@"
629
delete from dbo.AttachFIles
630
where  RefID=@RefID and FileID in ('{attDelIDList}');";
631
                                base.Execute(query, new { RefID = refID }, transaction);
632
                            }
633

    
634
                            foreach (AttFileInfo attFile in doc.AttFiles)
635
                            {
636
                                if (string.IsNullOrEmpty(attFile.RefID))
637
                                {
638
                                    attFile.RefID = refID;
639
                                    attFile.Creator = userId;
640

    
641
                                    query = $@"
642
insert into dbo.AttachFIles (FileID,RefID,Category,FileType,FileName,FilePath,FileExtension,FileData,Creator)
643
values
644
(
645
    lower(newid())
646
   ,@RefID
647
   ,@Category
648
   ,@FileType
649
   ,@FileName
650
   ,@FilePath
651
   ,@FileExtension
652
   ,@FileData
653
   ,@Creator
654
)";
655

    
656
                                    base.Execute(query, attFile, transaction);
657
                                }
658
                            }
659
                        }
660
                    }
661

    
662
                    transaction.Commit();
663
                    isSuccess = true;
664
                }
665
            }
666
            catch (Exception ex)
667
            {
668
                throw ex;
669
            }
670

    
671
            return isSuccess;
672
        }
673

    
674
        public Documents SetDocumentDataField(Documents doc, string userId)
675
        {
676
            Documents resultData = null;
677

    
678
            try
679
            {
680
                using (var transaction = base.BeginTransaction())
681
                {
682
                    string query = string.Empty;
683

    
684
                    if (!string.IsNullOrEmpty(doc.DocID))
685
                    {
686
                        StringBuilder sbSet = new StringBuilder();
687
                        var parameters = new Dictionary<string, object>();
688

    
689
                        #region Update 할 목록
690
                        if (doc.ID2StartDate != null)
691
                        {
692
                            sbSet.Append(" ,ID2StartDate=(case when ID2StartDate is null then @DateTimeNow else ID2StartDate end) ");
693
                            parameters.Add("ID2StartDate", doc.ID2StartDate);
694
                        }
695

    
696
                        if (!string.IsNullOrEmpty(doc.Worker))
697
                        {
698
                            sbSet.Append(" ,Worker=@Worker ");
699
                            parameters.Add("Worker", doc.Worker);
700
                        }
701
                        #endregion
702

    
703
                        if (parameters.Count > 0)
704
                        {
705
                            sbSet.Append(" ,ModifiedUser=@ModifiedUser ");
706
                            parameters.Add("ModifiedUser", userId);
707

    
708
                            parameters.Add("DocID", doc.DocID);
709

    
710
                            query = $@"
711
declare @DateTimeNow datetime
712
set @DateTimeNow = getdate()
713

    
714
update dbo.Documents
715
set    ModifiedDate=@DateTimeNow {sbSet}
716
where  [DocID]=@DocID
717

    
718
if @@rowcount > 0
719
begin
720
    select * from dbo.Documents where DocID=@DocID
721
end
722
else
723
begin
724
    select * from dbo.Documents where 1=2
725
end;";
726
                            resultData = base.QueryFirstOrDefault<Documents>(query, parameters, transaction);
727
                        }
728
                    }
729

    
730
                    transaction.Commit();
731
                }
732
            }
733
            catch (Exception ex)
734
            {
735
                throw ex;
736
            }
737

    
738
            return resultData;
739
        }
740

    
741
        public bool SetDocumentDatasField(List<Documents> docs, string userId)
742
        {
743
            bool isSuccess = false;
744

    
745
            try
746
            {
747
                using (var transaction = base.BeginTransaction())
748
                {
749
                    foreach (Documents doc in docs)
750
                    {
751
                        string query = string.Empty;
752

    
753
                        if (!string.IsNullOrEmpty(doc.DocID))
754
                        {
755
                            StringBuilder sbSet = new StringBuilder();
756
                            var parameters = new Dictionary<string, object>();
757

    
758
                            #region Update 할 목록
759
                            if (doc.ID2EndDate != null)
760
                            {
761
                                sbSet.Append(" ,ID2EndDate=@ID2EndDate ");
762
                                parameters.Add("ID2EndDate", doc.ID2EndDate);
763
                            }
764
                            #endregion
765

    
766
                            if (parameters.Count > 0)
767
                            {
768
                                sbSet.Append(" ,ModifiedUser=@ModifiedUser ");
769
                                parameters.Add("ModifiedUser", userId);
770

    
771
                                parameters.Add("DocID", doc.DocID);
772

    
773
                                query = $@"
774
update dbo.Documents
775
set    ModifiedDate=getdate() {sbSet}
776
where  [DocID]=@DocID;";
777
                                base.Execute(query, parameters, transaction);
778
                            }
779
                        }
780
                    }
781
                    transaction.Commit();
782
                    isSuccess = true;
783
                }
784
            }
785
            catch (Exception ex)
786
            {
787
                throw ex;
788
            }
789

    
790
            return isSuccess;
791
        }
792

    
793

    
794
        //ID2
795
        public IEnumerable<ID2Drawings> GetID2DrawingsByProject(ID2ProjectInfo id2Info)
796
        {
797
            try
798
            {
799
                string query = $@"
800
select @Name PROJECTNAME
801
      ,dw.[UID], dw.[NAME], left(dw.[NAME], len(dw.[NAME]) - dw.lastidx) DOCNAME
802
      ,case when rtrim(ltrim(isnull(convert(varchar, dw.[DATETIME]),''))) = '' then null else convert(datetime, convert(varchar, dw.[DATETIME])) end [DATETIME]
803
      ,dw.OCCUPIED, dw.[Image]
804
from
805
(
806
    select [UID], [NAME], [DATETIME], OCCUPIED, [Image], charindex('.', reverse([NAME])) lastidx
807
    from   dbo.Drawings
808
) dw;";
809
                return Query<ID2Drawings>(query, id2Info);
810
            }
811
            catch (Exception ex)
812
            {
813
                throw ex;
814
            }
815
        }
816

    
817
        /// <summary>
818
        /// 주어진 이름을 가진 심볼을 조회한다.
819
        /// </summary>
820
        /// <param name="id2Info"></param>
821
        /// <param name="Name"></param>
822
        /// <returns></returns>
823
        public IEnumerable<ID2Symbol> FindID2Symbols(string Name)
824
        {
825
            string query = $@"select Name, T.[Type], OriginalPoint, ConnectionPoint, Width, Height 
826
                    from Symbol A join SymbolType T on A.SymbolType_UID=T.UID where A.Name like @Name";
827
            return Query<ID2Symbol>(query, new { Name = $"%{Name}%" });
828
        }
829

    
830

    
831
        //Transactions
832
        public int GetTranKey(string userId, string projectIDs)
833
        {
834
            int result = -1;
835

    
836
            try
837
            {
838
                var dynamicParameters = new DynamicParameters();
839

    
840
                var parameters = new Dictionary<string, object>()
841
                {
842
                    { "UserId", userId },
843
                    { "ProjectIDs", projectIDs }
844
                };
845

    
846
                dynamicParameters.AddDynamicParams(parameters);
847

    
848
                using (var transaction = base.BeginTransaction())
849
                {
850
                    string query = $@"
851
--log master 입력
852
insert into dbo.Transactions (UserId, ProjectID)
853
values (@UserId, @ProjectIDs);
854
select scope_identity();";
855

    
856
                    result = base.ExecuteScalar<int>(query, dynamicParameters, transaction);
857

    
858
                    transaction.Commit();
859
                }
860
            }
861
            catch (Exception ex)
862
            {
863
                throw ex;
864
            }
865

    
866
            return result;
867
        }
868

    
869
        public bool SetTran(int seq, bool isMgt, bool isStart, int itemCount, int markusItemCount)
870
        {
871
            bool result = false;
872

    
873
            try
874
            {
875
                var dynamicParameters = new DynamicParameters();                
876
                var parameters = new Dictionary<string, object>()
877
                {
878
                    { "Seq", seq },
879
                    { "ItemCount", itemCount },
880
                    { "MarkusItemCount", markusItemCount }
881
                };
882
                dynamicParameters.AddDynamicParams(parameters);
883
                StringBuilder sbWhere = new StringBuilder();
884
                if (isMgt)
885
                {
886
                    if (isStart)
887
                    {
888
                        sbWhere.Append("StartDate=getdate(), ItemCount=@ItemCount");
889
                    }
890
                    else
891
                    {
892
                        sbWhere.Append("EndDate=getdate()");
893
                    }
894
                    
895
                }
896
                else
897
                {
898
                    if (isStart)
899
                    {
900
                        sbWhere.Append("MarkusStartDate=getdate(), MarkusItemCount=@MarkusItemCount");
901
                    }
902
                    else
903
                    {
904
                        sbWhere.Append("MarkusEndDate=getdate()");
905
                    }
906
                }
907

    
908
                using (var transaction = base.BeginTransaction())
909
                {
910
                    string query = $@"
911
update dbo.Transactions
912
set    {sbWhere}
913
where Seq=@Seq;";
914
                    base.Execute(query, dynamicParameters, transaction);
915

    
916
                    transaction.Commit();
917

    
918
                    result = true;
919
                }
920
            }
921
            catch (Exception ex)
922
            {
923
                throw ex;
924
            }
925

    
926
            return result;
927
        }
928

    
929
        public string GetTranData(int seq)
930
        {
931
            try
932
            {
933
                var dynamicParameters = new DynamicParameters();
934
                var parameters = new Dictionary<string, object>()
935
                {
936
                    { "Seq", seq }
937
                };
938
                dynamicParameters.AddDynamicParams(parameters);
939

    
940
                string query = $@"
941
select *
942
from   dbo.Transactions
943
where  Seq=@Seq";
944

    
945
                IEnumerable<dynamic> rows = base.Query<dynamic>(query, dynamicParameters);
946

    
947
                return this.ToSerializeData(rows);
948
            }
949
            catch (Exception ex)
950
            {
951
                throw ex;
952
            }
953
        }
954

    
955
        public string ToSerializeData(IEnumerable<dynamic> items)
956
        {
957
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
958

    
959
            if (items == null) return string.Empty;
960
            var datas = items.ToArray();
961
            if (datas.Length == 0) return string.Empty;
962

    
963
            foreach (var data in datas)
964
            {
965
                var dicItem = new Dictionary<string, object>();
966
                foreach (var pair in ((IDictionary<string, object>)data))
967
                {
968
                    dicItem.Add(pair.Key, pair.Value);
969
                }
970
                list.Add(dicItem);
971
            }
972

    
973
            return JsonConvert.SerializeObject(list);
974
        }
975

    
976
        public IEnumerable<Documents> GetTrDocuments(int seq)
977
        {
978
            var dynamicParameters = new DynamicParameters();
979
            StringBuilder sbWhere = new StringBuilder();
980
            var parameters = new Dictionary<string, object>()
981
            {
982
                { "Seq", seq }
983
            };
984
            dynamicParameters.AddDynamicParams(parameters);
985

    
986
            try
987
            {
988
                string query = $@"
989
declare @CreatedDate datetime
990
declare @EndDate datetime
991
declare @ProjectGroupID varchar(4000)
992

    
993
select top 1 @CreatedDate=CreatedDate, @EndDate=EndDate, @ProjectGroupID=ProjectID
994
from   dbo.Transactions
995
where  Seq=@Seq
996

    
997
--select RefProjectCode, DocumentNo
998
--from   dbo.Documents
999
--where  RefProjectCode in (select Code from dbo.Projects where ParentID=@ProjectGroupID)
1000
--   and RegisteredDate between @CreatedDate and @EndDate
1001

    
1002
select RefProjectCode, DocumentNo
1003
from   dbo.Documents
1004
where  RefProjectCode is not null and ((RegisteredDate between @CreatedDate and @EndDate) or (ModifiedDate between @CreatedDate and @EndDate))";
1005

    
1006
                if (parameters.Count > 0)
1007
                {
1008
                    dynamicParameters.AddDynamicParams(parameters);
1009
                }
1010

    
1011
                return Query<Documents>(query, dynamicParameters);
1012
            }
1013
            catch (Exception ex)
1014
            {
1015
                throw ex;
1016
            }
1017
        }
1018

    
1019
        public class MarkusConvert
1020
        {
1021
            public string PROJECT_NO { get; set; }
1022
            public string DOCUMENT_ID { get; set; }
1023
            public int STATUS { get; set; }
1024
        }
1025

    
1026
    }
1027
}
클립보드 이미지 추가 (최대 크기: 500 MB)