Exemplo n.º 1
0
        private void btnDeleteGood_Click(object sender, EventArgs e)
        {
            if (dgvData.CurrentRow.Cells["dgvcGoodERPCode"].Value != DBNull.Value && dgvData.CurrentRow.Cells["dgvcGoodERPCode"].Value != null)
            {
                RFMMessage.MessageBoxAttention("запись получена из хост-системы.\n Удаление невозможно ...");
                return;
            }
            if (RFMMessage.MessageBoxYesNo("Удалить текущий товар?") != DialogResult.Yes)
            {
                return;
            }
            if (dgvData.Rows.Count == 0)
            {
                return;
            }
            if (dgvData.CurrentRow == null)
            {
                return;
            }
            if (dgvData.IsStatusRow(dgvData.CurrentRow.Index))
            {
                return;
            }
            DataRow dr = ((DataRowView)((DataGridViewRow)dgvData.Rows[dgvData.CurrentRow.Index]).DataBoundItem).Row;

            tGoodsCustoms.Rows.Remove(dr);
            btnDeleteGood.Enabled = (dgvData.Rows.Count > 0);
        }
Exemplo n.º 2
0
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvActs.CurrentRow == null)
            {
                return;
            }

            if (!oActCur.ID.HasValue)
            {
                return;
            }


            if (oActCur.DateConfirm.HasValue)
            {
                RFMMessage.MessageBoxAttention("јкт уже подтвержден.\n" +
                                               "–едактирование невозможно!");
                return;
            }


            if (StartForm(new frmActsEdit((int)oActCur.ID, (int?)oActCur.InputID, (int?)oActCur.OutputID)) == DialogResult.Yes)
            {
                dgvActs_Restore();
            }
        }
Exemplo n.º 3
0
 private void txtFrameID4_TextChanged(object sender, EventArgs e)
 {
     if (txtFrameID4.Text.Length == 4)
     {
         // ищем подход¤щий контейнер
         Frame  oFrameTemp  = new Frame();
         string sBarCodeEnd = txtFrameID4.Text.Trim();
         oFrameTemp.BarCode               = sBarCodeEnd;
         oFrameTemp.FilterActual          = true;
         oFrameTemp.FilterHasFrameContent = true;
         //oFrameTemp.FilterFramesStatesStr = "S";
         oFrameTemp.FillData();
         if (oFrameTemp.MainTable.Rows.Count > 0)
         {
             if (oFrameTemp.MainTable.Rows.Count == 1)
             {
                 if (oFrameTemp.MainTable.Rows[0]["BarCode"].ToString().EndsWith(sBarCodeEnd))
                 {
                     oFrameTemp.ID = Convert.ToInt32(oFrameTemp.MainTable.Rows[0]["ID"]);
                 }
             }
             else
             {
                 DataView dvTemp = new DataView(oFrameTemp.MainTable);
                 dvTemp.RowFilter = "substring(BarCode, len(BarCode) - " + sBarCodeEnd.Length.ToString() + " + 1, " + sBarCodeEnd.Length.ToString() + ") = '" + sBarCodeEnd + "'";
                 DataTable dtTemp = dvTemp.ToTable();
                 if (dtTemp.Rows.Count > 1)
                 {
                     RFMMessage.MessageBoxAttention("¬нимание!\n\n" +
                                                    "Ќайдено несколько актуальных контейнеров с указанным окончанием штрих-кода " +
                                                    "(" + dtTemp.Rows.Count.ToString() + ")");
                     // подставл¤ем последний
                     oFrameTemp.ID = Convert.ToInt32(dtTemp.Rows[dtTemp.Rows.Count - 1]["ID"]);
                 }
             }
         }
         if (oFrameTemp.ID == null)
         {
             RFMMessage.MessageBoxError("Ќет доступных контейнеров с таким кодом...");
             txtFrameBarCode.Text = txtFrameID4.Text = "";
             return;
         }
         else
         {
             oFrame.ID = oFrameTemp.ID;
             FrameChoose();
         }
     }
 }
        private void btnGo_Click(object sender, EventArgs e)
        {
            if (cMode == "D")
            {
                if (dgvData.CurrentRow == null)
                {
                    RFMMessage.MessageBoxAttention("Выберите партнера!");
                    dgvPartnersDetails.Select();
                    return;
                }
                DataRow dr = ((DataRowView)((DataGridViewRow)dgvData.CurrentRow).DataBoundItem).Row;
                if (dgvPartnersDetails.Rows.Count > 0)
                {
                    DataRow drd = ((DataRowView)((DataGridViewRow)dgvPartnersDetails.CurrentRow).DataBoundItem).Row;
                    if (drd["FactName"].ToString().Trim().Length == 0)
                    {
                        RFMMessage.MessageBoxAttention("В выбранных реквизитах для партнера\n" +
                                                       "\"" + ((string)dr["Name"]).Trim() + "\"\n" +
                                                       "не заполнено фактическое название...");
                        dgvPartnersDetails.Select();
                        return;
                    }
                    else
                    {
                        ucSelect.SaveData(dgvPartnersDetails, "FactName", false);
                    }
                }
                else
                {
                    RFMMessage.MessageBoxAttention("Не заполнены реквизиты для партнера\n" +
                                                   "\"" + ((string)dr["Name"]).Trim() + "\"...");
                    dgvData.Select();
                    return;
                }
            }
            else
            {
                if (dgvData.Rows.Count > 0)
                {
                    ucSelect.SaveData(dgvData, "Name", bUseCheck);
                }
            }

            btnGo.DialogResult = DialogResult.Yes;
            Close();
        }
Exemplo n.º 5
0
        private void frmVeterinaryExportXmlEdit_Load(object sender, EventArgs e)
        {
            // Получение таблицы их XML
            if (sExportXML.Length > 0)
            {
                try
                {
                    tbl.ReadXml(new System.IO.StringReader(sExportXML));
                }
                catch (Exception ex)
                {
                    RFMMessage.MessageBoxAttention("Невозможно заполнить таблицу значениями!\n Введите данные заново!\r\n" + ex.Message);
                }
            }

            dgvData.AutoGenerateColumns = false;
            dgvData.DataSource          = tbl;
            dgvData.AllowUserToAddRows  = true;
        }
Exemplo n.º 6
0
        private void btnCalc_Click(object sender, EventArgs e)
        {
            // Расчет эффективности
            double nTripCost = (double)numTripCost.Value;

            if (nTripCost == 0)
            {
                RFMMessage.MessageBoxAttention("Не задана стоимость рейса!");
                return;
            }

            double nNormWarehouse = (double)numNormWarehouse.Value;
            double nNetto, nAmount, nMarkup, nTransportCost, nWarehouseCost, nCleanMarkup;
            double nExpencesSum = 0, nCleanMarkupSum = 0;

            foreach (DataRow r in tableEfficiency.Rows)
            {
                // Замена данных в статусной строке
                if (r["PartnerID"].ToString().Length == 0)
                {
                    r["Expences"]    = nExpencesSum;
                    r["CleanMarkup"] = nCleanMarkupSum;

                    continue;
                }

                nNetto         = Convert.ToDouble(r["Netto"]);
                nAmount        = Convert.ToDouble(r["Amount"]);
                nMarkup        = Convert.ToDouble(r["Markup"]);
                nTransportCost = nNetto * Convert.ToDouble(r["Kt"]) * nTripCost;
                nWarehouseCost = nNetto * nNormWarehouse;
                nCleanMarkup   = (r["OutIn"].ToString() == "O" && nAmount != nMarkup ? nMarkup - (nTransportCost + nWarehouseCost) : 0);

                r["Expences"]       = nTransportCost + nWarehouseCost;
                r["CleanMarkup"]    = nCleanMarkup;
                r["CleanMarkupPrc"] = (nAmount > 0 ? nCleanMarkup / nAmount * 100 : 0);

                nExpencesSum    += (r["OutIn"].ToString() == "O" && nAmount != nMarkup ? nTransportCost + nWarehouseCost : 0);
                nCleanMarkupSum += nCleanMarkup;
            }
        }
Exemplo n.º 7
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            bool    bFind = false;
            DataRow dr;

            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                dr = dtSource.Rows[i];
                if (dr["Cost"] != DBNull.Value && dr["Cost"] != null &&
                    (decimal)dr["Cost"] >= 0)
                {
                    bFind = true;
                    break;
                }
            }
            if (!bFind)
            {
                RFMMessage.MessageBoxAttention("Нечего сохранять...");
                return;
            }

            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                dr = dtSource.Rows[i];
                if (dr["Cost"] != DBNull.Value && dr["Cost"] != null &&
                    (decimal)dr["Cost"] >= 0 &&
                    dr["TripID"] != DBNull.Value && dr["TripID"] != null)
                {
                    oTrip.TripCostSave((int)dr["TripID"], (decimal)dr["Cost"]);
                    if (oTrip.ErrorNumber != 0)
                    {
                        break;
                    }
                }
            }
            if (oTrip.ErrorNumber == 0)
            {
                dgvTrips.GridSource.Filter = "";
                Dispose();
            }
        }
Exemplo n.º 8
0
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dgvCarsTasks.CurrentRow == null)
            {
                return;
            }
            if (!oCarTaskCur.ID.HasValue)
            {
                return;
            }

            if (oCarTaskCur.DateConfirm.HasValue)
            {
                RFMMessage.MessageBoxAttention("Задание уже подтверждено.\n" + "Редактирование невозможно!");
                return;
            }

            if (StartForm(new frmCarsTasksEdit((int)oCarTaskCur.ID)) == DialogResult.Yes)
            {
                dgvCarsTasks_Restore();
            }
        }
Exemplo n.º 9
0
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (grdData.CurrentRow == null)
            {
                return;
            }

            if (!oPassCur.ID.HasValue)
            {
                return;
            }

            // перечитать
            oPassCur.ReFillOne((int)oPassCur.ID);

            // проверки
            if (oPassCur.DateConfirm.HasValue)
            {
                RFMMessage.MessageBoxError("Пропуск уже утвержден...");
                return;
            }
            if (oPassCur.DateEnd.HasValue)
            {
                RFMMessage.MessageBoxAttention("Машина уже выехала...");
                //return;
            }
            if (oPassCur.DateBeg.HasValue)
            {
                RFMMessage.MessageBoxAttention("Машина уже въехала...");
                //return;
            }
            Refresh();

            if (StartForm(new frmPassesEdit((int)oPassCur.ID)) == DialogResult.Yes)
            {
                grdData_Restore();
            }
        }
Exemplo n.º 10
0
        private void btnLocate_Click(object sender, EventArgs e)
        {
            if (txtDeliveryAddress.Text.Length == 0)
            {
                RFMMessage.MessageBoxAttention("Пустой адрес!");
                return;
            }

            Partner tempPartner = new Partner();

            tempPartner.Name            = "Точка доставки";
            tempPartner.DeliveryAddress = txtDeliveryAddress.Text;
            if (txtLongitude.Text.Length > 0 && txtLatitude.Text.Length > 0)
            {
                tempPartner.Longitude = Convert.ToDecimal(txtLongitude.Text);
                tempPartner.Latitude  = Convert.ToDecimal(txtLatitude.Text);
            }

            frmShowMap frmShowMap = new frmShowMap(tempPartner);

            if (frmShowMap != null)
            {
                // Отображение карты
                StartForm(frmShowMap);

                // Переотображение данных о координатах и расстоянии
                // Эти данные переприсваиваются в форме frmShowMap!
                if (tempPartner.Longitude.HasValue && tempPartner.Latitude.HasValue)
                {
                    txtLongitude.Text = tempPartner.Longitude.ToString();
                    txtLatitude.Text  = tempPartner.Latitude.ToString();
                }
                if (tempPartner.Distance > 0)
                {
                    numDistance.Value = tempPartner.Distance;
                }
            }
        }
Exemplo n.º 11
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (cboOwnerSource.SelectedIndex < 0 || cboOwnerSource.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите исходного владельца товара!");
                cboOwnerSource.Select();
                return;
            }
            if (cboOwnerTarget.SelectedIndex < 0 || cboOwnerTarget.SelectedValue == null)
            {
                if (cboOwnerTarget.Enabled)
                {
                    RFMMessage.MessageBoxError("Выберите конечного владельца товара!");
                    cboOwnerSource.Select();
                    return;
                }
                else
                {
                    cboOwnerTarget.SelectedValue = cboOwnerSource.SelectedValue;
                }
            }
            if (cboPartnerDetailSource.SelectedValue == null || cboPartnerDetailSource.SelectedIndex < 0)
            {
                RFMMessage.MessageBoxError("Выберите реквизиты исходного владельца товара!");
                cboPartnerDetailSource.Select();
                return;
            }
            if (cboPartnerDetailSource.SelectedValue == null || cboPartnerDetailSource.SelectedIndex < 0)
            {
                if (cboOwnerTarget.Enabled)
                {
                    RFMMessage.MessageBoxError("Выберите реквизиты конечного владельца товара!");
                    cboPartnerDetailTarget.Select();
                    return;
                }
                else
                {
                    cboPartnerDetailTarget.SelectedValue = cboPartnerDetailSource.SelectedValue;
                }
            }

            if (radOwners.Checked && ((int)cboPartnerDetailSource.SelectedValue == (int)cboPartnerDetailTarget.SelectedValue))
            {
                RFMMessage.MessageBoxError("Выберите несовпадающих владельцев/реквизиты!");
                cboPartnerDetailTarget.Select();
                return;
            }

            if (cboGoodStateSource.SelectedIndex < 0 || cboGoodStateSource.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите исходное состояние товара!");
                cboGoodStateSource.Select();
                return;
            }
            if (cboGoodStateTarget.SelectedIndex < 0 || cboGoodStateTarget.SelectedValue == null)
            {
                if (cboGoodStateTarget.Enabled)
                {
                    RFMMessage.MessageBoxError("Выберите конечное состояние товара!");
                    cboGoodStateTarget.Select();
                    return;
                }
                else
                {
                    cboGoodStateTarget.SelectedValue = cboGoodStateSource.SelectedValue;
                }
            }
            if (radGoodStates.Checked && ((int)cboGoodStateSource.SelectedValue == (int)cboGoodStateTarget.SelectedValue))
            {
                RFMMessage.MessageBoxError("Выберите несовпадающие состояния товара!");
                cboGoodStateTarget.Select();
                return;
            }

            if (cboCurrency.SelectedIndex < 0 || cboCurrency.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите валюту!");
                cboCurrency.Select();
                return;
            }

            if (txtBillNumber.Text.Length == 0 &&
                RFMMessage.MessageBoxYesNo("Не указан номер документа.\nВсе равно сохранить?") == DialogResult.No)
            {
                txtBillNumber.Select();
                return;
            }

            // хоть один товар
            if (oMovingDocument.TableMovingsDocumentsGoods.Rows.Count == 0)
            {
                RFMMessage.MessageBoxAttention("Не введено ни одного товара...");
                return;
            }
            else
            {
                // хоть что-то введено
                bool bFound = false;
                foreach (DataRow r in oMovingDocument.TableMovingsDocumentsGoods.Rows)
                {
                    if ((decimal)r["QntWished"] > 0 || (decimal)r["BoxWished"] > 0)
                    {
                        bFound = true;
                        break;
                    }
                }
                if (!bFound)
                {
                    RFMMessage.MessageBoxYesNo("Ни для одного товара не введено количество...");
                    return;
                }
            }
            if (RFMMessage.MessageBoxYesNo("Сохранить документарное перемещение?") == DialogResult.Yes)
            {
                oMovingDocument.DateMoving            = dtpDateMovingDocument.Value.Date;
                oMovingDocument.GoodStateSourceID     = (int)cboGoodStateSource.SelectedValue;
                oMovingDocument.GoodStateTargetID     = (int)cboGoodStateTarget.SelectedValue;
                oMovingDocument.OwnerSourceID         = (int)cboOwnerSource.SelectedValue;
                oMovingDocument.OwnerTargetID         = (int)cboOwnerTarget.SelectedValue;
                oMovingDocument.CurrencyID            = (int)cboCurrency.SelectedValue;
                oMovingDocument.PartnerDetailSourceID = (int)cboPartnerDetailSource.SelectedValue;
                oMovingDocument.PartnerDetailTargetID = (int)cboPartnerDetailTarget.SelectedValue;
                oMovingDocument.Note       = txtNote.Text.Trim();
                oMovingDocument.BillNumber = txtBillNumber.Text.Trim();

                // добрались. сохраняем.
                Refresh();
                WaitOn(this);
                oMovingDocument.ClearError();
                bool bResult = oMovingDocument.Save();
                WaitOff(this);
                if (bResult && oMovingDocument.ErrorNumber == 0)
                {
                    RFMMessage.MessageBoxInfo("Документарное перемещение сохранено.");
                    MotherForm.GotParam = new object[] { (int)oMovingDocument.ID };
                    DialogResult        = DialogResult.Yes;
                    Dispose();
                }
            }
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            _SelectedPackingID = null;

            //if (StartForm(new frmSelectOnePacking(this, false, nOwnerID)) == DialogResult.Yes)
            if (StartForm(new frmSelectOnePacking(this, false, null, oOutputDocument.HostID)) == DialogResult.Yes)
            {
                if (_SelectedPackingID != null)
                {
                    // проверить, нет ли уже такой строки
                    foreach (DataRow r in oOutputDocument.TableOutputsDocumentsGoods.Rows)
                    {
                        if (Convert.ToInt32(r["PackingID"]) == _SelectedPackingID)
                        {
                            dgvOutputsDocumentsGoods.GridSource.Position = dgvOutputsDocumentsGoods.GridSource.Find("PackingID", _SelectedPackingID);
                            if (dgvOutputsDocumentsGoods.GridSource.Position < 0)
                            {
                                dgvOutputsDocumentsGoods.GridSource.MoveFirst();
                            }
                            return;
                        }
                    }

                    Good oGood = new Good();
                    oGood.PackingID = _SelectedPackingID;
                    oGood.FillData();
                    // выбранный товар
                    DataRow rg = oGood.MainTable.Rows[0];
                    // добавляем новую строку для выбранного товара
                    DataRow dr = oOutputDocument.TableOutputsDocumentsGoods.Rows.Add(-1, -1);
                    dr["Changed"]                                    = true;
                    dr["PackingID"]                                  = _SelectedPackingID;
                    dr["GoodID"]                                     = rg["GoodID"];
                    dr["QntWished"]                                  =
                        dr["BoxWished"]                              =
                            dr["QntConfirmed"]                       =
                                dr["BoxConfirmed"]                   =
                                    dr["QntBrought"]                 =
                                        dr["BoxBrought"]             =
                                            dr["Price"]              =
                                                dr["Vat"]            =
                                                    dr["PriceNoVat"] =
                                                        0;
                    dr["GoodName"]      = rg["GoodName"];
                    dr["GoodAlias"]     = rg["GoodAlias"];
                    dr["PackingAlias"]  = rg["PackingAlias"];
                    dr["GoodBarCode"]   = rg["GoodBarCode"];
                    dr["Articul"]       = rg["Articul"];
                    dr["GoodGroupName"] = rg["GoodGroupName"];
                    dr["GoodBrandName"] = rg["GoodBrandName"];
                    dr["CountryName"]   = rg["CountryName"];
                    dr["InBox"]         = rg["InBox"];
                    dr["BoxInPal"]      = rg["BoxInPal"];
                    dr["Weighting"]     = rg["Weighting"];

                    RFMMessage.MessageBoxAttention("Не забудьте ввести цену и НДС для добавленного товара!");

                    // и встаем на эту строку
                    dgvOutputsDocumentsGoods.GridSource.Position = dgvOutputsDocumentsGoods.GridSource.Find("PackingID", _SelectedPackingID);
                    if (dgvOutputsDocumentsGoods.GridSource.Position < 0)
                    {
                        dgvOutputsDocumentsGoods.GridSource.MoveFirst();
                    }
                    // встать на найденную строку, в ячейку "Коробок дост."
                    dgvOutputsDocumentsGoods.CurrentCell = dgvOutputsDocumentsGoods.Rows[dgvOutputsDocumentsGoods.GridSource.Position].Cells["dgrcBoxBrought"];
                }

                _SelectedPackingID        = null;
                _SelectedPackingAliasText = null;
            }
        }
        private void dgvOutputsDocumentsGoods_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewRow r = dgvOutputsDocumentsGoods.Rows[e.RowIndex];

            if (dgvOutputsDocumentsGoods.Columns[e.ColumnIndex].Name == "dgrcQntBrought" &&
                !(bool)r.Cells["dgrcWeighting"].Value &&
                (r.Cells["dgrcQntBrought"].Value == null || r.Cells["dgrcQntBrought"].Value == DBNull.Value ||
                 ((decimal)r.Cells["dgrcQntBrought"].Value > (decimal)r.Cells["dgrcQntConfirmed"].Value))
                )
            {
                if (r.Cells["dgrcQntBrought"].Value == null || r.Cells["dgrcQntBrought"].Value == DBNull.Value)
                {
                    r.Cells["dgrcQntBrought"].Value = 0;
                }
                else
                {
                    if (!(bool)r.Cells["dgrcChanged"].Value)
                    {
                        if (RFMMessage.MessageBoxYesNo("Количество доставленного товара больше количества отгруженного товара!\nВсе-таки сохранить?") != DialogResult.Yes)
                        {
                            r.Cells["dgrcQntBrought"].Value = r.Cells["dgrcQntConfirmed"].Value;
                        }
                    }
                }
            }

            if (dgvOutputsDocumentsGoods.Columns[e.ColumnIndex].Name == "dgrcBoxBrought" &&
                !(bool)r.Cells["dgrcWeighting"].Value &&
                (r.Cells["dgrcBoxBrought"].Value == null || r.Cells["dgrcBoxBrought"].Value == DBNull.Value ||
                 ((decimal)r.Cells["dgrcBoxBrought"].Value > (decimal)r.Cells["dgrcBoxConfirmed"].Value))
                )
            {
                if (r.Cells["dgrcBoxBrought"].Value == null || r.Cells["dgrcBoxBrought"].Value == DBNull.Value)
                {
                    r.Cells["dgrcBoxBrought"].Value = 0;
                }
                else
                {
                    //RFMMessage.MessageBoxError("Введено число больше допустимого!");
                    //r.Cells["dgrcBoxBrought"].Value = r.Cells["dgrcBoxConfirmed"].Value;
                    if (!(bool)r.Cells["dgrcChanged"].Value)
                    {
                        if (RFMMessage.MessageBoxYesNo("Число доставленных коробок больше числа отгруженных коробок!\nВсе-таки сохранить?") != DialogResult.Yes)
                        {
                            r.Cells["dgrcQntBrought"].Value = r.Cells["dgrcQntConfirmed"].Value;
                        }
                    }
                }
            }

            if (dgvOutputsDocumentsGoods.Columns[e.ColumnIndex].Name == "dgrcVat")
            {
                if (r.Cells["dgrcVat"].Value == null || r.Cells["dgrcVat"].Value == DBNull.Value)
                {
                    r.Cells["dgrcVat"].Value = 0;
                }

                // проверка ставок НДС
                decimal nVat = (decimal)r.Cells["dgrcVat"].Value;
                if (nVat == 0)
                {
                    RFMMessage.MessageBoxAttention("Не указана ставка НДС...");
                }
                else
                {
                    decimal?nVat1 = null, nVat2 = null;
                    Setting oSet     = new Setting();
                    string  sVatTemp = null;
                    sVatTemp = oSet.FillVariable("gnVat1");
                    if (sVatTemp != null && sVatTemp != "")
                    {
                        nVat1 = Convert.ToDecimal(sVatTemp);
                    }
                    sVatTemp = oSet.FillVariable("gnVat2");
                    if (sVatTemp != null && sVatTemp != "")
                    {
                        nVat2 = Convert.ToDecimal(sVatTemp);
                    }
                    if (nVat1.HasValue && nVat != nVat1 && nVat2.HasValue && nVat != nVat2 ||
                        !nVat1.HasValue && nVat2.HasValue && nVat != nVat2 ||
                        nVat1.HasValue && nVat != nVat1 && !nVat2.HasValue)
                    {
                        RFMMessage.MessageBoxError("Указана неверная ставка НДС...");
                        r.Cells["dgrcVat"].Value = 0;
                    }
                }
            }

            dgvOutputsDocumentsGoods.Refresh();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            int nDistance    = (int)numDistance.Value;
            int nDistanceOld = oTrip.Distance;

            dgvOutputsDocuments.GridSource.Filter = "";

            int             nNegative = -1;
            DataRow         dr;
            DataGridViewRow dgvr;

            for (int i = 0; i < dgvOutputsDocuments.Rows.Count; i++)
            {
                dgvr = dgvOutputsDocuments.Rows[i];

                if (dgvr.Cells["dgvcDurationMinutesFact"].Value != DBNull.Value &&
                    (int)dgvr.Cells["dgvcDurationMinutesFact"].Value < 0)
                {
                    nNegative = i;
                    break;
                }
            }
            if (nNegative >= 0)
            {
                dgvOutputsDocuments.GridSource.Filter = "IsUnique";
                RFMMessage.MessageBoxError("Укажите правильное время пребывания у клиента...");
                dgvOutputsDocuments.Rows[nNegative].Cells["dgvcTimeEnd"].Selected = true;
                dgvOutputsDocuments.BeginEdit(true);
                return;
            }

            bool bFind = (nDistance != nDistanceOld);

            if (!bFind)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dr = dt.Rows[i];
                    if (dr["DurationMinutesFact"] != DBNull.Value && (int)dr["DurationMinutesFact"] > 0)
                    {
                        bFind = true;
                        break;
                    }
                }
            }
            if (!bFind)
            {
                dgvOutputsDocuments.GridSource.Filter = "IsUnique";
                RFMMessage.MessageBoxAttention("Нечего сохранять...");
                return;
            }

            int         idMask = -1, idValue, nDuration = 0;
            DataRowView drv;
            DateTime?   dDateBeg = DateTime.Now, dDateEnd = DateTime.Now;

            dt.DefaultView.Sort = "PartnerTargetID";
            for (int i = 0; i < dt.DefaultView.Count; i++)
            {
                drv     = dt.DefaultView[i];
                idValue = (int)drv["PartnerTargetID"];
                if (idMask == idValue)
                {
                    if (dDateBeg == null)
                    {
                        drv["DateBegFact"] = DBNull.Value;
                    }
                    else
                    {
                        drv["DateBegFact"] = dDateBeg;
                    }
                    if (dDateEnd == null)
                    {
                        drv["DateEndFact"] = DBNull.Value;
                    }
                    else
                    {
                        drv["DateEndFact"] = dDateEnd;
                    }
                    drv ["DurationMinutesFact"] = nDuration;
                }
                else
                {
                    idMask = idValue;

                    if (drv["DateBegFact"] == DBNull.Value)
                    {
                        dDateBeg = null;
                    }
                    else
                    {
                        dDateBeg = (DateTime)drv["DateBegFact"];
                    }

                    if (drv["DateEndFact"] == DBNull.Value)
                    {
                        dDateEnd = null;
                    }
                    else
                    {
                        dDateEnd = (DateTime)drv["DateEndFact"];
                    }

                    if (drv["DurationMinutesFact"] == DBNull.Value)
                    {
                        nDuration = 0;
                    }
                    else
                    {
                        nDuration = (int)drv["DurationMinutesFact"];
                    }
                }
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dr = dt.Rows[i];
                if (dr["DurationMinutesFact"] != DBNull.Value && (int)dr["DurationMinutesFact"] > 0)
                {
                    oOutputDocument.SetDateFact((int)dr["ID"], (DateTime?)dr["DateBegFact"], (DateTime?)dr["DateEndFact"]);
                    if (oOutputDocument.ErrorNumber != 0)
                    {
                        break;
                    }
                }
            }
            if (oOutputDocument.ErrorNumber == 0)
            {
                if (nDistance != nDistanceOld)
                {
                    oTrip.TripDistanceSave(nTripID, nDistance);
                }

                DialogResult = DialogResult.Yes;
                Dispose();
            }
        }
Exemplo n.º 15
0
        private bool grdData_Restore()
        {
            // собираем условия

            sPartnersList = sPackingsList = null;

            // поставщики
            if (sSelectedPartnersIDList.Length > 0)
            {
                sPartnersList = sSelectedPartnersIDList;
            }
            // выбранные товары
            if (sSelectedPackingsIDList.Length > 0)
            {
                sPackingsList = sSelectedPackingsIDList;
            }

            int?nPercents = null, nMonth = null;

            if (radPercents.Checked)
            {
                nPercents = (int)numPercents.Value;
            }
            if (radMonths.Checked)
            {
                nMonth = (int)numMonths.Value;
            }
            bool bFromNow = false;

            if (radFromNow.Checked)
            {
                bFromNow = true;
            }

            WaitOn(this);

            Good oGoods = new Good();

            oGoods.FilterPackingsIDList = sPackingsList;
            oGoods.FilterGoodsActual    = true;
            oGoods.FillData();
            if (oGoods.ErrorNumber != 0)
            {
                WaitOff(this);
                return(false);
            }
            for (int i = 0; i < oGoods.MainTable.Rows.Count; i++)
            {
                if ((int)oGoods.MainTable.Rows[i]["Retention"] == 0)
                {
                    WaitOff(this);
                    RFMMessage.MessageBoxAttention("В отчет не попадут товары с нулевым сроком годности!");
                    WaitOn(this);
                    break;
                }
            }

            grdData.DataSource = null;

            oReport.ReportInputsDateValid(dtrDates.dtpBegDate.Value.Date, dtrDates.dtpEndDate.Value.Date,
                                          sPartnersList, sPackingsList,
                                          nPercents, nMonth,
                                          bFromNow);

            grdData.Restore(oReport.MainTable);

            WaitOff(this);

            grdData.Select();

            return(oReport.ErrorNumber == 0);
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (cboOutputDocumentType.SelectedIndex < 0 || cboOutputDocumentType.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите тип расходного документа!");
                tcOutputDocument.SelectedTab = tabMain;
                cboOutputDocumentType.Select();
                return;
            }

            if (cboOwner.SelectedIndex < 0 || cboOwner.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите владельца товара!");
                tcOutputDocument.SelectedTab = tabMain;
                cboOwner.Select();
                return;
            }

            if (cboGoodState.SelectedIndex < 0 || cboGoodState.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите состояние товара!");
                tcOutputDocument.SelectedTab = tabMain;
                cboGoodState.Select();
                return;
            }

            if (ucSelectRecordIDForm_Salers.TxtData.Text.Length == 0)
            {
                RFMMessage.MessageBoxError("Выберите реквизиты продавца товара!");
                tcOutputDocument.SelectedTab = tabMain;
                ucSelectRecordIDForm_Salers.Select();
                return;
            }

            if (ucSelectRecordIDForm_Shippers.TxtData.Text.Length == 0)
            {
                RFMMessage.MessageBoxError("Выберите реквизиты грузоотправителя товара!");
                tcOutputDocument.SelectedTab = tabMain;
                ucSelectRecordIDForm_Shippers.Select();
                return;
            }

            if (ucSelectRecordIDForm_Buyers.TxtData.Text.Length == 0)
            {
                RFMMessage.MessageBoxError("Выберите реквизиты покупателя товара!");
                tcOutputDocument.SelectedTab = tabMain;
                ucSelectRecordIDForm_Buyers.Select();
                return;
            }

            if (cboCurrency.SelectedIndex < 0 || cboCurrency.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите валюту!");
                tcOutputDocument.SelectedTab = tabMain;
                cboCurrency.Select();
                return;
            }

            if (chkBillNeed.Checked &&
                txtBillNumber.Text.Length == 0 &&
                RFMMessage.MessageBoxYesNo("Не указан номер накладной.\nВсе равно сохранить?") == DialogResult.No)
            {
                tcOutputDocument.SelectedTab = tabOther;
                txtBillNumber.Select();
                return;
            }

            if (chkFactureNeed.Checked &&
                txtFactureNumber.Text.Length == 0 &&
                RFMMessage.MessageBoxYesNo("Не указан номер счета-фактуры.\nВсе равно сохранить?") == DialogResult.No)
            {
                tcOutputDocument.SelectedTab = tabOther;
                txtFactureNumber.Select();
                return;
            }


            // хоть один товар
            if (oOutputDocument.TableOutputsDocumentsGoods.Rows.Count == 0)
            {
                RFMMessage.MessageBoxAttention("Не введено ни одного товара...");
                return;
            }
            else
            {
                // хоть что-то введено
                bool bFound = false;
                foreach (DataRow r in oOutputDocument.TableOutputsDocumentsGoods.Rows)
                {
                    if ((decimal)r["QntWished"] > 0 || (decimal)r["BoxWished"] > 0)
                    {
                        bFound = true;
                        break;
                    }
                }
                if (!bFound)
                {
                    RFMMessage.MessageBoxYesNo("Ни для одного товара не введено количество...");
                    return;
                }
            }
            if (RFMMessage.MessageBoxYesNo("Сохранить расходный документ (заказ)?") == DialogResult.Yes)
            {
                oOutputDocument.DateOutput           = dtpDateOutputDocument.Value.Date;
                oOutputDocument.OutputDocumentTypeID = (int)cboOutputDocumentType.SelectedValue;
                oOutputDocument.GoodStateID          = (int)cboGoodState.SelectedValue;
                oOutputDocument.OwnerID    = (int)cboOwner.SelectedValue;
                oOutputDocument.CurrencyID = (int)cboCurrency.SelectedValue;

                oOutputDocument.DeliveryPrice      = oOutputDocument.VeterinaryPrice = 0;
                oOutputDocument.DeliveryCurrencyID = oOutputDocument.VeterinaryCurrencyID = Convert.ToInt32(oOutputDocument.CurrencyID);

                oOutputDocument.DeliveryNeed = chkDeliveryNeed.Checked;
                oOutputDocument.Note         = txtNote.Text.Trim();
                if (ucSelectRecordIDForm_Salers.txtData.Text != oOutputDocument.PartnerSalerFactName)
                {
                    oOutputDocument.PartnerDetailSalerID = Convert.ToInt16(ucSelectRecordIDForm_Salers.GetIdString());
                }
                if (ucSelectRecordIDForm_Shippers.txtData.Text != oOutputDocument.PartnerShipperFactName)
                {
                    oOutputDocument.PartnerDetailShipperID = Convert.ToInt16(ucSelectRecordIDForm_Shippers.GetIdString());
                }
                if (ucSelectRecordIDForm_Buyers.txtData.Text != oOutputDocument.PartnerBayerFactName)
                {
                    oOutputDocument.PartnerDetailBayerID = Convert.ToInt16(ucSelectRecordIDForm_Buyers.GetIdString());
                }
                oOutputDocument.PF_BillNeed    = chkBillNeed.Checked;
                oOutputDocument.BillNumber     = txtBillNumber.Text.Trim();
                oOutputDocument.PF_FactureNeed = chkFactureNeed.Checked;
                oOutputDocument.FactureNumber  = txtFactureNumber.Text.Trim();
                oOutputDocument.PF_PayBillNeed = chkPayBillNeed.Checked;
                oOutputDocument.PF_WarrantNeed = chkWarrantNeed.Checked;
                oOutputDocument.TPL            = chkTPL.Checked;
                oOutputDocument.NotForJoin     = chkNotForJoin.Checked;

                // добрались. сохраняем.
                Refresh();
                WaitOn(this);
                oOutputDocument.ClearError();
                bool bResult = oOutputDocument.Save();
                WaitOff(this);
                if (bResult && oOutputDocument.ErrorNumber == 0)
                {
                    RFMMessage.MessageBoxInfo("Расходный документ (заказ) сохранен.");
                    MotherForm.GotParam = new object[] { (int)oOutputDocument.ID };
                    DialogResult        = DialogResult.Yes;
                    Dispose();
                }
            }
        }
Exemplo n.º 17
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            bool bFoundConfirmed, bWGoodsConfirmed;

            bFoundConfirmed = bWGoodsConfirmed = false;
            bool bHasWeights = (tTableWeightGoods.Rows.Count > 0);
            DataGridViewCellEventArgs oDgvcea;

            oDgvcea = new DataGridViewCellEventArgs(LastGrid.CurrentCell.ColumnIndex, LastGrid.CurrentRow.Index);
            if (LastGrid.IsCurrentCellDirty)
            {
                bValidOK = true;
                LastGrid.CommitChanges();
                if (lastGrid == dgvPieceGoods)
                {
                    dgvPieceGoods_CellValidated(dgvPieceGoods, oDgvcea);
                    dgvPieceGoods_CellEndEdit(dgvPieceGoods, oDgvcea);
                }
                else
                {
                    dgvWeightGoods_CellEndEdit(dgvWeightGoods, oDgvcea);
                }
                if (!bValidOK)
                {
                    LastGrid.CurrentRow.Cells[LastGrid.CurrentCell.ColumnIndex].Selected = true;
                    return;
                }
            }
            if (bHasWeights)
            {
                foreach (DataRow dr in tTableWeightGoods.Rows)
                {
                    if ((decimal)dr["QntConfirmed"] > 0)
                    {
                        bWGoodsConfirmed = bFoundConfirmed = true;
                        break;
                    }
                }
            }
            if (!bWGoodsConfirmed)
            {
                foreach (DataRow dr in oOutput.TableOutputsGoods.Rows)
                {
                    if ((decimal)dr["QntConfirmed"] > 0)
                    {
                        bFoundConfirmed = true;
                        break;
                    }
                }
            }
            if (!bFoundConfirmed)
            {
                if (RFMMessage.MessageBoxYesNo("Внимание!\n\nНе подтверждено ни одного товара.\n\nВсе-таки подтвердить расход?") != DialogResult.Yes)
                {
                    return;
                }
            }
            if (bHasWeights && !bWeightingTry)
            {
                RFMMessage.MessageBoxAttention("В накладной имеется весовой товар!");
                tcGoods.SelectedTab = tabWeight;
                dgvWeightGoods.Select();
                return;
            }
            if (bHasWeights && !bWGoodsConfirmed)
            {
                if (RFMMessage.MessageBoxYesNo("Внимание!\n\nНе подтверждено ни одного весового товара.\n\nВсе-таки подтвердить расход?") != DialogResult.Yes)
                {
                    dgvWeightGoods.Select();
                    return;
                }
            }

            // подтверждение с прямым исправлением остатков в ячейке отгрузки?
            Setting oSet           = new Setting();
            string  sIfEasyConfirm = oSet.FillVariable("bEasyConfirm");
            bool    bEasyConfirm   = false;

            if (sIfEasyConfirm != null && sIfEasyConfirm.Length > 0)
            {
                try
                {
                    bEasyConfirm = Convert.ToBoolean(sIfEasyConfirm);
                }
                catch { }
            }

            Cell oCell = new Cell();

            oCell.ID = (int)oOutput.MainTable.Rows[0]["CellID"];
            oCell.FillTableCellsContents(oCell.ID, true);
            StringBuilder sbCellLess   = new StringBuilder("");
            StringBuilder sbCellAbsent = new StringBuilder("");
            StringBuilder sbWished     = new StringBuilder("");
            StringBuilder sbSelected   = new StringBuilder("");
            StringBuilder sbPicked     = new StringBuilder("");
            Boolean       bInOut;
            int           nGoodStateID = (int)oOutput.MainTable.Rows[0]["GoodStateID"];
            int           nOwnerID     = (int)oOutput.MainTable.Rows[0]["OwnerID"];

            foreach (DataRow droOutGoods in oOutput.TableOutputsGoods.Rows)
            {
                bInOut = false;
                foreach (DataRow droCellGoods in oCell.TableCellsContents.Rows)
                {
                    if ((bool)oOutput.MainTable.Rows[0]["SeparatePicking"])
                    {
                        if ((int)droCellGoods["PackingID"] == (int)droOutGoods["PackingID"] &&
                            (int)droCellGoods["GoodStateID"] == nGoodStateID)
//							&&      (int)droCellGoods["OwnerID"] == nOwnerID)
                        {
                            bInOut = true;
                            if ((decimal)droCellGoods["Qnt"] < (decimal)droOutGoods["QntConfirmed"])
                            {
                                sbCellLess = sbCellLess.Append(droOutGoods["GoodAlias"].ToString() + "\r\n");
                            }
                        }
                    }
                    else
                    {
                        if ((int)droCellGoods["PackingID"] == (int)droOutGoods["PackingID"] &&
                            (int)droCellGoods["GoodStateID"] == nGoodStateID &&
                            Convert.IsDBNull(droCellGoods["OwnerID"]))
                        {
                            bInOut = true;
                            if ((decimal)droCellGoods["Qnt"] < (decimal)droOutGoods["QntConfirmed"])
                            {
                                sbCellLess = sbCellLess.Append(droOutGoods["GoodAlias"].ToString() + "\r\n");
                            }
                        }
                    }
                }
                if (!bInOut && (decimal)droOutGoods["QntConfirmed"] > 0)
                {
                    sbCellAbsent = sbCellAbsent.Append(droOutGoods["GoodAlias"].ToString() + "\r\n");
                }
                if (((decimal)droOutGoods["QntConfirmed"] > 0) &&
                    ((decimal)droOutGoods["QntConfirmed"] != (decimal)droOutGoods["QntWished"]))
                {
                    sbWished = sbWished.Append(droOutGoods["GoodAlias"].ToString() + "\r\n");
                }

                if (((decimal)droOutGoods["QntConfirmed"] > 0) &&
                    ((decimal)droOutGoods["QntConfirmed"] != (decimal)droOutGoods["QntSelected"]))
                {
                    sbSelected = sbSelected.Append(droOutGoods["GoodAlias"].ToString() + "\r\n");
                }

                if (((decimal)droOutGoods["QntConfirmed"] > 0) &&
                    ((decimal)droOutGoods["QntConfirmed"] != (decimal)droOutGoods["QntPicked"]))
                {
                    sbPicked = sbPicked.Append(droOutGoods["GoodAlias"].ToString() + "\r\n");
                }
            }

            if (!bEasyConfirm)
            {
                if (sbCellAbsent.Length > 0)
                {
                    //if (RFMMessage.MessageBoxYesNo("В ячейке отгрузки отсутствуют товары:\r\n" +
                    //	sbCellAbsent + "Все-таки подтвердить расход?") == DialogResult.No)
                    RFMMessage.MessageBoxError("В ячейке отгрузки отсутствуют товары:\r\n" +
                                               sbCellAbsent +
                                               "Подтверждение расхода невозможно.");
                    return;
                }
                if (sbCellLess.Length > 0)
                {
                    //if (RFMMessage.MessageBoxYesNo("Для следующих товаров:\r\n" + sbCellLess + "количество в ячейке отгрузки меньше, чем подтверждаемое количество.\r\n" +
                    //	"Все-таки подтвердить расход?") == DialogResult.No)
                    RFMMessage.MessageBoxError("Для следующих товаров:\r\n" + sbCellLess + "количество в ячейке отгрузки меньше, чем подтверждаемое количество.\r\n" +
                                               "Подтверждение расхода невозможно.");
                    return;
                }
                if (sbWished.Length > 0)
                {
                    if (RFMMessage.MessageBoxYesNo("Для следующих товаров:\r\n" + sbWished + "подтверждаемое количество не равно заказанному.\r\n" +
                                                   "Все-таки подтвердить расход?") == DialogResult.No)
                    {
                        return;
                    }
                }
                if (sbSelected.Length > 0)
                {
                    if (RFMMessage.MessageBoxYesNo("Для следующих товаров:\r\n" + sbSelected + "подтверждаемое количество не равно подобранному.\r\n" +
                                                   "Все-таки подтвердить расход?") == DialogResult.No)
                    {
                        return;
                    }
                }
                if (sbPicked.Length > 0)
                {
                    if (RFMMessage.MessageBoxYesNo("Для следующих товаров:\r\n" + sbPicked + "подтверждаемое количество не равно собранному в ячейке отгрузки для этого расхода.\r\n" +
                                                   "Все-таки подтвердить расход?") == DialogResult.No)
                    {
                        return;
                    }
                }

                if (RFMMessage.MessageBoxYesNo("Подтвердить расход?") != DialogResult.Yes)
                {
                    return;
                }
            }
            else
            {
                /*
                 * if (sbPicked.Length > 0)
                 * {
                 * if (RFMMessage.MessageBoxYesNo("Для следующих товаров:\r\n" + sbPicked + "подтверждаемое количество не равно собранному в ячейке отгрузки для этого расхода.\r\n" +
                 * "Все-таки подтвердить расход?") == DialogResult.No)
                 * return;
                 * }
                 */

                if (RFMMessage.MessageBoxYesNo("Подтвердить расход?") != DialogResult.Yes)
                {
                    return;
                }

                // выполняем автоматическое исправление состояния ячейки отгрузки
                foreach (DataRow droOutGoods in oOutput.TableOutputsGoods.Rows)
                {
                    int     nPackingID    = (int)droOutGoods["PackingID"];
                    decimal nQntConfirmed = 0;
                    for (int j = 0; j < oOutput.TableOutputsGoods.Rows.Count; j++)
                    {
                        DataRow dr = oOutput.TableOutputsGoods.Rows[j];
                        if ((int)dr["PackingID"] == nPackingID)
                        {
                            nQntConfirmed += (decimal)dr["QntConfirmed"];
                        }
                    }
                    decimal nQntInCell   = 0;
                    bool    bFoundInCell = false;
                    foreach (DataRow droCellGoods in oCell.TableCellsContents.Rows)
                    {
                        if ((bool)oOutput.MainTable.Rows[0]["SeparatePicking"])
                        {
                            if ((int)droCellGoods["PackingID"] == nPackingID &&
                                (int)droCellGoods["GoodStateID"] == nGoodStateID &&
                                (int)droCellGoods["OwnerID"] == nOwnerID)
                            {
                                bFoundInCell = true;
                                nQntInCell   = (decimal)droCellGoods["Qnt"];
                                if (nQntInCell < nQntConfirmed)
                                {
                                    oCell.MedicationDirect((int)oCell.ID, nGoodStateID, nOwnerID, nPackingID, nQntConfirmed - nQntInCell,
                                                           ((RFMFormMain)Application.OpenForms[0]).UserID, "Исправление состояния ячейки для подтверждения расхода с кодом " + oOutput.ID.ToString());
                                }
                                break;                                 //
                            }
                        }
                        else
                        {
                            if ((int)droCellGoods["PackingID"] == (int)droOutGoods["PackingID"] &&
                                (int)droCellGoods["GoodStateID"] == nGoodStateID &&
                                Convert.IsDBNull(droCellGoods["OwnerID"]))
                            {
                                bFoundInCell = true;
                                nQntInCell   = (decimal)droCellGoods["Qnt"];
                                if (nQntInCell < nQntConfirmed)
                                {
                                    oCell.MedicationDirect((int)oCell.ID, nGoodStateID, null, nPackingID, nQntConfirmed - nQntInCell,
                                                           ((RFMFormMain)Application.OpenForms[0]).UserID, "Исправление состояния ячейки для подтверждения расхода с кодом " + oOutput.ID.ToString());
                                }
                                break;                                 //
                            }
                        }
                    }
                    if (!bFoundInCell)
                    {
                        // вообще нет товара в ячейке отгрузки
                        if ((bool)oOutput.MainTable.Rows[0]["SeparatePicking"])
                        {
                            oCell.MedicationDirect((int)oCell.ID, nGoodStateID, nOwnerID, nPackingID, nQntConfirmed,
                                                   ((RFMFormMain)Application.OpenForms[0]).UserID, "Исправление состояния ячейки для подтверждения расхода с кодом " + oOutput.ID.ToString());
                        }
                        else
                        {
                            oCell.MedicationDirect((int)oCell.ID, nGoodStateID, null, nPackingID, nQntConfirmed,
                                                   ((RFMFormMain)Application.OpenForms[0]).UserID, "Исправление состояния ячейки для подтверждения расхода с кодом " + oOutput.ID.ToString());
                        }
                    }
                }
            }

            Refresh();
            WaitOn(this);
            oOutput.ClearError();
            bool bResult = oOutput.ConfirmData(ID,
                                               ((RFMFormBase)Application.OpenForms[0]).UserInfo.UserID,
                                               oOutput.TableOutputsGoods);

            WaitOff(this);
            if (bResult && oOutput.ErrorNumber == 0)
            {
                RFMMessage.MessageBoxInfo("Расход подтвержден.");
                DialogResult = DialogResult.Yes;
                Dispose();
            }
            else
            {
                RFMMessage.MessageBoxError("Ошибка подтверждения расхода...");
                // не выходить из формы
            }
        }
Exemplo n.º 18
0
        private void frmFramesMedication_Load(object sender, EventArgs e)
        {
            bool lResult = true;

            lblAction.Text         = "";
            grcBoxQnt.AgrType      =
                grcPalQnt.AgrType  =
                    grcQnt.AgrType =
                        EnumAgregate.Sum;
            numBoxQnt.Minimum = numRestQnt.Minimum = 0;

            // параметры контейнера
            oFrame.FillData();
            if (oFrame.ErrorNumber != 0)
            {
                RFMMessage.MessageBoxError("Ошибка при получении данных о контейнере...");
                Dispose();
            }

            DataRow r = oFrame.MainTable.Rows[0];

            if (r == null)
            {
                RFMMessage.MessageBoxError("Не определен контейнер...");
                lResult = false;
            }

            if (lResult)
            {
                lblCellAddress.Text = "_не определена";
                // в ячейке?
                if (r["CellID"] == DBNull.Value || r["CellID"] == null)
                {
                    RFMMessage.MessageBoxAttention("Не определена ячейка, в которой находится контейнер...");
                    nCellCurID = oCell.ID = null;
                    //lResult = false;
                }
                else
                {
                    nCellCurID = Convert.ToInt32(r["CellID"]);
                    oCell.ID   = nCellCurID;
                    oCell.FillData();
                    if (oCell.MainTable.Rows.Count == 1)
                    {
                        lblCellAddress.Text = oCell.MainTable.Rows[0]["Address"].ToString() +
                                              " (" + oCell.MainTable.Rows[0]["StoreZoneName"].ToString() + ")";
                    }
                    else
                    {
                        RFMMessage.MessageBoxInfo("Внимание!\n\nНе найдена ячейка с кодом " + r["CellID"].ToString() + ",\n" +
                                                  "в которой зарегистрирован контейнер...");
                        //lResult = false;
                    }
                }
            }

            if (lResult)
            {
                lblFrameID.Text = r["ID"].ToString();

                // содержимое контейнера
                oFrame.FillTableFramesContents(oFrame.ID);
                if (oFrame.ErrorNumber != 0)
                {
                    lResult = false;
                }
            }

            if (lResult)
            {
                oFrame.TableFramesContents.PrimaryKey           = null;
                oFrame.TableFramesContents.Columns["ID"].Unique = false;

                oFrame.TableFramesContents.Columns.Add("PackingNew", Type.GetType("System.Boolean"));
                oFrame.TableFramesContents.Columns.Add("Changes", Type.GetType("System.String"));
                foreach (DataRow rd in oFrame.TableFramesContents.Rows)
                {
                    rd["Changes"]    = "";
                    rd["PackingNew"] = false;
                }

                grdFramesContents_Restore();
            }

            if (lResult)
            {
                //  заполнение cbo-классификаторов
                lResult = cboGood_Restore() &&
                          cboOwner_Restore() &&
                          cboGoodState_Restore();
                if (!lResult)
                {
                    RFMMessage.MessageBoxError("Ошибка при заполнении классификаторов (товары)...");
                }
            }

            if (lResult)
            {
                cboOwner.SelectedValue     = -1;
                cboGoodState.SelectedValue = -1;
                if (r["OwnerID"] != DBNull.Value && r["OwnerID"] != null)
                {
                    nOwnerCurID            = Convert.ToInt32(r["OwnerID"]);
                    cboOwner.SelectedValue = Convert.ToInt32(r["OwnerID"]);
                }
                if (r["GoodStateID"] != DBNull.Value && r["GoodStateID"] != null)
                {
                    nGoodStateCurID            = Convert.ToInt32(r["GoodStateID"]);
                    cboGoodState.SelectedValue = Convert.ToInt32(r["GoodStateID"]);
                }

                cboGood.SelectedValue = -1;
                txtGood.Text          = "";
                numBoxQnt.Value       = 0;
                numRestQnt.Value      = 0;
                dtpDateValid.Value    = DateTime.Now.Date;
            }

            // если что-то не получилось - выход
            if (!lResult)
            {
                Dispose();
            }

            pnlDataChange.Enabled = false;
            btnAdd.Enabled        = true;
            btnEdit.Enabled       = false;
            btnDelete.Enabled     = false;
            btnGridSave.Enabled   = false;
            btnGridUndo.Enabled   = false;

            grdFramesContents.Select();

            _bLoaded = true;
        }
Exemplo n.º 19
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (cboInputType.SelectedIndex < 0 || cboInputType.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите тип прихода!");
                cboInputType.Select();
                return;
            }

            if (cboOwner.SelectedIndex < 0 || cboOwner.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите владельца товара!");
                cboOwner.Select();
                return;
            }

            if (cboGoodState.SelectedIndex < 0 || cboGoodState.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите состояние товара!");
                cboGoodState.Select();
                return;
            }

            if (ucSelectRecordIDForm_Partners.TxtData.Text.Length == 0)
            {
                RFMMessage.MessageBoxError("Выберите поставщика товара!");
                ucSelectRecordIDForm_Partners.Select();
                return;
            }

            if (cboCurrency.SelectedIndex < 0 || cboCurrency.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Выберите валюту!");
                cboCurrency.Select();
                return;
            }

            // хоть один товар
            bool bFound = false;

            if (oInput.TableInputsGoods.Rows.Count == 0)
            {
                RFMMessage.MessageBoxAttention("Не введено ни одного товара...");
                return;
            }
            else
            {
                // хоть что-то введено
                foreach (DataRow r in oInput.TableInputsGoods.Rows)
                {
                    if ((decimal)r["QntWished"] > 0 || (decimal)r["BoxWished"] > 0)
                    {
                        bFound = true;
                        break;
                    }
                }
                if (!bFound)
                {
                    RFMMessage.MessageBoxAttention("Ни для одного товара не введено количество...");
                    return;
                }
            }
            if (RFMMessage.MessageBoxYesNo("Сохранить задание на приход?") == DialogResult.Yes)
            {
                // oInput.HostID присвоено на старте
                oInput.DateInput    = dtpDateInput.Value.Date;
                oInput.InputTypeID  = (int)cboInputType.SelectedValue;
                oInput.GoodStateID  = (int)cboGoodState.SelectedValue;
                oInput.OwnerID      = (int)cboOwner.SelectedValue;
                oInput.CurrencyID   = (int)cboCurrency.SelectedValue;
                oInput.DeliveryNeed = chkDeliveryNeed.Checked;
                oInput.Note         = txtNote.Text.Trim();
                if (ucSelectRecordIDForm_Partners.txtData.Text != oInput.PartnerName)
                {
                    oInput.PartnerID = Convert.ToInt16(ucSelectRecordIDForm_Partners.GetIdString());
                }

                // добрались. сохраняем.
                Refresh();
                WaitOn(this);
                oInput.ClearError();
                bool bResult = oInput.Save();
                WaitOff(this);
                if (bResult && oInput.ErrorNumber == 0)
                {
                    RFMMessage.MessageBoxInfo("Задание на приход сохранено.");
                    MotherForm.GotParam = new object[] { (int)oInput.ID };
                    DialogResult        = DialogResult.Yes;
                    Dispose();
                }
            }
        }
Exemplo n.º 20
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (cboStoresZones.SelectedIndex < 0 || cboStoresZones.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Не указана зона пикинга...");
                return;
            }

            if (cboHeavers.SelectedIndex < 0 || cboHeavers.SelectedValue == null)
            {
                RFMMessage.MessageBoxError("Не указан грузчик...");
                return;
            }

            bool lChecked = false;

            foreach (DataRow r in tTable.Rows)
            {
                if ((bool)r["Checked"] && !(bool)r["IsConfirmed"])
                {
                    lChecked = true;
                }
            }
            if (!lChecked)
            {
                RFMMessage.MessageBoxError("Не отмечено ни одного перемещения...");
                return;
            }

            // подтверждение с прямым исправлением остатков в ячейке отгрузки?
            Setting oSet           = new Setting();
            string  sIfEasyConfirm = oSet.FillVariable("bEasyConfirm");
            bool    bEasyConfirm   = false;

            if (sIfEasyConfirm != null && sIfEasyConfirm.Length > 0)
            {
                try
                {
                    bEasyConfirm = Convert.ToBoolean(sIfEasyConfirm);
                }
                catch { }
            }

            if (RFMMessage.MessageBoxYesNo("Подтвердить перемещения коробок/штук?") == DialogResult.Yes)
            {
                // и вот тут начинается большая песня с проверками
                int          nPackingID;
                bool         bIsEnough;
                decimal      nDeficit          = 0;
                decimal      nInCell           = 0;
                Cell         oCellTemp         = new Cell();
                TrafficFrame oTrafficFrameTemp = new TrafficFrame();

                foreach (DataRow r in tTable.Rows)
                {
                    if (!Convert.ToBoolean(r["Checked"]) || Convert.ToBoolean(r["IsConfirmed"]))
                    {
                        continue;
                    }

                    bIsEnough  = false;
                    nPackingID = Convert.ToInt32(r["PackingID"]);
                    nInCell    = 0;
                    nDeficit   = 0;

                    oCellTemp.ClearError();

                    oCellTemp.ID = Convert.ToInt32(r["CellSourceID"]);
                    oCellTemp.FillData();
                    // привязки
                    DataRow rCell = oCellTemp.MainTable.Rows[0];
                    if (!Convert.IsDBNull(rCell["FixedPackingID"]) &&
                        Convert.ToInt32(rCell["FixedPackingID"]) != nPackingID)
                    {
                        RFMMessage.MessageBoxError("Ячейка " + rCell["Address"].ToString() + " имеет фиксированную привязку к другому товару...");
                        continue;
                    }
                    if (!Convert.IsDBNull(rCell["FixedGoodStateID"]) &&
                        Convert.ToInt32(rCell["FixedGoodStateID"]) != nGoodStateID)
                    {
                        RFMMessage.MessageBoxError("Ячейка " + rCell["Address"].ToString() + " имеет фиксированную привязку к другому состоянию...");
                        continue;
                    }
                    if (
                        (bSeparatePicking &&
                         (
                             (!Convert.IsDBNull(rCell["FixedOwnerID"]) && Convert.ToInt32(rCell["FixedOwnerID"]) != nOwnerID) ||
                             Convert.IsDBNull(rCell["FixedOwnerID"])
                         )
                        )
                        ||
                        (!bSeparatePicking &&
                         !Convert.IsDBNull(rCell["FixedOwnerID"]))
                        )
                    {
                        RFMMessage.MessageBoxError("Ячейка " + rCell["Address"].ToString() + " имеет фиксированную привязку к другому хранителю...");
                        continue;
                    }

                    oCellTemp.FillTableCellsContents(oCellTemp.ID, true);
                    foreach (DataRow cc in oCellTemp.TableCellsContents.Rows)
                    {
                        if (bSeparatePicking)
                        {
                            if (Convert.ToInt32(cc["PackingID"]) == nPackingID &&
                                Convert.ToInt32(cc["GoodStateID"]) == nGoodStateID &&
                                !Convert.IsDBNull(cc["OwnerID"]) &&
                                Convert.ToInt32(cc["OwnerID"]) == nOwnerID)
                            {
                                if (Convert.ToDecimal(cc["Qnt"]) >= Convert.ToDecimal(r["ForQntConfirmed"]))
                                {
                                    bIsEnough = true;
                                }
                                else
                                {
                                    nInCell += Convert.ToDecimal(cc["Qnt"]);
                                }
                            }
                        }
                        else
                        {
                            if (Convert.ToInt32(cc["PackingID"]) == nPackingID &&
                                Convert.ToInt32(cc["GoodStateID"]) == nGoodStateID &&
                                Convert.IsDBNull(cc["OwnerID"]))
                            {
                                if (Convert.ToDecimal(cc["Qnt"]) >= Convert.ToDecimal(r["ForQntConfirmed"]))
                                {
                                    bIsEnough = true;
                                }
                                else
                                {
                                    nInCell += Convert.ToDecimal(cc["Qnt"]);
                                }
                            }
                        }
                        if (bIsEnough)
                        {
                            break;
                        }
                    }
                    // прошли содержимое ячейки. товара не хватает
                    if (!bIsEnough)
                    {
                        nDeficit = Convert.ToDecimal(r["ForQntConfirmed"]) - nInCell;

                        if (!bEasyConfirm)
                        {
                            // есть ли в нее трафики?
                            oTrafficFrameTemp.FilterCellsTargetList = oCellTemp.ID.ToString();
                            oTrafficFrameTemp.FilterConfirmed       = false;
                            oTrafficFrameTemp.FillData();
                            if (oTrafficFrameTemp.MainTable.Rows.Count > 0)
                            {
                                /*RFMMessage.MessageBoxAttention("ВНИМАНИЕ!\n" +
                                 *  "В ячейке " + rCell["Address"].ToString() + " недостаточно товара (" + Convert.ToDecimal(nDeficit).ToString("# ##0").Trim() + " шт.)\n" +
                                 *  r["GoodAlias"].ToString() + ".\n\n" +
                                 *  "Есть невыполненные операции транспортировки паллет в эту ячейку (контейнер " + oTrafficFrameTemp.MainTable.Rows[0]["FrameID"] + ") .");*/
                                RFMMessage.MessageBoxAttention("ВНИМАНИЕ!\n" +
                                                               "В ячейке " + rCell["Address"].ToString() + " недостаточно товара\n" +
                                                               r["GoodAlias"].ToString() + ".\n\n" +
                                                               "Есть невыполненные операции транспортировки паллет в эту ячейку (контейнер " + oTrafficFrameTemp.MainTable.Rows[0]["FrameID"] + ") .");
                                continue;
                            }
                            else
                            {
                                // трафиков нет. сами изменим состояние ячейки

                                /*string sDeficitText = (Convert.ToBoolean(r["Weighting"])) ?
                                 *      (Convert.ToDecimal(nDeficit).ToString("# ##0.000").Trim() + " кг") :
                                 *      RFMPublic.RFMUtilities.Declen(Convert.ToInt32(Math.Floor(nDeficit)), "штук", "штук", "штук");*/
                                string sDeficitText;
                                if (Convert.ToBoolean(r["Weighting"]))
                                {
                                    sDeficitText = Convert.ToDecimal(nDeficit).ToString("# ##0.000").Trim() + " кг";
                                }
                                else
                                {
                                    decimal nInBox     = Convert.ToDecimal(r["InBox"]);
                                    int     nFullBoxes = Convert.ToInt32(Math.Floor(nDeficit / nInBox));
                                    int     nPieces    = Convert.ToInt32(nDeficit - nFullBoxes * nInBox);

                                    sDeficitText = nFullBoxes.ToString() + " кор.";
                                    if (nPieces != 0)
                                    {
                                        sDeficitText = sDeficitText + "+" + nPieces.ToString() + " шт.";
                                    }
                                }
                                if (RFMMessage.MessageBoxYesNo("ВНИМАНИЕ!\n" +
                                                               "В ячейке " + rCell["Address"].ToString() + " не хватает товара (" + sDeficitText + ").\n" +
                                                               r["GoodAlias"].ToString() + "\n\n" +
                                                               "Невыполненных операций транспортировки паллет в эту ячейку нет.\n\n" +
                                                               "Выполнить исправление состояния ячейки на " + sDeficitText + "?", false) == DialogResult.Yes)
                                {
                                    oCellTemp.MedicationDirect((int)oCellTemp.ID, nGoodStateID, nOwnerID,
                                                               nPackingID, nDeficit, ((RFMFormMain)Application.OpenForms[0]).UserID,
                                                               "Исправление состояния ячейки для подтверждения перемещений по расходу с кодом " + oOutput.ID.ToString());
                                }
                            }
                        }
                        else
                        {
                            oCellTemp.MedicationDirect((int)oCellTemp.ID, nGoodStateID, nOwnerID,
                                                       nPackingID, nDeficit, ((RFMFormMain)Application.OpenForms[0]).UserID,
                                                       "Исправление состояния ячейки для подтверждения перемещений по расходу с кодом " + oOutput.ID.ToString());
                        }
                    }
                }
                // прошли все товары

                Refresh();
                WaitOn(this);
                oOutput.ClearError();
                bool bResult = oOutput.ConfirmTraffics(ID, false, chkMinusAllowed.Checked, (int)cboHeavers.SelectedValue, tTable);
                WaitOff(this);
                if (bResult && oOutput.ErrorNumber == 0)
                {
                    RFMMessage.MessageBoxInfo("Подтверждены перемещения коробок/штук.");
                    DialogResult = DialogResult.Yes;
                    Dispose();

                    /*
                     * if (ForLoad(true) == 0)
                     * {
                     *      DialogResult = DialogResult.Yes;
                     *      Dispose();
                     * }
                     */
                }
                else
                {
                    RFMMessage.MessageBoxError("Ошибка подтверждения перемещения коробок/штук...");
                }
            }
        }
Exemplo n.º 21
0
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (grdData.Rows.Count == 0 || grdData.CurrentRow == null)
            {
                return;
            }

            // сохранение - всего подряд
            //DataRow dr = ((DataRowView)((DataGridViewRow)grdData.Rows[grdData.CurrentRow.Index]).DataBoundItem).Row;
            //DataTable dtRep = CopyTable(dt, "dtRep", "OutputsDocumentsListID = '" + dr["OutputsDocumentsListID"].ToString() + "'", "");
            foreach (DataRow dr in dt.Rows)
            {
                // сохранение серии и номера, если введены
                if (dr["VeterinaryBlankSeries"] != null && !Convert.IsDBNull(dr["VeterinaryBlankSeries"]) && dr["VeterinaryBlankSeries"].ToString().Trim().Length > 0 ||
                    dr["VeterinaryBlankNumber"] != null && !Convert.IsDBNull(dr["VeterinaryBlankNumber"]) && dr["VeterinaryBlankNumber"].ToString().Trim().Length > 0)
                {
                    string sVeterinaryBlankSeries = "";
                    if (dr["VeterinaryBlankSeries"] != null && !Convert.IsDBNull(dr["VeterinaryBlankSeries"]) && dr["VeterinaryBlankSeries"].ToString().Length > 0)
                    {
                        sVeterinaryBlankSeries = dr["VeterinaryBlankSeries"].ToString().Trim();
                    }
                    string sVeterinaryBlankNumber = "";
                    if (dr["VeterinaryBlankNumber"] != null && !Convert.IsDBNull(dr["VeterinaryBlankNumber"]) && dr["VeterinaryBlankNumber"].ToString().Length > 0)
                    {
                        sVeterinaryBlankNumber = dr["VeterinaryBlankNumber"].ToString().Trim();
                    }
                    string sVeterinaryBlankType = (optLocalBlank.Checked ? "4" : "2");

                    string   sOutputsDocumentsList    = dr["OutputsDocumentsListID"].ToString();
                    string[] sOutputsDocumentsIDSplit = sOutputsDocumentsList.Split(new char[] { ',' });
                    foreach (string s in sOutputsDocumentsIDSplit)
                    {
                        if (s.Length == 0)
                        {
                            continue;
                        }
                        try
                        {
                            int nOutputDocumentID = Convert.ToInt32(s);
                            oOutputDocument.SaveVeterinaryBlankData(nOutputDocumentID,
                                                                    sVeterinaryBlankSeries, sVeterinaryBlankNumber,
                                                                    sVeterinaryBlankType, ((RFMFormMain)Application.OpenForms[0]).UserID);
                        }
                        catch { }
                    }
                }
                dr["VeterinarFIO"] = txtVeterinarFio.Text;
            }

            // несколько отмеченных записей или только текущая запись
            DataTable dtMarked = CopyTable(dt, "dtMarked", "IsMarked = true", "");

            if (dtMarked.Rows.Count == 0)
            {
                // текущая запись
                DataRow   drMarked     = ((DataRowView)((DataGridViewRow)grdData.Rows[grdData.CurrentRow.Index]).DataBoundItem).Row;
                DataTable dtMarkedTemp = CopyTable(dt, "dtMarkedTemp", "OutputsDocumentsListID = '" + drMarked["OutputsDocumentsListID"].ToString() + "'", "");
                dtMarked.Merge(dtMarkedTemp);
            }
            if (dtMarked.Rows.Count == 0)
            {
                RFMMessage.MessageBoxInfo("Нет данных...");
                return;
            }

            // печать 2-ой (обратной) страницы
            foreach (DataRow drp in dtMarked.Rows)
            {
                drp["IsPrintSecondPage"] = chkSecondPage.Checked;
            }

            if (chkVeterinaryListAdd.Checked)
            {
                string sMarkedOutputsDocumentsList = "";
                // если печатается приложение - должны быть заполнены серия и номер
                foreach (DataRow drp in dtMarked.Rows)
                {
                    if (drp["VeterinaryBlankSeries"] == null || Convert.IsDBNull(drp["VeterinaryBlankSeries"]) || drp["VeterinaryBlankSeries"].ToString().Trim().Length == 0 ||
                        drp["VeterinaryBlankNumber"] == null || Convert.IsDBNull(drp["VeterinaryBlankNumber"]) || drp["VeterinaryBlankNumber"].ToString().Trim().Length == 0)
                    {
                        RFMMessage.MessageBoxInfo("Не введены данные о серии и номере бланка ветеринарного свидетельства\n" +
                                                  "(печать с приложениями)...");
                        return;
                    }

                    drp["VeterinaryMarks"]            =
                        drp["VeterinaryLaboratories"] =
                            "см. Приложение 1";

                    sMarkedOutputsDocumentsList += drp["OutputsDocumentsListID"].ToString() + ",";
                }

                ActiveReport3 rep = new DataDynamics.ActiveReports.ActiveReport3();
                if (optLocalBlank.Checked)
                {
                    rep = new VeterinaryBlank();
                }
                else
                {
                    rep = new VeterinaryBlankSingle();
                }

                StartForm(new frmActiveReport(dtMarked, rep));

                if (RFMMessage.MessageBoxYesNo("Внимание!\n\n" +
                                               "Выполнена печать на бланках ветеринарных свидетельств.\n" +
                                               "Сейчас будет выполняться печать приложений.\n\n" +
                                               "Продолжить?") != DialogResult.Yes)
                {
                    return;
                }

                // данные для приложений
                OutputDocument oOutputDocumentAdd = new OutputDocument();
                oOutputDocumentAdd.FillVeterinaryAddTableOutputsDocumentsGoods(sMarkedOutputsDocumentsList, optPartnerGroup.Checked);
                if (oOutputDocumentAdd.ErrorNumber == 0 && oOutputDocumentAdd.TableOutputsDocumentsGoods != null)
                {
                    if (oOutputDocumentAdd.TableOutputsDocumentsGoods.Rows.Count == 0)
                    {
                        RFMMessage.MessageBoxInfo("Нет данных для печати приложений к ветеринарным свидетельствам...");
                        return;
                    }

                    RFMMessage.MessageBoxAttention("Выполняется печать приложений к ветеринарным свидетельствам...");
                    rep = new VeterinaryListAdd();
                    StartForm(new frmActiveReport(oOutputDocumentAdd.TableOutputsDocumentsGoods, rep));
                }
            }
            else
            {
                ActiveReport3 rep = new DataDynamics.ActiveReports.ActiveReport3();
                if (optLocalBlank.Checked)
                {
                    rep = new VeterinaryBlank();
                }
                else
                {
                    rep = new VeterinaryBlankSingle();
                }

                StartForm(new frmActiveReport(dtMarked, rep));
            }

            // отметка печати
            bool bOK = false;

            foreach (DataRow dr in dt.Rows)
            {
                if ((bool)dr["IsMarked"])
                {
                    dr["IsPrinted"] = true;
                    bOK             = true;
                }
            }
            if (!bOK)
            {
                // только для текущей
                DataRow drMarked = ((DataRowView)((DataGridViewRow)grdData.Rows[grdData.CurrentRow.Index]).DataBoundItem).Row;
                drMarked["IsPrinted"] = true;
            }
        }
        private void btnAddGood_Click(object sender, EventArgs e)
        {
            _SelectedPackingsIDList = null;
            _SelectedPackingsIDList = _SelectedIDList = null;
            int       nGoodID = 0;
            bool      nFound  = false;
            DataTable dtSource;
            Good      oGoodTemp = new Good();

            if (_SelectedInputDocumentID != null || _SelectedInputID != null)
            {
                if (_SelectedInputDocumentID != null)
                {
                    InputDocument oInputDocument = new InputDocument();
                    oInputDocument.ID = _SelectedInputDocumentID;
                    oInputDocument.FillTableInputsDocumentsGoods();
                    if (oInputDocument.TableInputsDocumentsGoods.Rows.Count == 0)
                    {
                        RFMMessage.MessageBoxAttention("В выбранном приходном документе нет товаров...");
                        return;
                    }
                    dtSource = oInputDocument.TableInputsDocumentsGoods.Copy();
                }
                else
                {
                    Input oInput = new Input();
                    oInput.ID = _SelectedInputID;
                    oInput.FillTableInputsGoods();
                    if (oInput.TableInputsGoods.Rows.Count == 0)
                    {
                        RFMMessage.MessageBoxAttention("В выбранном задании на приход нет товаров...");
                        return;
                    }
                    dtSource = oInput.TableInputsGoods.Copy();
                }
                if (StartForm(new frmSelectID(this, dtSource,
                                              "GoodAlias, GoodBarcode, Articul, GoodGroupName, GoodBrandName, Retention, Weighting, GoodActual, CountryName, ERPCode",
                                              "Товар, Штрих-Код, Артикул, Группа, Бренд, Срок годн., Вес., Акт., Страна, ERP-код", true)) != DialogResult.Yes)
                {
                    _SelectedIDList = null;
                    return;
                }
                if (_SelectedIDList == null || !_SelectedIDList.Contains(","))
                {
                    return;
                }
                string[]      cIDList = _SelectedIDList.Split(',');
                StringBuilder sb      = new StringBuilder();
                DataRow       dr;
                for (int i = 0; i < cIDList.Length; i++)
                {
                    for (int j = 0; j < dtSource.Rows.Count; j++)
                    {
                        dr = dtSource.Rows[j];
                        if (cIDList[i] == dr["ID"].ToString())
                        {
                            sb.Append(dr["PackingID"].ToString() + ",");
                        }
                    }
                }
                oGoodTemp.PackingsIDList = "," + sb;
                oGoodTemp.FillData();
            }

            else
            {
                if (StartForm(new frmSelectOnePacking(this, true)) == DialogResult.Yes)
                {
                    if (_SelectedPackingsIDList == null || !_SelectedPackingsIDList.Contains(","))
                    {
                        return;
                    }

                    RFMCursorWait.Set(true);
                    oGoodTemp.PackingsIDList = "," + _SelectedPackingsIDList;
                    oGoodTemp.FillData();
                    if (oGoodTemp.ErrorNumber != 0 || oGoodTemp.MainTable == null || oGoodTemp.MainTable.Rows.Count == 0)
                    {
                        RFMCursorWait.Set(false);
                        return;
                    }
                }
            }
            foreach (DataRow rg in oGoodTemp.MainTable.Rows)
            {
                // нет ли уже такого товара?
                nGoodID = Convert.ToInt32(rg["GoodID"]);
                nFound  = false;

                foreach (DataRow drTemp in tGoodsVeterinaries.Rows)
                {
                    if (Convert.ToInt32(drTemp["GoodID"]) == nGoodID)
                    {
                        nFound = true;
                        if (oGoodTemp.MainTable.Rows.Count == 1)
                        {
                            RFMCursorWait.Set(false);
                            RFMMessage.MessageBoxError("Такой товар уже в списке...");
                            RFMCursorWait.Set(true);
                        }
                        break;
                    }
                }
                if (!nFound)
                {
                    // добавляем новую строку для выбранного товара
                    DataTable dtTemp = tGoodsVeterinaries.Clone();
                    dtTemp.Columns["GoodID"].AllowDBNull = true;
                    DataRow dr = dtTemp.Rows.Add();
                    dr["GoodID"]        = nGoodID;
                    dr["GoodName"]      = rg["GoodName"];
                    dr["GoodAlias"]     = rg["GoodAlias"];
                    dr["GoodBarCode"]   = rg["GoodBarCode"];
                    dr["Articul"]       = rg["Articul"];
                    dr["GoodGroupName"] = rg["GoodGroupName"];
                    dr["GoodBrandName"] = rg["GoodBrandName"];
                    dr["CountryName"]   = rg["CountryName"];
                    dr["Weighting"]     = rg["Weighting"];
                    dr["GoodActual"]    = rg["GoodActual"];
                    dr["Netto"]         = rg["Netto"];
                    dr["Brutto"]        = rg["Brutto"];
                    dr["Retention"]     = rg["Retention"];
                    dr["GoodERPCode"]   = rg["GoodERPCode"];

                    tGoodsVeterinaries.ImportRow(dr);
                }
                // встать на последнюю добавленную строку
                if (nGoodID != 0)
                {
                    grdData.GridSource.Position = grdData.GridSource.Find("GoodID", nGoodID);
                    if (grdData.GridSource.Position < 0)
                    {
                        grdData.GridSource.MoveFirst();
                    }
                }
                RFMCursorWait.Set(false);
            }
            _SelectedPackingsIDList = null;

            btnDeleteGood.Enabled = (grdData.Rows.Count > 0);
        }
Exemplo n.º 23
0
        private void dgvInputDocumentGoods_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }

            DataGridViewRow r = dgvInputDocumentGoods.Rows[e.RowIndex];

            if (dgvInputDocumentGoods.Columns[e.ColumnIndex].Name == "dgrcQntBrought")
            {
                bIsEditQnt = true;
                if (r.Cells["dgrcQntBrought"].Value == null || r.Cells["dgrcQntBrought"].Value == DBNull.Value)
                {
                    r.Cells["dgrcQntBrought"].Value = 0;
                    return;
                    //if ((decimal)r.Cells["dgrcQntWished"].Value > 0)
                    //{
                    //RFMMessage.MessageBoxAttention("Не указано количество поступившего товара [шт.]!");
                    //dgvInputDocumentGoods.Refresh();
                    //return;
                    //}
                }

                if (!(bool)r.Cells["dgrcWeighting"].Value)
                {
                    if (!bIsEditBox)
                    {
                        // если изменилось значение и оно не равно заказу - сказать
                        if ((decimal)r.Cells["dgrcQntBrought"].Value > (decimal)r.Cells["dgrcQntWished"].Value)
                        {
                            //RFMMessage.MessageBoxAttention("Количество поступившего товара [шт.] больше заказанного!");
                        }
                        else
                        {
                            if ((decimal)r.Cells["dgrcQntBrought"].Value == 0)
                            {
                                //RFMMessage.MessageBoxAttention("Не указано количество поступившего товара [шт.]!");
                            }
                            else
                            {
                                if ((decimal)r.Cells["dgrcQntBrought"].Value < (decimal)r.Cells["dgrcQntWished"].Value)
                                {
                                    //RFMMessage.MessageBoxAttention("Количество поступившего товара [шт.] меньше заказанного!");
                                }
                            }
                        }
                    }
                }
                bIsEditQnt = false;
            }

            if (dgvInputDocumentGoods.Columns[e.ColumnIndex].Name == "dgrcBoxBrought")
            {
                bIsEditBox = false;
                if (r.Cells["dgrcBoxBrought"].Value == null || r.Cells["dgrcBoxBrought"].Value == DBNull.Value)
                {
                    r.Cells["dgrcBoxBrought"].Value = 0;
                    return;
                    //if ((decimal)r.Cells["dgrcQntWished"].Value > 0)
                    //{
                    //	RFMMessage.MessageBoxAttention("Не указано количество поступившего товара [кор.]!");
                    //	dgvInputDocumentGoods.Refresh();
                    //	return;
                    //}
                }

                // если изменилось значение и оно не равно заказу - сказать
                if (!bIsEditQnt)
                {
                    if ((decimal)r.Cells["dgrcBoxBrought"].Value > (decimal)r.Cells["dgrcBoxWished"].Value)
                    {
                        //RFMMessage.MessageBoxAttention("Количество поступившего товара [кор.] больше заказанного!");
                    }
                    else
                    {
                        if ((decimal)r.Cells["dgrcBoxBrought"].Value == 0)
                        {
                            //RFMMessage.MessageBoxAttention("Не указано количество поступившего товара [кор.]!");
                        }
                        else
                        {
                            if ((decimal)r.Cells["dgrcBoxBrought"].Value < (decimal)r.Cells["dgrcBoxWished"].Value)
                            {
                                //RFMMessage.MessageBoxAttention("Количество поступившего товара [кор.] меньше заказанного!");
                            }
                        }
                    }
                }
                bIsEditBox = false;
            }

            if (dgvInputDocumentGoods.Columns[e.ColumnIndex].Name == "dgrcVat")
            {
                if (r.Cells["dgrcVat"].Value == null || r.Cells["dgrcVat"].Value == DBNull.Value)
                {
                    r.Cells["dgrcVat"].Value = 0;
                }

                // проверка ставок НДС
                decimal nVat = (decimal)r.Cells["dgrcVat"].Value;
                if (nVat == 0)
                {
                    RFMMessage.MessageBoxAttention("Не указана ставка НДС...");
                }
                else
                {
                    decimal?nVat1 = null, nVat2 = null;
                    Setting oSet     = new Setting();
                    string  sVatTemp = null;
                    sVatTemp = oSet.FillVariable("gnVat1");
                    if (sVatTemp != null && sVatTemp != "")
                    {
                        nVat1 = Convert.ToDecimal(sVatTemp);
                    }
                    sVatTemp = oSet.FillVariable("gnVat2");
                    if (sVatTemp != null && sVatTemp != "")
                    {
                        nVat2 = Convert.ToDecimal(sVatTemp);
                    }
                    if (nVat1.HasValue && nVat != nVat1 && nVat2.HasValue && nVat != nVat2 ||
                        !nVat1.HasValue && nVat2.HasValue && nVat != nVat2 ||
                        nVat1.HasValue && nVat != nVat1 && !nVat2.HasValue)
                    {
                        RFMMessage.MessageBoxError("Указана неверная ставка НДС...");
                        r.Cells["dgrcVat"].Value = 0;
                    }
                }
            }

            dgvInputDocumentGoods.Refresh();
        }