MultiTool/MultiTool.Form/frmImportMain.vb
2022-05-13 15:16:52 +02:00

935 lines
37 KiB
VB.net

Imports System.IO
Imports System.Net.Http
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraReports.UI
Imports DigitalData.GUIs.Common
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging
Imports MultiTool.Common
Imports MultiTool.Common.Documents
Imports MultiTool.Common.Templates
Imports MultiTool.Common.Winline
Imports MultiTool.Common.Winline.Entities
Imports MultiTool.Common.Constants
Imports MultiTool.Common.Exceptions
Public Class frmImportMain
Public LogConfig As LogConfig
Public ConfigManager As ConfigManager(Of Config)
Private Logger As Logger
Private Database As MSSQLServer
Private Winline As WinlineData
Private FileEx As DigitalData.Modules.Filesystem.File
Private WebService As WebServiceData
Private DocumentLoader As Documents.DocumentLoader
Private DocumentCleaner As Documents.DocumentCleaner
Private ReportGenerator As ReportGenerator(Of OrderReport)
Private FormHelper As FormHelper
Private Grids As List(Of GridControl)
Private GridLoader As GridLoader
Private GridBuilder As GridBuilder
Private ReadOnly CurrentTemplate As Template = Nothing
' Runtime variables
Private CurrentGrid As GridControl = Nothing
Private CurrentDocument As Document = Nothing
Private CurrentDocumentReadOnly As Boolean = False
Private FilesLoading As Boolean = False
Public Sub New(pLogConfig As LogConfig, pConfigManager As ConfigManager(Of Config), pTemplate As Template)
InitializeComponent()
LogConfig = pLogConfig
ConfigManager = pConfigManager
CurrentTemplate = pTemplate
End Sub
Private Sub WebService_Progress(sender As Object, e As String)
SplashScreenManager.SetWaitFormDescription(e)
End Sub
#Region "Form Events"
Private Sub frmImportMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Logger = LogConfig.GetLogger()
FormHelper = New FormHelper(LogConfig, Me)
' Initialize Database
Dim oConnectionString = MSSQLServer.DecryptConnectionString(ConfigManager.Config.ConnectionString)
Database = New MSSQLServer(LogConfig, oConnectionString)
GridBuilder = New GridBuilder(GridViewFiles, GridView1, GridView2, GridView3, GridView4).
WithDefaults().
WithReadOnlyOptions().
WithClipboardHandler()
GridViewFiles.OptionsView.ShowAutoFilterRow = False
Winline = My.Winline
FileEx = New DigitalData.Modules.Filesystem.File(LogConfig)
WebService = New WebServiceData(LogConfig, Database, Winline, My.GeneralConfiguration.Webservice, My.GeneralConfiguration)
AddHandler WebService.WebServiceProgress, AddressOf WebService_Progress
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Initialisieren_der_Anwendungs_Daten)
End Try
Text = String.Format(My.Resources.frmShared._0____WebService_Multitool_für_WinLine, CurrentTemplate.Name)
End Sub
Private Async Sub frmImportMain_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
btnLoadFiles.Enabled = False
SplashScreenManager.ShowWaitForm()
Try
SplashScreenManager.SetWaitFormDescription(My.Resources.frmImportMainExtra.Lade_Oberfläche)
lookupMandator.Properties.DataSource = Winline.Mandators
lookupMandator.ForceInitialize()
lookupMandator.Properties.View.BestFitColumns()
DocumentLoader = New DocumentLoader(LogConfig, Winline, Database,
My.MappingConfiguration,
My.TemplateConfiguration,
My.GeneralConfiguration,
ConfigManager.Config)
DocumentCleaner = New DocumentCleaner(LogConfig, CurrentTemplate)
GridLoader = New GridLoader(LogConfig)
ReportGenerator = New ReportGenerator(Of OrderReport)(LogConfig, Database, My.TemplateConfiguration, My.GeneralConfiguration)
SplashScreenManager.SetWaitFormDescription(My.Resources.frmImportMainExtra.Lade_Vorlagen)
Grids = CreateGridsAndColumns(CurrentTemplate)
For Each oGrid As GridControl In Grids
AddHandler oGrid.GotFocus, AddressOf Grid_Focus
Next
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Laden_der_Winline_Daten)
Finally
SplashScreenManager.CloseWaitForm()
btnLoadFiles.Enabled = True
End Try
Await LoadFiles()
End Sub
Private Sub frmImportMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Try
DocumentCleaner.CleanImportedDocuments(DocumentLoader.Files)
Catch ex As Exception
FormHelper.ShowError(ex, "Beenden der Anwendung")
End Try
End Sub
Private Async Function frmImportMain_KeyDown(sender As Object, e As KeyEventArgs) As Task Handles MyBase.KeyDown
If e.KeyCode = Keys.F5 Then
Await LoadFiles()
End If
End Function
Private Sub txtCurrentFile_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles txtCurrentFile.ItemClick
If CurrentDocument IsNot Nothing Then
TryOpenFile(CurrentDocument.FullName, My.Resources.frmImportMainExtra.Aktuelle_Datei)
End If
End Sub
#End Region
#Region "Grid Events"
Private Sub GridViewFiles_CustomDrawCell(sender As Object, e As Views.Base.RowCellCustomDrawEventArgs) Handles GridViewFiles.CustomDrawCell
Try
Dim oDocument As Document = GridViewFiles.GetRow(e.RowHandle)
If oDocument.Equals(CurrentDocument) Then
e.Appearance.Options.UseBackColor = True
e.Appearance.BackColor = Color.LightYellow
End If
If oDocument.HasErrors Then
e.Appearance.Options.UseBackColor = True
e.Appearance.BackColor = Color.LightCoral
End If
If oDocument.HasErrors And oDocument.Equals(CurrentDocument) Then
e.Appearance.Options.UseBackColor = True
e.Appearance.BackColor = Color.Coral
End If
If oDocument.Imported Then
e.Appearance.Options.UseBackColor = True
e.Appearance.BackColor = Color.LightGreen
End If
If oDocument.Imported And oDocument.Equals(CurrentDocument) Then
e.Appearance.Options.UseBackColor = True
e.Appearance.BackColor = Color.Green
End If
Catch ex As Exception
Logger.Error(ex)
End Try
End Sub
Private Sub GridView_CustomDrawCell(sender As Object, e As Views.Base.RowCellCustomDrawEventArgs)
Dim oView As GridView = sender
If e.RowHandle < 0 Or CurrentDocument Is Nothing Then
Exit Sub
End If
Dim oObject As DataRowView = oView.GetRow(e.RowHandle)
Dim oGuid = oObject.Row.Item(COLUMN_GUID)
Dim oRow As DocumentRow = CurrentDocument.Rows.
Where(Function(r) r.Id.ToString = oGuid).
SingleOrDefault()
If oRow Is Nothing Then
Exit Sub
End If
If oRow.HasErrors Then
Dim oColumName = e.Column.FieldName
Dim oErrorFields = oRow.Fields.
Where(Function(field) field.Value.HasError).
Select(Function(field) field.Key).
ToList()
If oErrorFields.Count > 0 AndAlso oErrorFields.Contains(oColumName) Then
e.Appearance.Options.UseBackColor = True
e.Appearance.BackColor = Color.LightCoral
End If
End If
End Sub
Private Sub Grid_Focus(sender As GridControl, e As EventArgs)
CurrentGrid = sender
End Sub
Private Sub Grid_MouseDoubleClick(sender As Object, e As MouseEventArgs)
Dim oGrid As GridControl = DirectCast(sender, GridControl)
Dim oView As GridView = DirectCast(oGrid.FocusedView, GridView)
Dim oHitInfo = oView.CalcHitInfo(e.Location)
If Not oHitInfo.InDataRow Then
Exit Sub
End If
Dim oRow As DataRow = oView.GetFocusedDataRow()
Dim oModifiedRow = EditRow(oRow, oView)
If oModifiedRow IsNot Nothing Then
ReloadRow(oModifiedRow)
End If
End Sub
Private Sub GridViewFiles_FocusedRowChanged(sender As Object, e As Views.Base.FocusedRowChangedEventArgs) Handles GridViewFiles.FocusedRowChanged
Try
FilesLoading = True
SplitContainerMain.Panel2.Enabled = True
Dim oDocument As Document = GridViewFiles.GetRow(e.FocusedRowHandle)
If oDocument Is Nothing Then
Exit Sub
End If
If oDocument.Mandator Is Nothing Then
lookupMandator.EditValue = Nothing
lookupMandator.BackColor = Color.LightCoral
End If
lookupMandator.EditValue = oDocument.Mandator
LoadDocument(oDocument)
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Laden_des_Dokuments)
Finally
FilesLoading = False
End Try
End Sub
#End Region
#Region "Ribbon Events"
Private Async Sub btnCalculatePrices_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnCalculatePrices.ItemClick
Dim oCurrentMandator As Mandator = TryCast(lookupMandator.EditValue, Mandator)
If oCurrentMandator Is Nothing Then
MsgBox(My.Resources.frmImportMainExtra.Bitte_wählen_Sie_einen_Mandanten_aus__bevor_Sie_fortfahren, MsgBoxStyle.Exclamation, Text)
Exit Sub
End If
BeginLoadingUI()
SplashScreenManager.SetWaitFormDescription("Lade Preisinformationen..")
Dim oStopWatch As New Stopwatch()
Try
oStopWatch.Start()
Dim oNewDocument = Await DocumentLoader.MaybeApplyPriceFunctions(CurrentDocument, oCurrentMandator, CurrentTemplate)
oStopWatch.Stop()
DocumentLoader.ReplaceDocument(oNewDocument)
LoadDocument(oNewDocument)
Catch ex As Exception
FormHelper.ShowError(ex, "Laden der Preisinformationen")
Finally
EndLoadingUI()
Logger.Debug("Loading Priceinfo took [{0}] ms", oStopWatch.ElapsedMilliseconds)
End Try
End Sub
Private Sub btnOpenLogDirectory2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnOpenLogDirectory2.ItemClick
FormHelper.TryOpenDirectory(LogConfig.LogDirectory, My.Resources.frmImportMainExtra.Logverzeichnis)
End Sub
Private Sub btnDebugExportReport_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnDebugExportReport.ItemClick
' Get the document
Dim oDocument As Document = GridViewFiles.GetRow(GridViewFiles.FocusedRowHandle)
' Generate the report
Dim oReportResult = ReportGenerator.GenerateReport(oDocument, CurrentTemplate)
Dim oFileInfo = New FileInfo(oReportResult.FileName)
' Export it to pdf
oReportResult.Report.ExportToPdf(oReportResult.FileName)
Dim oMessage = $"Die Datei wurde im Verzeichnis '{oFileInfo.Directory}' abgelegt. Möchten Sie die Datei jetzt öffnen?"
Dim oDialogResult = MsgBox(oMessage, MsgBoxStyle.Question Or MsgBoxStyle.YesNo, Text)
If oDialogResult = MsgBoxResult.Yes Then
Try
Process.Start(oReportResult.FileName)
Catch ex As Exception
FormHelper.ShowError(ex, "Export Report")
End Try
End If
End Sub
Private Async Sub btnTestTransferFile_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnTestTransferFile.ItemClick
Try
BeginLoadingUI()
' Get the document
Dim oDocument As Document = GridViewFiles.GetRow(GridViewFiles.FocusedRowHandle)
' Check for errors and abort
If oDocument.HasErrors = True Then
FormHelper.ShowWarning("Diese Datei kann noch nicht übertragen werden, da sie noch Fehler oder fehlende Werte enthält.")
Exit Sub
End If
Dim oResult = Await TransferFile(oDocument, pIsTest:=True)
If oResult = True Then
MsgBox(My.Resources.frmImportMainExtra.Datei_erfolgreich_in_die_WinLine_übertragen, MsgBoxStyle.Information, Text)
End If
Catch ex As HttpRequestException
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Übertragung_zur_WinLine, My.Resources.frmImportMainExtra.Die_Verbindung_zum_WinLine_Server_ist_fehlgeschlagen)
Catch ex As TaskCanceledException
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Übertragung_zur_WinLine, My.Resources.frmImportMainExtra.Die_Verbindung_zum_WinLine_Server_ist_fehlgeschlagen)
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Übertragung_zur_WinLine)
Finally
EndLoadingUI()
End Try
End Sub
Private Async Sub btnTransferFile_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnTransferFile.ItemClick
Try
BeginLoadingUI()
' Get the document
Dim oDocument As Document = GridViewFiles.GetRow(GridViewFiles.FocusedRowHandle)
' Check for errors and abort
If oDocument.HasErrors = True Then
FormHelper.ShowWarning("Diese Datei kann noch nicht übertragen werden, da sie noch Fehler oder fehlende Werte enthält.")
Exit Sub
End If
Dim oResult = Await TransferFile(oDocument, pIsTest:=False)
If oResult = True Then
MsgBox(My.Resources.frmImportMainExtra.Datei_erfolgreich_in_die_WinLine_übertragen, MsgBoxStyle.Information, Text)
End If
Catch ex As HttpRequestException
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Übertragung_zur_WinLine, My.Resources.frmImportMainExtra.Die_Verbindung_zum_WinLine_Server_ist_fehlgeschlagen)
Catch ex As TaskCanceledException
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Übertragung_zur_WinLine, My.Resources.frmImportMainExtra.Die_Verbindung_zum_WinLine_Server_ist_fehlgeschlagen)
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Übertragung_zur_WinLine)
Finally
EndLoadingUI()
End Try
End Sub
Private Async Sub btnTransferAllFiles_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnTransferAllFiles.ItemClick
Try
BeginLoadingUI()
' Get the documents
Dim oSelectedRows = GridViewFiles.GetSelectedRows()
If oSelectedRows.Length = 0 Then
Exit Sub
End If
Dim oDocuments As List(Of Document) = oSelectedRows.
Select(Of Document)(Function(rowHandle) GridViewFiles.GetRow(rowHandle)).
ToList()
Dim oFailedDocuments As New List(Of String)
Dim oSuccessfulDocuments As Integer = 0
For Each oDocument As Document In oDocuments
Try
Await TransferFile(oDocument)
Catch ex As Exception
Logger.Error(ex)
oFailedDocuments.Add(ex.Message)
End Try
Next
oSuccessfulDocuments = oDocuments.Count - oFailedDocuments.Count
If oSuccessfulDocuments > 0 Then
Dim oMessage = String.Format(My.Resources.frmImportMainExtra._0__Dateien_erfolgreich_in_die_Winline_übertragen_, oSuccessfulDocuments)
MsgBox(oMessage, MsgBoxStyle.Information, Text)
End If
If oFailedDocuments.Count > 0 Then
Dim oErrorMessages = String.Join(vbNewLine, oFailedDocuments)
Dim oFailedCount = oFailedDocuments.Count
Dim oMessage = $"Für {oFailedCount} Dateien ist die Übertragung in die Winline fehlgeschlagen. Folgende Fehler sind aufgetreten: {oErrorMessages}{vbNewLine}"
MsgBox(oMessage, MsgBoxStyle.Exclamation, Text)
End If
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Übertragung_zur_WinLine)
Finally
EndLoadingUI()
End Try
End Sub
Private Sub btnEditRow_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnEditRow.ItemClick
Dim oGrid As GridControl = DirectCast(CurrentGrid, GridControl)
Dim oView As GridView = DirectCast(oGrid.FocusedView, GridView)
Dim oRow As DataRow = oView.GetFocusedDataRow()
If oRow Is Nothing Then
Exit Sub
End If
Dim oModifiedRow = EditRow(oRow, oView)
If oModifiedRow IsNot Nothing Then
ReloadRow(oModifiedRow)
End If
End Sub
Private Async Function btnLoadFiles_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) As Task Handles btnLoadFiles.ItemClick
Await LoadFiles()
End Function
Private Async Sub btnReloadFile_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnReloadFile.ItemClick
Dim oCurrentMandator As Mandator = TryCast(lookupMandator.EditValue, Mandator)
'If oCurrentMandator Is Nothing Then
' MsgBox(My.Resources.frmImportMainExtra.Bitte_wählen_Sie_einen_Mandanten_aus__bevor_Sie_fortfahren, MsgBoxStyle.Exclamation, Text)
' Exit Sub
'End If
Dim oMessage = String.Format(My.Resources.frmImportMainExtra.Wollen_Sie_wirklich_die_aktuelle_Datei_neu_laden, oCurrentMandator)
Dim oResult As DialogResult = MsgBox(oMessage, MsgBoxStyle.Question Or MsgBoxStyle.YesNo, Text)
If oResult = DialogResult.Yes Then
Await ReloadFile()
End If
End Sub
Private Sub btnOpenInputDirectory_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnOpenInputDirectory.ItemClick
FormHelper.TryOpenDirectory(CurrentTemplate.InputDirectory, My.Resources.frmImportMainExtra.Eingangsverzeichnis)
End Sub
Private Sub btnOpenOutputDirectory_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnOpenOutputDirectory.ItemClick
FormHelper.TryOpenDirectory(CurrentTemplate.OutputDirectory, My.Resources.frmImportMainExtra.Ausgabeverzeichnis)
End Sub
Private Sub btnOpenSchemaDirectory_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnOpenSchemaDirectory.ItemClick
FormHelper.TryOpenDirectory(My.GeneralConfiguration.TemplateDirectory, My.Resources.frmImportMainExtra.Vorlagenverzeichnis)
End Sub
Private Sub btnShowXml_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnShowXml.ItemClick
Dim oForm As New frmXmlEditor With {.FileName = CurrentDocument.FullName}
oForm.Show()
End Sub
Private Sub btnRemoveRow_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnRemoveRow.ItemClick
If CurrentGrid Is Nothing Then
Exit Sub
End If
Dim oMessage As String = My.Resources.frmImportMainExtra.Wollen_Sie_die_ausgewählte_Zeile_wirklich_löschen_
If MsgBox(oMessage, MsgBoxStyle.Question Or MsgBoxStyle.YesNo, Text) = MsgBoxResult.Yes Then
' Get GUID of currently selected row
Dim oView As GridView = CurrentGrid.FocusedView
Dim oRow As DataRowView = oView.GetRow(oView.FocusedRowHandle)
Dim oGuid = oRow.Row.Item(COLUMN_GUID)
' Get currently selected document
Dim oDocument As Document = GridViewFiles.GetRow(GridViewFiles.FocusedRowHandle)
Dim oNewRows = oDocument.Rows.
Where(Function(r) r.Id.ToString <> oGuid).
ToList()
oDocument.Rows = oNewRows
Dim oIndex = DocumentLoader.Files.IndexOf(oDocument)
DocumentLoader.Files.Item(oIndex) = oDocument
lookupMandator.EditValue = oDocument.Mandator
LoadDocument(oDocument)
End If
End Sub
Private Sub btnOpenReport_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnOpenReport.ItemClick
Try
If CurrentDocumentReadOnly = True Then
FormHelper.ShowWarning("Bitte wählen Sie zunächst einen Mandanten aus, bevor Sie diese Datei exportieren!")
Exit Sub
End If
SplashScreenManager.ShowWaitForm()
SplashScreenManager.SetWaitFormDescription(My.Resources.frmImportMainExtra.Erstellen_der_Berichtsvorschau)
SetDocumentButtonsEnabled(False)
GridControlFiles.Enabled = False
btnLoadFiles.Enabled = False
SplitContainerGrids.Enabled = False
Dim oDocument As Document = GridViewFiles.GetRow(GridViewFiles.FocusedRowHandle)
Dim oReportGenerator = New ReportGenerator(Of OrderReport)(LogConfig, Database,
My.TemplateConfiguration,
My.GeneralConfiguration)
Dim oResult = oReportGenerator.GenerateReport(oDocument, CurrentTemplate)
Dim oPrintTool As New ReportPrintTool(oResult.Report)
oPrintTool.Report.CreateDocument(False)
oPrintTool.ShowPreview()
SplitContainerGrids.Enabled = True
btnLoadFiles.Enabled = True
GridControlFiles.Enabled = True
SetDocumentButtonsEnabled(True)
SplashScreenManager.CloseWaitForm()
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Erstellen_der_Berichtsvorschau)
End Try
End Sub
#End Region
#Region "Methods"
Private Sub LoadDocument(pDocument As Document)
Try
Dim oDatasources As New Dictionary(Of String, DataTable)
' Reset datasource so that all data will be refreshed
For Each oGrid In Grids
oGrid.DataSource = Nothing
Next
' Create initial Datatable for each Root Element
For Each oTable In CurrentTemplate.Tables
Dim oDataTable As New DataTable()
' This is makes it possible to fetch the DocumentRow later
oDataTable.Columns.Add(New DataColumn(COLUMN_GUID))
For Each oColumn In oTable.Columns
oDataTable.Columns.Add(New DataColumn(oColumn.Name))
Next
oDatasources.Add(oTable.Name, oDataTable)
Next
' List of Root Elements in XML
For Each oRow In pDocument.Rows
' Grab grid for the current DocumentRow
Dim oGrid As GridControl = Grids.
Where(Function(g) g.Name = oRow.TableName).
SingleOrDefault()
' Grab table for the current DocumentRow and create new row
Dim oDataTable As DataTable = oDatasources.Item(oRow.TableName)
Dim oDataRow = oDataTable.NewRow()
' Assign the Guid of the DocumentRow
oDataRow.Item(COLUMN_GUID) = oRow.Id.ToString
' Set values for the current row
For Each oField In oRow.Fields
If oDataTable.Columns.Contains(oField.Key) Then
oDataRow.Item(oField.Key) = oField.Value
Else
Logger.Warn("Element [{0}] from files does not exist in Schema. Skipping.", oField.Key)
End If
Next
' Add row to the current table
oDataTable.Rows.Add(oDataRow)
oDataTable.AcceptChanges()
' Finally load data into grid
oGrid.DataSource = oDataTable
Next
txtCurrentFile.Caption = String.Format(My.Resources.frmImportMainExtra.Aktuelle_Datei___0_, pDocument.FileName)
If pDocument.Errors.Count > 0 Then
txtErrors.Caption = String.Format("Fehler: {0}", pDocument.Errors.Count)
txtErrors.Visibility = DevExpress.XtraBars.BarItemVisibility.Always
Else
txtErrors.Visibility = DevExpress.XtraBars.BarItemVisibility.Never
End If
If pDocument.HasErrors = True Then
btnCalculatePrices.Enabled = False
btnShowErrors.Enabled = True
Else
btnCalculatePrices.Enabled = True
btnShowErrors.Enabled = False
End If
If pDocument.Mandator Is Nothing Then
RibbonPageGroupEdit.Enabled = False
RibbonPageGroupTransfer.Enabled = False
CurrentDocumentReadOnly = True
'MsgBox("Für die aktuelle Datei konnte kein Mandant zugeordnet werden! Bitte wählen Sie einen aus und laden Sie dann die Datei erneut.", MsgBoxStyle.Critical, Text)
Else
RibbonPageGroupEdit.Enabled = True
RibbonPageGroupTransfer.Enabled = True
CurrentDocumentReadOnly = False
End If
CurrentDocument = pDocument
SetDocumentButtonsEnabled(True)
Catch ex As Exception
SetDocumentButtonsEnabled(False)
Logger.Error(ex)
Throw ex
End Try
End Sub
Private Sub ReloadRow(pRow As DocumentRow)
Dim oModifiedRow = pRow
Dim oIndex = CurrentDocument.Rows.IndexOf(oModifiedRow)
CurrentDocument.Rows.Item(oIndex) = oModifiedRow
LoadDocument(CurrentDocument)
' Refresh Files to update Row color
GridViewFiles.RefreshData()
End Sub
Private Async Function LoadFiles() As Task
Try
BeginLoadingUI()
FilesLoading = True
DocumentCleaner.CleanImportedDocuments(DocumentLoader.Files)
Logger.Debug("Loading [{0}] files", DocumentLoader.Files.Count)
AddHandler DocumentLoader.FileLoadComplete, Sub(_sender As Object, _e As Documents.DocumentLoader.FileLoadInfo)
Dim oMessage = String.Format("Lade Dateien ({0}/{1})", _e.FilesLoaded, _e.FilesTotal)
SplashScreenManager.SetWaitFormCaption(oMessage)
End Sub
AddHandler DocumentLoader.FileLoadProgress, Sub(_sender As Object, _e As Documents.DocumentLoader.FileLoadProgressInfo)
SplashScreenManager.SetWaitFormDescription(_e.RunningFunction)
End Sub
SplashScreenManager.SetWaitFormCaption(String.Format("Lade Dateien ({0}/{1})", 0, DocumentLoader.Files.Count))
If Await DocumentLoader.LoadFiles(CurrentTemplate, lookupMandator.EditValue) Then
GridControlFiles.DataSource = Nothing
GridControlFiles.DataSource = DocumentLoader.Files
txtFilesLoaded.Caption = String.Format(My.Resources.frmImportMainExtra._0__Dateien_geladen, DocumentLoader.Files.Count)
End If
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Laden_der_Dokumente)
Finally
FilesLoading = False
EndLoadingUI()
End Try
End Function
Public Async Function ReloadFile() As Task
Try
BeginLoadingUI()
FilesLoading = True
Dim oDocument As Document = GridViewFiles.GetRow(GridViewFiles.FocusedRowHandle)
Dim oNewDocument = Await DocumentLoader.LoadFile(oDocument.File, CurrentTemplate, lookupMandator.EditValue)
Dim oIndex = DocumentLoader.Files.IndexOf(oDocument)
DocumentLoader.Files.Item(oIndex) = oNewDocument
LoadDocument(oNewDocument)
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Neuladen_des_Dokuments)
Finally
FilesLoading = False
EndLoadingUI()
End Try
End Function
Private Function EditRow(pRow As DataRow, pView As GridView) As DocumentRow
Try
If CurrentDocumentReadOnly = True Then
FormHelper.ShowWarning("Bitte wählen Sie zunächst einen Mandanten aus, bevor Sie diese Datei bearbeiten!")
Return Nothing
End If
Dim oColumns = pView.Columns.Select(Function(c) c.FieldName).ToList()
Dim oDocumentRow = CurrentDocument.Rows.
Where(Function(r) r.Id.ToString = pRow.Item(COLUMN_GUID)).
SingleOrDefault()
Dim oTemplateTable = CurrentTemplate.Tables.
Where(Function(t) t.Name = pView.GridControl.Name).
SingleOrDefault()
Dim oForm As New frmRowEditor(
LogConfig,
oColumns,
oDocumentRow,
CurrentDocument.Mandator,
Winline,
oTemplateTable
)
If oForm.ShowDialog() = DialogResult.OK Then
Return oForm.DocumentRow
Else
Return Nothing
End If
Catch ex As Exception
FormHelper.ShowError(ex, My.Resources.frmImportMainExtra.Laden_der_Detailzeilen)
Return Nothing
End Try
End Function
Private Async Function TransferFile(pDocument As Document, Optional pIsTest As Boolean = False) As Task(Of Boolean)
' Check for errors and abort
If pDocument.HasErrors = True Then
FormHelper.ShowWarning("Diese Datei kann noch nicht übertragen werden, da sie noch Fehler oder fehlende Werte enthält.")
Return False
End If
Logger.Info("Transferring file [{0}] to Winline", pDocument.FileName)
Dim oResult = Await WebService.TransferDocumentToWinline(pDocument, CurrentTemplate, lookupMandator.EditValue, pIsTest)
Logger.Debug("Transfer successful: [{0}]", oResult)
If oResult = True Then
' If this was only a test, we are done.
If pIsTest = True Then
Logger.Debug("This was a Test Transfer. Exiting.")
Return True
End If
' Generate the report
WebService.RaiseWebServiceProgress("Bericht erzeugen")
Logger.Debug("Creating report for file [{0}]", pDocument.FileName)
Dim oReportResult = ReportGenerator.GenerateReport(pDocument, CurrentTemplate)
' Export it to pdf
WebService.RaiseWebServiceProgress("Bericht exportieren")
Logger.Debug("Exporting report to [{0}]", oReportResult.FileName)
oReportResult.Report.ExportToPdf(oReportResult.FileName)
' Mark Document as Imported, will be moved on Form Close or File Reload
Logger.Debug("Setting file [{0}] to Imported", pDocument.FileName)
pDocument.Imported = True
Return True
Else
Return False
End If
End Function
Private Function CreateGridsAndColumns(pTemplate As Templates.Template) As List(Of GridControl)
Dim oGrids As New List(Of GridControl)
Dim oTableCounter = 0
For Each oTable In pTemplate.Tables
If oTableCounter = 0 Then
Dim oGrid = GridLoader.GetGridFromElement(GridControl1, oTable)
AddHandler oGrid.DoubleClick, AddressOf Grid_MouseDoubleClick
AddHandler GridView1.CustomDrawCell, AddressOf GridView_CustomDrawCell
oGrids.Add(oGrid)
End If
If oTableCounter = 1 Then
Dim oGrid = GridLoader.GetGridFromElement(GridControl2, oTable)
AddHandler oGrid.DoubleClick, AddressOf Grid_MouseDoubleClick
AddHandler GridView2.CustomDrawCell, AddressOf GridView_CustomDrawCell
oGrids.Add(oGrid)
End If
If oTableCounter = 2 Then
Dim oGrid = GridLoader.GetGridFromElement(GridControl3, oTable)
AddHandler oGrid.DoubleClick, AddressOf Grid_MouseDoubleClick
AddHandler GridView3.CustomDrawCell, AddressOf GridView_CustomDrawCell
oGrids.Add(oGrid)
End If
If oTableCounter = 3 Then
Dim oGrid = GridLoader.GetGridFromElement(GridControl4, oTable)
AddHandler oGrid.DoubleClick, AddressOf Grid_MouseDoubleClick
AddHandler GridView4.CustomDrawCell, AddressOf GridView_CustomDrawCell
oGrids.Add(oGrid)
End If
If oTableCounter > 3 Then
MsgBox(My.Resources.frmImportMainExtra.Zur_Zeit_werden_nur_bis_zu_4_Tabellen_unterstützt_, MsgBoxStyle.Exclamation, Text)
End If
oTableCounter += 1
Next
If oTableCounter < 3 Then
SplitContainerGrids.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1
End If
Return oGrids
End Function
Private Sub TryOpenDirectory(pPath As String, pDisplayName As String)
If Directory.Exists(pPath) Then
Process.Start(pPath)
Else
Dim oMessage = String.Format(My.Resources.frmImportMainExtra._0__nicht_konfiguriert_oder_nicht_gefunden, pDisplayName)
MsgBox(oMessage, MsgBoxStyle.Exclamation, Text)
End If
End Sub
Private Sub TryOpenFile(pPath As String, pDisplayName As String)
If IO.File.Exists(pPath) Then
Process.Start(pPath)
Else
Dim oMessage = String.Format(My.Resources.frmImportMainExtra._0__nicht_konfiguriert_oder_nicht_gefunden, pDisplayName)
MsgBox(oMessage, MsgBoxStyle.Exclamation, Text)
End If
End Sub
Private Sub BeginLoadingUI()
SplashScreenManager.ShowWaitForm()
SetDocumentButtonsEnabled(False)
GridControlFiles.Enabled = False
SplitContainerGrids.Enabled = False
lookupMandator.Enabled = False
RibbonPageGroupLoad.Enabled = False
RibbonPageGroupEdit.Enabled = False
RibbonPageGroupReport.Enabled = False
RibbonPageGroupTransfer.Enabled = False
End Sub
Private Sub EndLoadingUI()
RibbonPageGroupLoad.Enabled = True
RibbonPageGroupEdit.Enabled = True
RibbonPageGroupReport.Enabled = True
RibbonPageGroupTransfer.Enabled = True
lookupMandator.Enabled = True
SplitContainerGrids.Enabled = True
GridControlFiles.Enabled = True
SetDocumentButtonsEnabled(True)
SplashScreenManager.CloseWaitForm()
End Sub
Private Sub SetDocumentButtonsEnabled(pEnabled As Boolean)
btnShowXml.Enabled = pEnabled
btnReloadFile.Enabled = pEnabled
btnTransferFile.Enabled = pEnabled
btnRemoveRow.Enabled = pEnabled
btnOpenReport.Enabled = pEnabled
btnTransferAllFiles.Enabled = pEnabled
btnEditRow.Enabled = pEnabled
End Sub
Private Sub btnShowErrors_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnShowErrors.ItemClick
If CurrentDocument IsNot Nothing Then
Dim oErrors = CurrentDocument.Errors.
Select(Function(s) " - " & s).
ToList()
Dim oMessage = String.Join(vbNewLine, oErrors)
MsgBox($"Datei enthält {oErrors.Count} Fehler:{vbNewLine}{vbNewLine}{oMessage}", MsgBoxStyle.Exclamation, Text)
End If
End Sub
Private AskReloadFile As Boolean = False
Private Async Function lookupMandator_EditValueChanged(sender As Object, e As EventArgs) As Task Handles lookupMandator.EditValueChanged
Dim oMandator As Mandator = lookupMandator.EditValue
If lookupMandator.EditValue Is Nothing Then
lookupMandator.BackColor = Color.LightCoral
AskReloadFile = False
Else
lookupMandator.BackColor = Nothing
If AskReloadFile Then
AskReloadFile = False
Dim oResult = MsgBox($"Sie haben den Mandanten '{oMandator}' ausgewählt. Wollen Sie jetzt die aktuelle Datei neu laden?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo, Text)
If oResult = MsgBoxResult.Yes Then
Await ReloadFile()
End If
End If
End If
End Function
Private Sub lookupMandator_EditValueChanging(sender As Object, e As DevExpress.XtraEditors.Controls.ChangingEventArgs) Handles lookupMandator.EditValueChanging
If e.OldValue Is Nothing And e.NewValue IsNot Nothing And FilesLoading = False Then
AskReloadFile = True
End If
End Sub
#End Region
End Class