Programm_Wirl/AA-Forms/FormKundeVW.cs

1177 lines
45 KiB
C#

using AForge.Video.DirectShow;
using BrightIdeasSoftware;
using DatenDB;
using Deckungsbeitrag.AA_Forms;
using Deckungsbeitrag.AA_Klassen;
using Spire.Barcode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using ZXing;
namespace Deckungsbeitrag
{
public partial class FormKundeVW : Form
{
private FilterInfoCollection videoDevices;
List<Sortiment> sortimentListe = null;
List<KundeArtikel> standListe = null;
Kunde kunde = null;
Image qrcode = null;
private readonly Meldungen meldung = new Meldungen();
private readonly Benutzer benutzer;
int beforeedit = 0;
private bool formloading = false;
private DataGridView.HitTestInfo _hitInfo;
public bool _tosave = false;
private bool _tosaveInventur = false;
public bool TosaveInventur
{
get { return _tosaveInventur; }
set
{
_tosaveInventur = value;
if (_tosaveInventur & dateTimePickerInventur.Checked & dateTimePickerLiefertag.Checked)
{
buttonFreigeben.Enabled = true;
buttonFreigeben.BackColor = Color.FromArgb(0, 192, 0);
}
else
{
buttonFreigeben.Enabled = false;
buttonFreigeben.BackColor = Color.Gray;
}
}
}
public FormKundeVW()
{
InitializeComponent();
}
public FormKundeVW(Kunde kunde) :this()
{
this.kunde = kunde;
}
public FormKundeVW(Benutzer benutzer) : this()
{
this.benutzer = benutzer;
}
public FormKundeVW(Kunde kunde, Benutzer benutzer) : this(kunde)
{
this.benutzer = benutzer;
}
private void KundeDaten_Load(object sender, EventArgs e)
{
formloading = true;
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
//Sortiment Liste erstellen.
sortimentListe = Funktionen.SortimentLesen("Liste");
//Alle TextBoxen deaktivieren.
TextBoxes_Unable();
labelAnzahlChars.Text = textBoxAnmerkung.TextLength.ToString() + "/" + textBoxAnmerkung.MaxLength.ToString();
this.labelAnzahlChars.Location = new Point(this.textBoxAnmerkung.Right - this.labelAnzahlChars.Width, this.labelAnzahlChars.Location.Y);
this.tabControlKunde.Location = new Point(this.textBoxAnmerkung.Right + 10, 11);
ComboBox_Laden();
if (this.kunde == null) this.kunde = Funktionen.KundenAuswahl();
if (this.kunde != null) DatenLesen();
else this.Close();
}
private void FormKundeVW_Shown(object sender, EventArgs e)
{
this.tabControlKunde.Width = this.ClientSize.Width - tabControlKunde.Left - 10;
}
private void ComboBox_Laden()
{
// Service Liste erstellen und mit ComboBox verknüpfen.
this.comboBoxService.Enabled = false;
List<string> list = Kunde.GetServiceDistinct();
this.comboBoxService.DataSource = list;
// Aufgaben Liste erstellen und mit ComboBox verknüpfen.
List<Aufgabe> aufgabenlist1 = Aufgabe.GetList(2);
this.comboBoxAufgabe.DataSource = aufgabenlist1;
this.comboBoxAufgabe.DisplayMember = "Bezeichnung";
this.comboBoxAufgabe.SelectedIndex = -1;
this.comboBoxAufgabe.Enabled = false;
// Sommer-Lieferrhythmus Liste mit ComboBox verknüpfen.
this.comboBoxLRSommer.DataSource = new BindingSource(Lieferrhythmen.AnzeigeNamen, null);
this.comboBoxLRSommer.DisplayMember = "Key";
this.comboBoxLRSommer.ValueMember = "Value";
// WinterLieferrhythmus Liste mit ComboBox verknüpfen.
this.comboBoxLRWinter.DataSource = new BindingSource(Lieferrhythmen.AnzeigeNamen, null);
this.comboBoxLRWinter.DisplayMember = "Key";
this.comboBoxLRWinter.ValueMember = "Value";
}
private void DatenLesen()
{
formloading = true;
//TextBoxen deaktivieren.
TextBoxes_Unable();
//Alle Einträge der DataGridView entfernen. Davor muss die DataSource entfernt werden.
this.dGArtikel.DataSource = null;
this.dGArtikel.Rows.Clear();
//ComboBox für Sonderaufgaben wie "In Säcke Verpacken".
this.comboBoxAufgabe.Enabled = true;
//Properties für Standliste.
//sortNr ist falls noch kein Stand hinterlegt wurde
string sortNr = string.Empty;
//kundeid ist falls bereits ein Stand existiert und die Artikel gespeichert wurden.
string kundeid = this.kunde.KundeID.ToString();
// Wenn bereits ein Stand gespeichert ist, kommt er aus der DB. Wenn kein Stand gespeichert kommt Liste aus Sortiment.
if (KundeArtikel.GetList(kundeid).Count > 0)
{
this.standListe = KundeArtikel.GetList(kundeid);
if (this.standListe[0].ArtikelID == null || this.standListe[0].Reihung == 0)
{
CompareToSortiment();
}
Load_Gridview(this.standListe);
}
else
{
//Jedes Innsbrucker Soziale Dienste Sortiment ist gleich.
if (this.kunde.KundeNummer == "010069" | this.kunde.KundeNummer == "010071") sortNr = "010068";
else sortNr = this.kunde.KundeNummer;
//Sortiment holen und Standliste filtern.
standListe = new List<KundeArtikel>();
int reihung = 1;
foreach(Sortiment sort in sortimentListe.FindAll(Sortiment => Sortiment.KundeNummer == sortNr))
{
if (sort.ArtName.Contains("*EK")) continue;
KundeArtikel item = new KundeArtikel
{
ArtikelNR = sort.ArtNr,
ArtikelName = sort.ArtName,
KundeID = Kunde.GetKundeID(sort.KundeNummer, null),
ArtikelID = Artikel.GetArtikelID(sort.ArtNr),
Reihung = reihung
};
standListe.Add(item);
reihung++;
}
if (standListe.Count == 0) this.tabControlKunde.Controls.Remove(tabPageArtikel);
standListe = standListe.OrderBy(x => x.Reihung).ToList();
//GridView mit der jeweiligen Liste füllen.
Load_Gridview(standListe);
}
// QR-Code wird erstellt
BarcodeWriter code = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE
};
qrcode = code.Write(this.kunde.KundeNummer);
this.pictureBoxQRCode.Image = qrcode;
this.pictureBoxQRCode.SizeMode = PictureBoxSizeMode.Zoom;
// SWS-Entwurf wird erstellt und angezeigt
this.pictureBoxEntwurf.Image = Funktionen.SWS_Entwurf(null, this.kunde);
this.pictureBoxEntwurf.Visible = true;
// Restliche TextBoxen werden befüllt
this.textBoxKndNr.Text = this.kunde.KundeNummer;
this.textBoxKundeName.Text = this.kunde.KundeName;
this.textBoxKndName2.Text = this.kunde.KundeName2;
this.textBoxStraße.Text = this.kunde.Strasse;
this.textBoxPLZ.Text = this.kunde.PLZ.ToString();
this.textBoxOrt.Text = this.kunde.Ort;
this.textBoxSuchtext.Text = this.kunde.Suchtext;
this.textBoxAnmerkung.Text = this.kunde.Anmerkung;
// CheckBox aktivieren
this.checkBoxNW.Checked = this.kunde.HatNachwaesche;
// ComboBox-Item für Aufgabe wird gewählt und Button Entfernen aktiviert
foreach (Aufgabe auf in comboBoxAufgabe.Items) if (auf.AufgabeID == this.kunde.Aufgabe) this.comboBoxAufgabe.SelectedItem = auf;
if (this.comboBoxAufgabe.SelectedItem != null) this.buttonAufgEnt.Enabled = true;
// ComboBox-Item für Service wird gewählt
if (!string.IsNullOrWhiteSpace(this.kunde.Service))
{
foreach (string s in comboBoxService.Items) if (s == this.kunde.Service) this.comboBoxService.SelectedItem = s;
}
this.comboBoxLRSommer.SelectedIndexChanged -= ComboBoxLieferrhythmus_SelectedIndexChanged;
this.comboBoxLRWinter.SelectedIndexChanged -= ComboBoxLieferrhythmus_SelectedIndexChanged;
this.comboBoxAufgabe.SelectedIndexChanged -= ComboBoxAufgabe_SelectedIndexChanged;
// ComboBox-Item für Lieferrhythmus wird gewählt
this.comboBoxLRSommer.SelectedValue = (Liefertage)this.kunde.SommerLieferRhythmus;
this.comboBoxLRWinter.SelectedValue = (Liefertage)this.kunde.WinterLieferRhythmus;
if (this.kunde.Aufgabe == null) this.comboBoxAufgabe.SelectedIndex = -1;
else this.comboBoxAufgabe.SelectedItem = Aufgabe.GetAufgabe(null, this.kunde.Aufgabe);
this.comboBoxAufgabe.SelectedIndexChanged += ComboBoxAufgabe_SelectedIndexChanged;
this.comboBoxLRSommer.SelectedIndexChanged += ComboBoxLieferrhythmus_SelectedIndexChanged;
this.comboBoxLRWinter.SelectedIndexChanged += ComboBoxLieferrhythmus_SelectedIndexChanged;
// numericUpDown für AufgabeCount befüllen
this.numericUpDownAufgabeCount.Value = (decimal)this.kunde.AufgabeCount;
// Wird noch nicht verwendet
this.buttonProgramm.Text = "WP 01";
// Buttons und ähnliches aktivieren.
this.buttonProgramm.Enabled = true;
this.buttonBewertung.Enabled = true;
this.tabControlKunde.Enabled = true;
OLV_Load();
Chart_Load();
this.tabControlKunde.SelectedIndex = 0;
formloading = false;
}
private void CompareToSortiment()
{
int reihung = 1;
Kunde _kunde = Kunde.GetKunde(null, this.standListe[0].KundeID, null);
foreach (Sortiment sort in sortimentListe.FindAll(Sortiment => Sortiment.KundeNummer == _kunde.KundeNummer))
{
if (sort.ArtName.Contains("*EK")) continue;
KundeArtikel kndart = this.standListe.Find(s => s.ArtikelNR == sort.ArtNr);
kndart.ArtikelID = Artikel.GetArtikelID(sort.ArtNr);
kndart.Reihung = reihung;
kndart.Save();
reihung++;
}
this.standListe = this.standListe.OrderBy(x => x.Reihung).ToList();
}
/// <summary>
/// TextBox Events
/// </summary>
private void TextBoxes_Unable()
{
foreach (Control ctr in this.Controls) if (ctr is TextBox) { if (!ctr.Name.Contains("Anmerkung")) ctr.Enabled = false; }
}
private void TextBoxKndNr_Leave(object sender, EventArgs e)
{
}
private void TSBBeenden_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void ButtonDrucken_Click(object sender, EventArgs e)
{
Funktionen.SWS_Drucken(null, this.kunde, this);
}
private void TSBNext_Click(object sender, EventArgs e)
{
SaveChanges();
// Kundenliste öffnen und Kunde auswählen.
this.kunde = Funktionen.KundenAuswahl();
if (kunde != null) DatenLesen();
}
private void SaveChanges()
{
if (_tosave)
{
if (this.comboBoxAufgabe.SelectedItem != null && this.numericUpDownAufgabeCount.Value == 0) { meldung.GetFehler(this, $"Du hast für deine Aufgabe noch keine Auftraganzahl eingegeben. Hole das bitte jetzt nach."); return; }
if (this.comboBoxAufgabe.SelectedItem == null && this.numericUpDownAufgabeCount.Value > 0) { meldung.GetFehler(this, "Du hast noch keine Aufgabe ausgewählt. Hole das bitte jetzt nach."); return; }
if (MessageBox.Show("Möchtest du die Änderungen speichern?", "FRAGE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) this.kunde.Save();
_tosave = false;
}
if (TosaveInventur)
{
if (MessageBox.Show("Du hast die Inventur noch nicht gespeichert, möchtest du diese jetzt speichern?", "FRAGE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) ButtonFreigeben_Click(buttonFreigeben, null);
TosaveInventur = false;
}
}
private void ButtonProgramm_Click(object sender, EventArgs e)
{
}
private void ButtonAufgEnt_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Möchtest du die Aufgabe wirklich löschen?", "Frage", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.comboBoxAufgabe.SelectedIndex = -1;
this.kunde.Aufgabe = null;
this.kunde.Save();
}
}
private void OLV_Load()
{
foreach(ObjectListView olv in this.Controls.OfType<ObjectListView>())
{
olv.HeaderFormatStyle = Funktionen.GetHeader();
olv.OwnerDraw = true;
Generator.GenerateColumns(olv, typeof(OLVKundenumsatz), true);
if (olv.Name.Contains("Jahresumsatz"))
{
foreach (OLVColumn c in olv.Columns) if (c.Name == "Zeitraum") c.Text = "Jahr";
olv.SetObjects(OLVKundenumsatz.GetJahresumsatz(this.kunde.KundeID));
}
if (olv.Name.Contains("Quartalsumsatz"))
{
foreach (OLVColumn c in olv.Columns) if (c.Name == "Zeitraum") c.Text = "Quartal";
olv.SetObjects(OLVKundenumsatz.GetQuartalsumsatz(this.kunde.KundeID));
}
if (olv.Name.Contains("Monatsumsatz"))
{
foreach (OLVColumn c in olv.Columns) if (c.Name == "Zeitraum") c.Text = "Monat";
olv.SetObjects(OLVKundenumsatz.GetMonatsumsatz(this.kunde.KundeID));
}
}
}
private void Chart_Load()
{
foreach (Chart chart in this.Controls.OfType<Chart>()) chart.Visible = true;
//IMPLEMENTIEREN
ClassChart ch = ClassChart.FillChart(this.kunde.KundeID);
//Chart Jahresumsatz
List<OLVKundenumsatz> olv = OLVKundenumsatz.GetJahresumsatz(this.kunde.KundeID);
string[] x = new string[olv.Count()];
double[] y = new double[olv.Count()];
for (int i = 0; i < y.Length; i++)
{
y[i] = olv[i].Umsatz;
x[i] = olv[i].Zeitraum;
}
this.chartJahresumsatz.Series[0].LegendText = "Umsatz";
this.chartJahresumsatz.Series[0].ChartType = SeriesChartType.Column;
this.chartJahresumsatz.Series[0].IsValueShownAsLabel = true;
this.chartJahresumsatz.Series[0].Points.DataBindXY(x, y);
//Chart Quartalsumsatz
List<OLVKundenumsatz> olvq = OLVKundenumsatz.GetQuartalsumsatz(this.kunde.KundeID);
string[] xq = new string[olvq.Count()];
double[] yq = new double[olvq.Count()];
for (int i = 0; i < olvq.Count(); i++)
{
yq[i] = olvq[i].Umsatz;
xq[i] = olvq[i].Zeitraum;
}
this.chartQuartalsumsatz.Series[0].LegendText = "Umsatz";
this.chartQuartalsumsatz.Series[0].ChartType = SeriesChartType.Bar;
this.chartQuartalsumsatz.Series[0].IsValueShownAsLabel = true;
this.chartQuartalsumsatz.Series[0].Points.DataBindXY(xq, yq);
}
private void ComboBoxAufgabe_DropDownClosed(object sender, EventArgs e)
{
}
private void KundeDaten_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.End) TSBNext_Click(this, e);
}
/// <summary>
/// Events für ShortCut zu "Nächster Kunde"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void NaechsterKundeToolStripMenuItem_Click(object sender, EventArgs e)
{
TSBNext_Click(this, e);
}
/// <summary>
/// Laden der DataGridView zur Stand und Fehlmengenverwaltung.
/// </summary>
/// <param name="objectListe"></param>
private void Load_Gridview(List<KundeArtikel> objectListe)
{
if (objectListe.Count > 0)
{
this.dGArtikel.AutoGenerateColumns = false;
foreach (DataGridViewColumn col in this.dGArtikel.Columns)
{
col.DataPropertyName = col.Name;
}
// DataGridView mit ArtikelStand Liste verbinden und Columns automatisch generieren.
this.dGArtikel.DataSource = objectListe;
this.dGArtikel.ClearSelection();
this.dGArtikel.CurrentCell = this.dGArtikel.Rows[0].Cells[3];
// Alle Spaltenbreiten an den Zellinhalt anpassen
this.dGArtikel.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
// Alle Zeilenhöhen an Zellinhalt anpassen
this.dGArtikel.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
}
/// <summary>
/// Speichern von Stand und Fehlmengenänderungen.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StandSpeichernToolStripMenuItem_Click(object sender, EventArgs e)
{
int tosave = 0;
int toupdate = 0;
int saved = 0;
this.dGArtikel.EndEdit();
// Speichern der Zeilen aus der DataGridView
foreach(DataGridViewRow row in this.dGArtikel.Rows)
{
KundeArtikel item = KundeArtikel.GetItemIfAvailable(int.Parse(row.Cells[1].Value.ToString()), int.Parse(row.Cells[2].Value.ToString()));
if(item != null)
{
++toupdate;
if (int.Parse(row.Cells[4].Value.ToString()) != 0)
{
item.Stand = int.Parse(row.Cells[4].Value.ToString());
item.StandBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (int.Parse(row.Cells[5].Value.ToString()) != 0)
{
item.Fehlmenge = int.Parse(row.Cells[5].Value.ToString());
item.FehlmengeBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (int.Parse(row.Cells[6].Value.ToString()) != 0)
{
item.Reklamation = int.Parse(row.Cells[6].Value.ToString());
item.ReklamationBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (int.Parse(row.Cells[7].Value.ToString()) != 0)
{
item.Korrektur = int.Parse(row.Cells[7].Value.ToString());
item.KorrekturBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (item.Save() == 1) saved++;
}
else
{
++tosave;
item.KundeArtikelID = null;
item.KundeID = int.Parse(row.Cells[1].Value.ToString());
item.ArtikelNR = int.Parse(row.Cells[2].Value.ToString());
item.ArtikelName = row.Cells[3].Value.ToString();
if (int.Parse(row.Cells[4].Value.ToString()) != 0)
{
item.Stand = int.Parse(row.Cells[4].Value.ToString());
item.StandBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (int.Parse(row.Cells[5].Value.ToString()) != 0)
{
item.Fehlmenge = int.Parse(row.Cells[5].Value.ToString());
item.FehlmengeBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (int.Parse(row.Cells[6].Value.ToString()) != 0)
{
item.Reklamation = int.Parse(row.Cells[6].Value.ToString());
item.ReklamationBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (int.Parse(row.Cells[7].Value.ToString()) != 0)
{
item.Korrektur = int.Parse(row.Cells[7].Value.ToString());
item.KorrekturBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (item.Save() == 1) saved++;
}
}
// Überprüfung ob alle Zeilen gespeichert wurden.
if ((toupdate + tosave) == saved) meldung.Gespeichert();
else meldung.Speicherfehler();
Load_Gridview(this.standListe);
}
private void DGArtikel_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
DataGridView dataGrid = sender as DataGridView;
beforeedit = int.Parse(dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
private void DGArtikel_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridView dg = sender as DataGridView;
DataGridViewRow row = dg.Rows[e.RowIndex];
DataGridViewCell cell = dg.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell != null)
{
// Wenn der Zellenwert sich geändert hat, wird die entsprechende Zahl in der DB upgedatet.
if (beforeedit != int.Parse(cell.Value.ToString()))
{
// Speichern des aktuellen Zellinhaltes.
if (row.Cells[0].Value != null)
{
KundeArtikel item = KundeArtikel.GetItem(int.Parse(row.Cells[0].Value.ToString()));
item.KundeArtikelID = int.Parse(row.Cells[0].Value.ToString());
if (row.Cells[e.ColumnIndex].OwningColumn.Name == "Stand")
{
item.Stand = int.Parse(row.Cells[e.ColumnIndex].Value.ToString());
item.StandBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (row.Cells[e.ColumnIndex].OwningColumn.Name == "Fehlmenge")
{
item.Fehlmenge = int.Parse(row.Cells[e.ColumnIndex].Value.ToString());
item.FehlmengeBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (row.Cells[e.ColumnIndex].OwningColumn.Name == "Reklamation")
{
item.Reklamation = int.Parse(row.Cells[e.ColumnIndex].Value.ToString());
//item.KorrekturBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (row.Cells[e.ColumnIndex].OwningColumn.Name == "Korrektur")
{
item.Korrektur = int.Parse(row.Cells[e.ColumnIndex].Value.ToString());
item.KorrekturBearbeitet = this.benutzer.BenutzerName + " am " + DateTime.Now.ToString();
}
if (item.Save() != 1) meldung.Speicherfehler();
}
}
}
}
}
private void ButtonServiceBearbeiten_Click(object sender, EventArgs e)
{
if(this.comboBoxService.Enabled == false) this.comboBoxService.Enabled = true;
}
private void TextBoxAnmerkung_Leave(object sender, EventArgs e)
{
if (meldung.GetFrage(this, "Möchtest du die Anmerkung speichern?", false) == DialogResult.Yes) { kunde.Anmerkung = textBoxAnmerkung.Text; }
}
private void NumericUpDownAufgabeCount_Leave(object sender, EventArgs e)
{
if (meldung.GetFrage(this, $"Möchtest du die Aufgabe für die nächsten {numericUpDownAufgabeCount.Value} Aufträge speichern?", false) == DialogResult.Yes)
{
if (this.comboBoxAufgabe.SelectedItem == null) { this.kunde.Aufgabe = null; this.kunde.AufgabeCount = null; }
else { this.kunde.Aufgabe = ((Aufgabe)this.comboBoxAufgabe.SelectedItem).AufgabeID; this.kunde.AufgabeCount = (int)numericUpDownAufgabeCount.Value; }
}
}
/// <summary>
/// ValueChanged Events zum Speichern wenn Changed.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TextBoxAnmerkung_TextChanged(object sender, EventArgs e)
{
if (formloading) return;
_tosave = true;
labelAnzahlChars.Text = textBoxAnmerkung.TextLength.ToString() + "/" + textBoxAnmerkung.MaxLength.ToString();
TextBoxAnmerkung_Leave(this, null);
}
private void ComboBoxAufgabe_SelectedIndexChanged(object sender, EventArgs e)
{
if (formloading) return;
_tosave = true;
}
private void NumericUpDownAufgabeCount_ValueChanged(object sender, EventArgs e)
{
NumericUpDown numeric = (NumericUpDown)sender;
if (formloading) return;
_tosave = true;
}
private void ComboBoxService_SelectedValueChanged(object sender, EventArgs e)
{
if (formloading) return;
if (this.comboBoxService.Enabled == true) this.kunde.Service = this.comboBoxService.SelectedValue.ToString();
else return;
_tosave = true;
}
private void ComboBoxLieferrhythmus_SelectedIndexChanged(object sender, EventArgs e)
{
if (formloading) return;
this.kunde.SommerLieferRhythmus = (int)this.comboBoxLRSommer.SelectedValue;
this.kunde.WinterLieferRhythmus = (int)this.comboBoxLRWinter.SelectedValue;
_tosave = true;
}
/// <summary>
/// FormClosing: Wenn Form wird geschlossen, Kontrolle ob Änderungen gemacht wurden.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormKundeVW_FormClosing(object sender, FormClosingEventArgs e)
{
SaveChanges();
}
private void CheckBoxNW_Click(object sender, EventArgs e)
{
if (formloading) return;
this.kunde.HatNachwaesche = this.checkBoxNW.Checked;
_tosave = true;
}
#region INVENTUR Tab
private void TabControlKunde_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.tabControlKunde.SelectedTab.Text == "Inventuren")
{
this.tabControlInventur.Cursor = Cursors.WaitCursor;
this.tabControlInventur.SuspendLayout();
string savePath = Path.Combine(ConfigurationManager.AppSettings["DateiSavePfad"], "Listen\\Inventuren") ?? "Inventuren";
if (ConfigurationManager.AppSettings["ConnectionString"].Split(';')[4].Split('=')[1] == "Test_Wirl") savePath = Path.Combine(ConfigurationManager.AppSettings["DateiSavePfad"], "Test\\Inventuren") ?? "Inventuren";
string delPath = Path.Combine(savePath, $"Warten-{this.kunde.KundeNummer}.csv");
string[] lines = null;
if (File.Exists(delPath))
{
int i = 0;
//int j = 0;
lines = File.ReadAllLines(delPath, Encoding.UTF8);
this.dateTimePickerInventur.ValueChanged -= DateTimePicker_ValueChanged;
this.dateTimePickerLiefertag.ValueChanged -= DateTimePicker_ValueChanged;
this.dGVZahlen.Columns.Clear();
this.dGVZahlen.Rows.Clear();
this.dGVZahlen.AllowUserToAddRows = false;
// 1. alle Zeilen lesen
foreach (string line in lines)
{
i++;
if (i == 1 || i == 2 || i == 3 || i ==6 || i == 7 || i == 8)
{
if (i == 2 && line.Split(':')[1].Replace(';', ' ').Trim() != this.kunde.KundeNummer) return;
else continue;
}
if (i == 4 && DateTime.TryParse(line.Split(':')[1].Replace(';', ' ').Trim(), out DateTime dt)) dateTimePickerInventur.Value = dt;
if (i == 5 && DateTime.TryParse(line.Split(':')[1].Replace(';', ' ').Trim(), out DateTime date)) dateTimePickerLiefertag.Value = date;
if (i == 9)
{
string[] artikel = line.Split(';');
DataGridViewColumn col;
for (int x = 0; x < artikel.Length; x++)
{
if (x == 0) continue;
KundeArtikel kndart = KundeArtikel.GetItemIfAvailable((int)this.kunde.KundeID, int.Parse(artikel[x].Split(':')[1]));
col = new DataGridViewTextBoxColumn
{
HeaderText = artikel[x],
Name = "col_" + artikel[x],
Tag = kndart,
ReadOnly = false,
SortMode = DataGridViewColumnSortMode.NotSortable
};
this.dGVZahlen.Columns.Add(col);
}
}
if (i > 9)
{
string[] data = line.Split(';');
DataGridViewRow drow = new DataGridViewRow();
drow.CreateCells(this.dGVZahlen);
for (int j = 0; j < data.Length; j++)
{
if (j == 0) drow.HeaderCell.Value = data[0];
else drow.Cells[j - 1].Value = data[j];
}
this.dGVZahlen.Rows.Add(drow);
}
}
}
else
{
GetInventurColumns();
GetRowHeader(null);
GetOLVItems();
}
GetRowLayout();
this.dateTimePickerInventur.ValueChanged += DateTimePicker_ValueChanged;
this.dateTimePickerLiefertag.ValueChanged += DateTimePicker_ValueChanged;
this.tabControlInventur.ResumeLayout();
this.tabControlInventur.Cursor = Cursors.Default;
}
}
/// <summary>
/// Laden von alten Inventuren.
/// </summary>
private void GetOldInventuren()
{
string savePath = Path.Combine(ConfigurationManager.AppSettings["DateiSavePfad"], "Listen\\Inventuren") ?? "Inventuren";
if (ConfigurationManager.AppSettings["ConnectionString"].Split(';')[4].Split('=')[1] == "Test_Wirl") savePath = Path.Combine(ConfigurationManager.AppSettings["DateiSavePfad"], "Test\\Inventuren") ?? "Inventuren";
string[] invFiles = Directory.GetFiles(savePath, $"*-{this.kunde.KundeNummer}.csv");
string[] lines = null;
// Wenn keine Files vorhanden -> RETURN
if (invFiles.Length == 0) return;
int i = 0;
foreach (string s in invFiles)
{
i++;
// Wartende Inventur wird ignoriert.
if (s.StartsWith("Warten")) continue;
// 1. alle Zeilen lesen
lines = File.ReadAllLines(Path.Combine(savePath, s), Encoding.UTF8);
// 2. an UCInventur übergeben
}
}
private void GetRowLayout()
{
foreach (DataGridViewRow row in this.dGVZahlen.Rows)
{
if (row.HeaderCell.Value == null) continue;
switch (row.HeaderCell.Value.ToString())
{
case var t when t == "INV-Ausgleich":
row.HeaderCell.Style.BackColor = row.DefaultCellStyle.BackColor = Color.Green;
row.HeaderCell.Style.Font = row.DefaultCellStyle.Font = new Font(dGVZahlen.Font, FontStyle.Bold);
row.HeaderCell.Style.ForeColor = row.DefaultCellStyle.ForeColor = Color.White;
break;
case var t when t == "Schwund":
row.HeaderCell.Style.BackColor = row.DefaultCellStyle.BackColor = Color.Red;
row.HeaderCell.Style.Font = row.DefaultCellStyle.Font = new Font(dGVZahlen.Font, FontStyle.Bold);
row.HeaderCell.Style.ForeColor = row.DefaultCellStyle.ForeColor = Color.White;
break;
case var t when t == "IST-Stand":
row.HeaderCell.Style.Font = row.DefaultCellStyle.Font = new Font(dGVZahlen.Font, FontStyle.Bold);
break;
default:
break;
}
}
this.dGVZahlen.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
}
private void GetRowHeader(string[] datarows)
{
string[] rows;
if (datarows != null) { rows = datarows.ToArray(); }
else rows = new string[] { "IST-Stand", "SOLL-Stand", "INV-Ausgleich", "Reklamation", "Nachwäsche", "Schwund" };
this.dGVZahlen.Rows.Clear();
this.dGVZahlen.Rows.Add(rows.Length - 1);
foreach (DataGridViewRow row in this.dGVZahlen.Rows)
{
row.HeaderCell.Value = rows[row.Index];
row.ReadOnly = true;
//switch (row.HeaderCell.Value.ToString())
//{
// case var t when t == "INV-Ausgleich":
// row.HeaderCell.Style.BackColor = row.DefaultCellStyle.BackColor = Color.Green;
// row.HeaderCell.Style.Font = row.DefaultCellStyle.Font = new Font(dGVZahlen.Font, FontStyle.Bold);
// row.HeaderCell.Style.ForeColor = row.DefaultCellStyle.ForeColor = Color.White;
// break;
// case var t when t == "Schwund":
// row.HeaderCell.Style.BackColor = row.DefaultCellStyle.BackColor = Color.Red;
// row.HeaderCell.Style.Font = row.DefaultCellStyle.Font = new Font(dGVZahlen.Font, FontStyle.Bold);
// row.HeaderCell.Style.ForeColor = row.DefaultCellStyle.ForeColor = Color.White;
// break;
// case var t when t == "IST-Stand":
// row.HeaderCell.Style.Font = row.DefaultCellStyle.Font = new Font(dGVZahlen.Font, FontStyle.Bold);
// break;
// default:
// break;
//}
}
//this.dGVZahlen.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
}
private void GetOLVItems()
{
foreach (DataGridViewColumn col in this.dGVZahlen.Columns)
{
KundeArtikel kndart = col.Tag as KundeArtikel;
foreach (DataGridViewRow row in this.dGVZahlen.Rows)
{
if (row.HeaderCell.Value?.ToString() == "SOLL-Stand") row.Cells[col.Index].Value = kndart.Stand;
if (row.HeaderCell.Value?.ToString() == "Reklamation") row.Cells[col.Index].Value = kndart.Reklamation;
if (row.HeaderCell.Value?.ToString() == "Nachwäsche") row.Cells[col.Index].Value = kndart.Fehlmenge;
}
}
}
private void GetInventurColumns()
{
this.dGVZahlen.Columns.Clear();
DataGridViewColumn col;
foreach (KundeArtikel kndart in this.standListe)
{
string text = Artikel.GetShort(kndart.ArtikelID, null);
//string text = kndart.ArtikelName;
col = new DataGridViewTextBoxColumn
{
HeaderText = text,
Name = "col_" + text,
Tag = kndart,
ReadOnly = false,
SortMode = DataGridViewColumnSortMode.NotSortable
};
this.dGVZahlen.Columns.Add(col);
}
// Alle Spaltenbreiten an den Zellinhalt anpassen
this.dGVZahlen.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
// Alle Zeilenhöhen an Zellinhalt anpassen
this.dGVZahlen.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
private void PictureBoxPlus_Click(object sender, EventArgs e)
{
string text;
CustomInputBox input = new CustomInputBox("Möchtest du der Tabelle eine Zeile hinzufügen?", "ZÄHLPUNKT HINZUFÜGEN", "Name", "isAlpha");
if (input.ShowDialog() == DialogResult.OK)
{
text = input.text;
}
else return;
// Neue Zeile mit Daten erstellen
DataGridViewRow newRow = new DataGridViewRow();
newRow.CreateCells(this.dGVZahlen);
foreach (DataGridViewCell cell in newRow.Cells) cell.Value = 0;
newRow.HeaderCell.Value = text;
// An Position 2 einfügen (vor bestehender Zeile 2)
this.dGVZahlen.Rows.Insert(0, newRow);
}
private void DeleteRowToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_hitInfo.RowIndex >= 0 && _hitInfo.ColumnIndex >= 0)
{
int row = _hitInfo.RowIndex;
int col = _hitInfo.ColumnIndex;
string wert = dGVZahlen.Rows[row].Cells[col].Value?.ToString();
if (MessageBox.Show($"Möchtest du die Zeile {row + 1} wirklich löschen?", "FRAGE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { this.dGVZahlen.Rows.RemoveAt(row); foreach (DataGridViewColumn column in this.dGVZahlen.Columns) DoCalculation(column.Index); }
else return;
}
}
private void DGVZahlen_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
_hitInfo = dGVZahlen.HitTest(e.X, e.Y);
contextMenuStripGridView.Show(dGVZahlen, e.Location);
}
}
private void DoCalculation(int colIndex)
{
int istStand = 0; int sollStand = 0; int reklamation = 0; int nachwaesche = 0; int invAusgleich = 0;
int istIndex = FindRowByHeaderText("IST-Stand");
foreach (DataGridViewRow row in dGVZahlen.Rows)
{
if (row.Index < istIndex) istStand += int.Parse(row.Cells[colIndex].Value.ToString());
switch (row.HeaderCell.Value.ToString())
{
case var t when t == "SOLL-Stand":
sollStand = int.Parse(row.Cells[colIndex].Value.ToString());
break;
case var t when t == "INV-Ausgleich":
row.Cells[colIndex].Value = invAusgleich = sollStand - istStand;
break;
case var t when t == "Schwund":
row.Cells[colIndex].Value = invAusgleich - reklamation - nachwaesche;
break;
case var t when t == "IST-Stand":
int rowIndex = row.Index;
row.Cells[colIndex].Value = istStand;
break;
case var t when t == "Reklamation":
reklamation = int.Parse(row.Cells[colIndex].Value.ToString());
break;
case var t when t == "Nachwäsche":
nachwaesche = int.Parse(row.Cells[colIndex].Value.ToString());
break;
default:
break;
}
}
TosaveInventur = true;
}
private void DGVZahlen_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DoCalculation(e.ColumnIndex);
}
public int FindRowByHeaderText(string headerText)
{
foreach (DataGridViewRow row in dGVZahlen.Rows)
{
if (!row.IsNewRow && row.HeaderCell.Value != null &&
row.HeaderCell.Value.ToString() == headerText)
{
return row.Index;
}
}
return -1; // Nicht gefunden
}
private void ContextMenuStripGridView_Opening(object sender, CancelEventArgs e)
{
if (_hitInfo.RowIndex >= 0 && _hitInfo.ColumnIndex >= 0)
{
int row = _hitInfo.RowIndex;
int col = _hitInfo.ColumnIndex;
if (dGVZahlen.Rows[row].ReadOnly) deleteRowToolStripMenuItem.Enabled = false;
else deleteRowToolStripMenuItem.Enabled = true;
}
}
private void ButtonFreigeben_Click(object sender, EventArgs e)
{
string savePath = Path.Combine(ConfigurationManager.AppSettings["DateiSavePfad"], "Listen\\Inventuren") ?? "Inventuren";
if (ConfigurationManager.AppSettings["ConnectionString"].Split(';')[4].Split('=')[1] == "Test_Wirl") savePath = Path.Combine(ConfigurationManager.AppSettings["DateiSavePfad"], "Test\\Inventuren") ?? "Inventuren";
string delPath = Path.Combine(savePath, $"Warten-{this.kunde.KundeNummer}.csv");
SaveInventurToCSV("Speichern", null);
if (File.Exists(delPath))
{
if (MessageBox.Show("Möchtest du die Inventur abschließen?", "FRAGE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int auftragID = ErstelleInventurAuftrag();
SaveInventurToCSV("Abschließen", auftragID);
}
}
else
{
Program.AddFehler(this.benutzer, $"Inventur konnte nicht gesoeichert werden.", $"KundeNr: {this.kunde.KundeNummer} Liefertag: {dateTimePickerLiefertag}", null);
MessageBox.Show("Die Inventur konnte nicht gespeichert werden. Der Fehler wurde gemeldet.", "FEHLER", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
TabControlKunde_SelectedIndexChanged(this.tabControlKunde, null);
}
private int ErstelleInventurAuftrag()
{
int auftragId = 0;
Auftrag inv = new Auftrag()
{
KundeID = (int)this.kunde.KundeID,
ArbeiterID = (int)this.benutzer.BenutzerID,
Typ = AuftragTyp.Inventur,
Status = AuftragStatus.Herrichten,
Erstellt = DateTime.Now,
ErstelltVon = (int)this.benutzer.BenutzerID,
Liefertag = dateTimePickerLiefertag.Value.Date,
};
int[] inventur = inv.Save();
if (inventur[0] == 1)
{
auftragId = inventur[1];
foreach (DataGridViewRow row in dGVZahlen.Rows)
{
if (row.HeaderCell.Value.ToString() == "INV-Ausgleich")
{
int save = dGVZahlen.Columns.Count;
int saved = 0;
foreach (DataGridViewColumn column in dGVZahlen.Columns)
{
KundeArtikel kndart = (KundeArtikel)column.Tag;
Artikel art = Artikel.GetArtikel(null, ((KundeArtikel)column.Tag).ArtikelID);
if (row.Cells[column.Index].Value == null || int.Parse(row.Cells[column.Index].Value.ToString()) == 0) { save -= 1; continue; }
KundeArtikel.SaveKundeArtikel_Numbers(kndart, int.Parse(row.Cells[column.Index].Value.ToString()), 0, 0, null);
AuftragArtikel aufart = new AuftragArtikel()
{
AuftragID = inventur[1],
ArtikelID = art.ArtikelID,
ArtikelName = art.Bezeichnung,
Gesamt = row.Cells[column.Index].Value == null ? 0 : int.Parse(row.Cells[column.Index].Value.ToString()),
Anzahl = row.Cells[column.Index].Value == null ? 0 : int.Parse(row.Cells[column.Index].Value.ToString()),
Erledigt = false,
};
saved += aufart.Save();
}
if (save != saved)
{
Program.AddFehler(this.benutzer, "Es wurden nicht alle Artikel der Inventur gespeichert.", $"Auftrag: {inventur[1]} Fehler bei <FormKundeVW><ErstelleInventurAuftrag>", null);
MessageBox.Show("Es konnten nicht alle Artikel gespeichert werden. Vergleiche den Auftrag mit der CSV.", "FEHLER", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
return auftragId;
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Möchtest du die Inventur wirklich löschen?", "FRAGE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.dateTimePickerInventur.Checked = this.dateTimePickerLiefertag.Checked = false;
foreach(DataGridViewRow row in dGVZahlen.Rows)
{
if (!dGVZahlen.Rows[row.Index].ReadOnly) this.dGVZahlen.Rows.RemoveAt(row.Index);
foreach (DataGridViewColumn column in this.dGVZahlen.Columns) DoCalculation(column.Index);
}
TosaveInventur = false;
}
}
/// <summary>
/// DataGridView wird geladen.
/// Wenn Inventurdatei vorhanden werden Spalten hinzugefügt und Zeilen aufgefüllt.
/// </summary>
/// <param name="sender"></param>
private void SaveInventurToCSV(object sender, int? Id)
{
Kunde _knd = this.kunde;
Benutzer _user = this.benutzer;
List<KundeArtikel> _artikelliste = this.standListe;
string status = string.Empty;
string savePath = Path.Combine(ConfigurationManager.AppSettings["DateiSavePfad"], "Listen\\Inventuren") ?? "Inventuren";
if (ConfigurationManager.AppSettings["ConnectionString"].Split(';')[4].Split('=')[1] == "Test_Wirl") savePath = Path.Combine(ConfigurationManager.AppSettings["DateiSavePfad"], "Test\\Inventuren") ?? "Inventuren";
// Inventur Status Warten wenn noch Zahlen fehlen.
if (sender.ToString() == "Speichern") status = "Warten";
else
{
// Inventur Status Herrichten wenn alle Zahlen vorhanden und Auftrag erstellt wurde.
if (sender.ToString() == "Abschließen")
{
status = $"Herrichten-{Id}";
string deletePath = Path.Combine(savePath, $"Warten-{_knd.KundeNummer}.csv");
if (File.Exists(deletePath)) File.Delete(deletePath);
}
else // Inventur Status Fertig wenn Inventur fertig hergerichtet und demnäcsht ausgeliefert.
{
//TODO: Wenn Auftrag Fertig dann Fertig Datei erstellen und Herrichten löschen.
status = $"Fertig-{Id}";
string delPath = Path.Combine(savePath, $"Herrichten-{Id}-{_knd.KundeNummer}.csv");
if (File.Exists(delPath)) File.Delete(delPath);
}
}
string artikel = string.Empty;
string cols = string.Empty;
string fileName = $"{status}-{_knd.KundeNummer}.csv"; // Dateiname: Status-AuftragID-KundeNummer.csv
string csvPath;
csvPath = Path.Combine(savePath, fileName);
// Prüfen ob Header schon existiert
//bool headerExists = File.Exists(csvPath);
// Artikelbezeichnungen in string convertieren
foreach (KundeArtikel art in _artikelliste) artikel += art.ArtikelName + ";";
foreach (var col in dGVZahlen.Columns.Cast<DataGridViewColumn>().Where(c => c.Visible).OrderBy(c => c.DisplayIndex))
{
if (col.Visible) cols += ";" + col.HeaderText + ":" + ((KundeArtikel)col.Tag).ArtikelNR.ToString();
}
// Prüfen ob Inventur neu ist
//if (headerExists) neueinventur = NeueInventur(csvPath, cols);
// Nur Header bei NEUER Datei
var csv = new StringBuilder();
csv.AppendLine("=== INVENTUR INFO ===");
csv.AppendLine($"KundeNr: {_knd.KundeNummer}");
csv.AppendLine($"Kunde: {_knd.KundeName}");
csv.AppendLine($"Inventurdatum: {dateTimePickerInventur.Value.Date:d}");
csv.AppendLine($"Liefertag: {dateTimePickerLiefertag.Value.Date:d}");
if (Id != null) csv.AppendLine($"Auftrag: {Id}");
else csv.AppendLine("Auftrag: ");
csv.AppendLine();
csv.AppendLine(new string('=', 30));
csv.AppendLine($"Artikel{cols}");
File.WriteAllText(csvPath, csv.ToString(), Encoding.UTF8);
// NEUE Artikel ANHÄNGEN (ohne Header)
var appendCsv = new StringBuilder();
foreach (DataGridViewRow row in this.dGVZahlen.Rows)
{
// Nur sichtbare Spalten auslesen
var values = new List<string>();
for (int i = 0; i < row.Cells.Count; i++)
{
if (row.Cells[i].Visible)
{
if (i == 0)
{
values.Add(row.HeaderCell.Value.ToString());
}
values.Add(row.Cells[i].Value?.ToString() ?? "0");
}
}
// Eine Zeile pro Row, mit allen Werten getrennt durch ";"
appendCsv.AppendLine(string.Join(";", values));
}
File.AppendAllText(csvPath, appendCsv.ToString(), Encoding.UTF8);
TosaveInventur = false;
}
private void DateTimePicker_ValueChanged(object sender, EventArgs e)
{
DateTimePicker dtp = sender as DateTimePicker;
if (dtp.Checked == true) TosaveInventur = true;
else TosaveInventur = false;
}
#endregion
}
}