CREATE OR ALTER procedure SAVE_TARA_NETTO (
    PROGRAM_ID integer,
    OPERATOR_ID integer,
    TRANSPORT_ID integer,
    EVENT_BRUTTO_ID integer,
    CARGO_ID integer,
    TARA double precision,
    BRUTTO double precision,
    DIRECTION integer,
    COUNT_WEIGHT integer,
    PRICE_TONNA double precision,
    LOSS double precision,
    ORGANIZATION_LIMIT_ID integer,
    CARD_ID integer,
    PASS_BACK integer,
    WEIGH_TWICE integer)
returns (
    ID integer,
    EVENT_TARA_ID integer)
as
declare variable NETTO double precision;
declare variable NETTO_KG integer;
declare variable PRICE double precision;
declare variable REMAINDER double precision;
declare variable REAL_NETTO double precision;
declare variable PRICE_KOPP integer;
begin
  /************************************************/
  EXECUTE PROCEDURE
    SAVE_TARA(
     :PROGRAM_ID,
     :OPERATOR_ID,
     :TRANSPORT_ID,
     :TARA,
     :COUNT_WEIGHT,
     :CARD_ID)
  RETURNING_VALUES
    :EVENT_TARA_ID;
  /************************************************/
  REAL_NETTO = BRUTTO - TARA;
  NETTO_KG = (REAL_NETTO - (REAL_NETTO/100*LOSS)) * 1000;
  NETTO = NETTO_KG;
  NETTO = NETTO / 1000;
  /************************************************/
  FOR
    SELECT
      REMAINDER
    FROM
      ORGANIZATION_CARGO
    WHERE
      (CARGO_ID = :CARGO_ID) AND
      (ORGANIZATION_ID = :ORGANIZATION_LIMIT_ID)
    INTO
      :REMAINDER
  DO
    BEGIN
      IF (:DIRECTION = 0)
      THEN
        REMAINDER = REMAINDER + NETTO;
      ELSE
        REMAINDER = REMAINDER - NETTO;

      UPDATE
        ORGANIZATION_CARGO
      SET
        REMAINDER = :REMAINDER
      WHERE
        (CARGO_ID = :CARGO_ID) AND
        (ORGANIZATION_ID = :ORGANIZATION_LIMIT_ID);
    END
  /************************************************/
  ID = GEN_ID(GEN_EVENT_NETTO_ID, 1);

  PRICE_KOPP = NETTO * PRICE_TONNA * 100;
  PRICE = PRICE_KOPP;
  PRICE = PRICE / 100;
  INSERT INTO
    EVENT_NETTO
    (ID,
     PROGRAM_ID,
     OPERATOR_ID,
     EVENT_TARA_ID,
     EVENT_BRUTTO_ID,
     REAL_NETTO,
     LOSS,
     NETTO,
     PRICE,
     PRICE_TONNA,
     PASS_BACK)
  VALUES
    (:ID,
     :PROGRAM_ID,
     :OPERATOR_ID,
     :EVENT_TARA_ID,
     :EVENT_BRUTTO_ID,
     :REAL_NETTO,
     :LOSS,
     :NETTO,
     :PRICE,
     :PRICE_TONNA,
     :PASS_BACK);
  /************************************************/
  UPDATE
    EVENT_BRUTTO
  SET
    EVENT_BRUTTO.CARGO_ID = :CARGO_ID,
    EVENT_BRUTTO.CARGO_PRICE_TONNA = :PRICE_TONNA
  WHERE
    EVENT_BRUTTO.ID = :EVENT_BRUTTO_ID;
  /************************************************/
  IF (WEIGH_TWICE = 1)
  THEN
    BEGIN
      UPDATE
        TRANSPORT
      SET
        EVENT_TARA_ID = NULL
      WHERE
        ID = :TRANSPORT_ID;
    END
  /************************************************/
  SUSPEND;
END;