<p>Additional check document for ready to account (make acc.entries).</p>
@param pReqVars additional param
@param pEntity entity
@param pRequestData Request Data
@throws Exception - an exception if don't
3605
@Override
  public final void addCheckIsReadyToAccount(
    final Map<String, Object> pReqVars,
      final PurchaseInvoice pEntity,
        final IRequestData pRequestData) throws Exception {
    // nothing
  }
482603
public final <T> T retrieveEntity(final Map<String, Object> pAddParam,
    final Class<T> pEntityClass,
      final IRecordSet<RS> pRecordSet) throws Exception {
    @SuppressWarnings("unchecked")
    IFactorySimple<T> facEn = (IFactorySimple<T>) this.entitiesFactoriesFatory
      .lazyGet(pAddParam, pEntityClass);
    T entity = facEn.create(pAddParam);
    String foreignFieldNmsNm = "foreignFieldNms";
    List<String> foreignFieldNms = new ArrayList<String>();
    pAddParam.put(foreignFieldNmsNm, foreignFieldNms);
    String currentLevelNm = "currentLevel";
    List<Integer> currentLevel = new ArrayList<Integer>();
    currentLevel.add(1);
    pAddParam.put(currentLevelNm, currentLevel);
    String deepLevelNm = "deepLevel";
    List<Integer> deepLevel = new ArrayList<Integer>();
    deepLevel.add(2); //default top level
    pAddParam.put(deepLevelNm, deepLevel);
    this.fillerEntitiesFromRs.fill(pAddParam, entity, pRecordSet);
    //(TODO itself) exit from all recursions:
    pAddParam.remove(currentLevelNm);
    pAddParam.remove(deepLevelNm);
    pAddParam.remove(foreignFieldNmsNm);
    return entity;
  }
888954
public final void makeAccentryMatchingReversed(
    final Map<String, Object> pReqVars, final String pEntryId,
      final BankStatementLine pBsl, final DateFormat pDateFormat,
        final String pLangDef) throws Exception {
    EBankEntryResultType resultRecordType = EBankEntryResultType.ACC_ENTRY;
    EBankEntryResultAction resultAction = null;
    String resultDescription = null;
    Long resultRecordId = null;
    AccountingEntry accent = getSrvOrm().retrieveEntityById(pReqVars,
      AccountingEntry.class, Long.parseLong(pEntryId));
    if (accent == null) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "cant_found_accentry");
    }
    if (accent.getSourceType() == 1010) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "AlreadyDone");
    }
    if (pBsl.getItsAmount().compareTo(BigDecimal.ZERO) > 0 && pBsl
      .getItsAmount().compareTo(accent.getDebit()) != 0
        && accent.getSubaccDebitType() != 2002 && !pBsl.getItsOwner()
          .getBankAccount().getItsId().equals(accent.getSubaccDebitId())) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "record_is_not_matching");
    } else if (pBsl.getItsAmount().compareTo(BigDecimal.ZERO) < 0 && pBsl
      .getItsAmount().abs().compareTo(accent.getCredit()) != 0
        && accent.getSubaccCreditType() != 2002 && !pBsl.getItsOwner()
          .getBankAccount().getItsId().equals(accent.getSubaccCreditId())) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "record_is_not_matching");
    }
    if (EBankEntryStatus.VOIDED.equals(pBsl.getItsStatus())) {
      if (accent.getIdDatabaseBirth() != getSrvOrm().getIdDatabase()) {
        throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
          "can_not_change_foreign_src");
      }
      resultAction = EBankEntryResultAction.CREATE;
      AccountingEntry reversed = accent;
      accent = new AccountingEntry();
      accent.setSourceType(pBsl.constTypeCode());
      accent.setSourceId(pBsl.getItsId());
      accent.setSourceDatabaseBirth(pBsl.getIdDatabaseBirth());
      accent.setIdDatabaseBirth(reversed.getIdDatabaseBirth());
      accent.setReversedId(reversed.getItsId());
      accent.setReversedIdDatabaseBirth(reversed.getIdDatabaseBirth());
      accent.setItsDate(new Date(reversed.getItsDate().getTime() + 1));
      accent.setAccDebit(reversed.getAccDebit());
      accent.setSubaccDebit(reversed.getSubaccDebit());
      accent.setSubaccDebitId(reversed.getSubaccDebitId());
      accent.setSubaccDebitType(reversed.getSubaccDebitType());
      accent.setDebit(reversed.getDebit().negate());
      accent.setAccCredit(reversed.getAccCredit());
      accent.setSubaccCredit(reversed.getSubaccCredit());
      accent.setSubaccCreditId(reversed.getSubaccCreditId());
      accent.setSubaccCreditType(reversed.getSubaccCreditType());
      accent.setCredit(reversed.getCredit().negate());
      accent.setDescription(makeDescrForCreated(pBsl, pDateFormat, pLangDef)
        + " " + getSrvI18n().getMsg("reversed_n", pLangDef)
          + accent.getReversedIdDatabaseBirth() + "-" + accent.getReversedId());
      getSrvOrm().insertEntity(pReqVars, accent);
      accent.setIsNew(false);
      String oldDesr = "";
      if (reversed.getDescription() != null) {
        oldDesr = reversed.getDescription();
      }
      reversed.setDescription(oldDesr + " " + getSrvI18n()
        .getMsg("reversing_n", pLangDef) + accent.getIdDatabaseBirth() + "-"
          + accent.getItsId());
      reversed.setReversedId(accent.getItsId());
      reversed.setReversedIdDatabaseBirth(accent.getIdDatabaseBirth());
      getSrvOrm().updateEntity(pReqVars, reversed);
    } else {
      resultAction = EBankEntryResultAction.MATCH;
    }
    resultRecordId = accent.getItsId();
    resultDescription = makeBslResDescr(resultAction, pDateFormat, accent,
      accent.getItsDate(), pLangDef);
    pBsl.setResultAction(resultAction);
    pBsl.setResultRecordType(resultRecordType);
    pBsl.setResultRecordId(resultRecordId);
    pBsl.setResultDescription(resultDescription);
    getSrvOrm().updateEntity(pReqVars, pBsl);
  }
727303
@Override
  public final List<T> retrieveEntriesFor(
    final Map<String, Object> pAddParam,
      final IDocWarehouse pEntity) throws Exception {
    String where = null;
    Long docId = pEntity.getItsId();
    if (pEntity.getIdBirth() != null) {
      docId = pEntity.getIdBirth();
    }
    String tblNm = getDrawItemEntryClass().getSimpleName().toUpperCase();
    if (pEntity instanceof IDrawItemSource) {
      where = " where SOURCETYPE=" + pEntity.constTypeCode()
        + " and SOURCEID="  + docId + " and " + tblNm + ".IDDATABASEBIRTH="
          + pEntity.getIdDatabaseBirth();
    } else if (pEntity instanceof IMakingWarehouseEntry) {
      where = " where DRAWINGTYPE=" + pEntity.constTypeCode()
        + " and DRAWINGID=" + docId + " and " + tblNm + ".IDDATABASEBIRTH="
          + pEntity.getIdDatabaseBirth();
    }
    List<T> result = null;
    if (where != null) {
      result = getSrvOrm().retrieveListWithConditions(pAddParam,
        getDrawItemEntryClass(), where);
      where = null;
    }
    if (pEntity instanceof IDrawItemSource) { //also may draw, e.g. Manufacture
      where = " where DRAWINGTYPE=" + pEntity.constTypeCode()
        + " and DRAWINGID="  + docId + " and " + tblNm + ".IDDATABASEBIRTH="
          + pEntity.getIdDatabaseBirth();
    }
    if (where != null) {
      if (result == null) {
        result = getSrvOrm().retrieveListWithConditions(pAddParam,
          getDrawItemEntryClass(), where);
      } else {
        result.addAll(getSrvOrm().retrieveListWithConditions(pAddParam,
          getDrawItemEntryClass(), where));
      }
      where = null;
    }
    if (pEntity.getLinesWarehouseType() == EWarehouseMovementType.LOAD) {
      //e.g. PurchaseInvoice
      where = " where SOURCEOWNERTYPE=" + pEntity.constTypeCode()
        + " and SOURCEOWNERID=" + docId + " and " + tblNm + ".IDDATABASEBIRTH="
          + pEntity.getIdDatabaseBirth();
    } else if (pEntity.getLinesWarehouseType()
      == EWarehouseMovementType.WITHDRAWAL) {
      //e.g. SalesInvoice
      where = " where DRAWINGOWNERTYPE=" + pEntity.constTypeCode()
        + " and DRAWINGOWNERID=" + docId + " and " + tblNm + ".IDDATABASEBIRTH="
          + pEntity.getIdDatabaseBirth();
    }
    if (where != null) {
      if (result == null) {
        result = getSrvOrm().retrieveListWithConditions(pAddParam,
          getDrawItemEntryClass(), where);
      } else {
        result.addAll(getSrvOrm().retrieveListWithConditions(pAddParam,
          getDrawItemEntryClass(), where));
      }
    }
    return result;
  }
915495
protected final <I extends IHasIdLongVersionName> ItemInList createItemInList(final Map<String, Object> pReqVars, final I pItem) throws Exception {
    ItemInList itemInList = new ItemInList();
    itemInList.setIsNew(true);
    EShopItemType itemType;
    if (pItem.getClass() == InvItem.class) {
      itemType = EShopItemType.GOODS;
    } else if (pItem.getClass() == ServiceToSale.class) {
      itemType = EShopItemType.SERVICE;
    } else if (pItem.getClass() == SeGoods.class) {
      itemType = EShopItemType.SEGOODS;
    } else if (pItem.getClass() == SeService.class) {
      itemType = EShopItemType.SESERVICE;
    } else {
      throw new Exception("NYI for " + pItem.getClass());
    }
    itemInList.setItsType(itemType);
    itemInList.setItemId(pItem.getItsId());
    itemInList.setItsName(pItem.getItsName());
    itemInList.setAvailableQuantity(BigDecimal.ZERO);
    return itemInList;
  }
1033693
@Override
  public final void process(final Map<String, Object> pAddParam,
    final IRequestData pRequestData) throws Exception {
    this.prcAccEntitiesPage.process(pAddParam, pRequestData);
    pRequestData.setAttribute("typeCodeSubaccMap",
      this.srvTypeCode.getTypeCodeMap());
  }
496750
@Override
  public final void makeOtherEntries(final Map<String, Object> pAddParam,
    final PrepaymentFrom pEntity, final IRequestData pRequestData,
      final boolean pIsNew) throws Exception {
    // nothing
  }
1218142
@Override
  public final void makeFirstPrepareForSave(final Map<String, Object> pAddParam,
    final GoodsLoss pEntity,
      final IRequestData pRequestData) throws Exception {
    // nothing
  }
576635
@Override
  public final void handle(final Map<String, Object> pReqVars,
    final IRequestData pRequestData,
      final OutputStream pSous) throws Exception {
    try {
      String nmEnt = pRequestData.getParameter("nmEnt");
      Class entityClass = this.entitiesMap.get(nmEnt);
      this.srvDatabase.setIsAutocommit(false);
      this.srvDatabase.setTransactionIsolation(this.readTi);
      this.srvDatabase.beginTransaction();
      IHasId<?> entity = null;
      @SuppressWarnings("unchecked")
      IFactorySimple<IHasId<?>> entFac = (IFactorySimple<IHasId<?>>)
        this.entitiesFactoriesFatory.lazyGet(pReqVars, entityClass);
      entity = entFac.create(pReqVars);
      this.fillEntityFromReq.fill(pReqVars, entity, pRequestData);
      String reporterNm = pRequestData.getParameter("reporterNm");
      @SuppressWarnings("unchecked")
      IEntityFileReporter<IHasId<?>, ?> efr =
        (IEntityFileReporter<IHasId<?>, ?>)
          this.fctEntitiesFileReporters.lazyGet(pReqVars, reporterNm);
      efr.makeReport(pReqVars, entity, pRequestData, pSous);
      this.srvDatabase.commitTransaction();
    } catch (Exception ex) {
      if (!this.srvDatabase.getIsAutocommit()) {
        this.srvDatabase.rollBackTransaction();
      }
      throw ex;
    } finally {
      this.srvDatabase.releaseResources();
    }
  }
945625
@Override
  public final void withdrawal(final Map<String, Object> pAddParam,
    final IMakingWarehouseEntry pEntity, final Date pDateAccount,
      final Long pDrawingOwnerId) throws Exception {
    if (!pEntity.getIdDatabaseBirth()
      .equals(getSrvOrm().getIdDatabase())) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "can_not_make_di_entry_for_foreign_src");
    }
    String queryMain = lazyGetQuery(srvAccSettings
      .lazyGetAccSettings(pAddParam).getCogsMethod().getFileName());
    StringBuffer sb = new StringBuffer();
    int i = 0;
    for (ADrawItemSourcesLine drawItemSourceLine
      : getDrawItemSources(pAddParam)) {
      if (drawItemSourceLine.getIsUsed()) {
        String query = lazyGetQuery(drawItemSourceLine.getFileName());
        query = query.replace(":IDDATABASEBIRTH", String.valueOf(getSrvOrm()
          .getIdDatabase()));
        query = query.replace(":INVITEM", pEntity.getInvItem()
          .getItsId().toString());
        query = query.replace(":UNITOFMEASURE", pEntity.getUnitOfMeasure()
          .getItsId().toString());
        if (i++ > 0) {
          sb.append("\nunion all\n\n");
        }
        sb.append(query);
      }
    }
    String sourceAll = sb.toString();
    if (sourceAll.trim().length() == 0) {
      throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
        "there_is_no_draw_material_rules");
    }
    //ADrawItemEntry just holder source id and type
    List<T> sources =
      new ArrayList<T>();
    queryMain = queryMain.replace(":SOURCEALL",
      sourceAll);
    BigDecimal quantityInSources = BigDecimal.ZERO;
    IRecordSet<RS> recordSet = null;
    try {
      recordSet = getSrvDatabase().retrieveRecords(queryMain);
      if (recordSet.moveToFirst()) {
        do {
          Long sourceId = recordSet.getLong("SOURCEID");
          Integer sourceType = recordSet.getInteger("SOURCETYPE");
          Long sourceOwnerId = recordSet.getLong("SOURCEOWNERID");
          Integer sourceOwnerType = recordSet.getInteger("SOURCEOWNERTYPE");
          BigDecimal theRest = BigDecimal
              .valueOf(recordSet.getDouble("THEREST"));
          T source = createDrawItemEntry(pAddParam);
          source.setSourceId(sourceId);
          source.setSourceType(sourceType);
          source.setSourceOwnerId(sourceOwnerId);
          source.setSourceOwnerType(sourceOwnerType);
          sources.add(source);
          quantityInSources = quantityInSources.add(theRest);
          if (quantityInSources.compareTo(pEntity.getItsQuantity()) >= 0) {
            break;
          }
        } while (recordSet.moveToNext());
      }
    } finally {
      if (recordSet != null) {
        recordSet.close();
      }
    }
    if (quantityInSources.compareTo(pEntity.getItsQuantity()) < 0) {
      throw new ExceptionWithCode(PurchaseInvoice.THERE_IS_NO_GOODS,
        "there_is_no_goods_in_stock");
    }
    BigDecimal quantityToDrawRest = pEntity.getItsQuantity();
    for (T source : sources) {
      @SuppressWarnings("unchecked")
      IFactorySimple<IDrawItemSource> fctDis =
        (IFactorySimple<IDrawItemSource>) this.entitiesFactoriesFatory
         .lazyGet(pAddParam, srvTypeCode.getTypeCodeMap()
          .get(source.getSourceType()));
      IDrawItemSource drawed = fctDis.create(pAddParam);
      String fldIdName = this.srvOrm.getTablesMap()
        .get(drawed.getClass().getSimpleName()).getIdFieldName();
      Method setterId = this.settersRapiHolder
        .getFor(drawed.getClass(), fldIdName);
      setterId.invoke(drawed, source.getSourceId());
      drawed = srvOrm.retrieveEntity(pAddParam, drawed);
      BigDecimal quantityToDraw;
      if (quantityToDrawRest.compareTo(drawed.getTheRest()) < 0) {
        quantityToDraw = quantityToDrawRest;
      } else {
        quantityToDraw = drawed.getTheRest();
      }
      withdrawalFrom(pAddParam, pEntity, drawed, quantityToDraw);
      quantityToDrawRest = quantityToDrawRest.subtract(quantityToDraw);
      if (quantityToDrawRest.doubleValue() == 0) {
        break;
      }
    }
  }
869775
public final void createAccentry(final Map<String, Object> pReqVars,
    final BankStatementLine pBsl, final DateFormat pDateFormat,
      final String pLangDef, final IRequestData pRequestData) throws Exception {
    Account accCash;
    Account corAcc;
    String subcorAcc = null;
    Long subcorAccId = null;
    Integer subcorAccType = null;
    Date itsDate;
    try {
      String accCashStr = pRequestData.getParameter("accCash");
      accCash = new Account();
      accCash.setItsId(accCashStr);
      accCash = getSrvOrm().retrieveEntity(pReqVars, accCash);
      if (accCash == null) {
        throw new Exception("cant_find_account");
      }
      String corAccStr = pRequestData.getParameter("corAcc");
      corAcc = new Account();
      corAcc.setItsId(corAccStr);
      corAcc = getSrvOrm().retrieveEntity(pReqVars, corAcc);
      if (corAcc == null) {
        throw new Exception("cant_find_account");
      }
      if (corAcc.getSubaccType() != null) {
        subcorAcc = pRequestData.getParameter("subcorAcc");
        String subcorAccTypeStr = pRequestData.getParameter("subcorAccType");
        subcorAccType = Integer.parseInt(subcorAccTypeStr);
        String subcorAccIdStr = pRequestData.getParameter("subcorAccId");
        subcorAccId = Long.parseLong(subcorAccIdStr);
      }
      String itsDateStr = pRequestData.getParameter("itsDate");
      itsDate = this.dateTimeNoTzFormatIso8601.parse(itsDateStr);
    } catch (Exception e) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "wrong_paramaters", e);
    }
    EBankEntryResultType resultRecordType = EBankEntryResultType.ACC_ENTRY;
    EBankEntryResultAction resultAction = EBankEntryResultAction.CREATE;
    String resultDescription = null;
    Long resultRecordId = null;
    AccountingEntry accent = new AccountingEntry();
    if (pBsl.getItsAmount().compareTo(BigDecimal.ZERO) > 0) {
      accent.setAccDebit(accCash);
      accent.setSubaccDebit(pBsl.getItsOwner().getBankAccount().getItsName());
      accent.setSubaccDebitId(pBsl.getItsOwner().getBankAccount().getItsId());
      accent.setSubaccDebitType(2002);
      accent.setAccCredit(corAcc);
      accent.setSubaccCredit(subcorAcc);
      accent.setSubaccCreditId(subcorAccId);
      accent.setSubaccCreditType(subcorAccType);
    } else {
      accent.setAccDebit(corAcc);
      accent.setSubaccDebit(subcorAcc);
      accent.setSubaccDebitId(subcorAccId);
      accent.setSubaccDebitType(subcorAccType);
      accent.setAccCredit(accCash);
      accent.setSubaccCredit(pBsl.getItsOwner().getBankAccount().getItsName());
      accent.setSubaccCreditId(pBsl.getItsOwner().getBankAccount().getItsId());
      accent.setSubaccCreditType(2002);
    }
    accent.setSourceType(pBsl.constTypeCode());
    accent.setSourceId(pBsl.getItsId());
    accent.setSourceDatabaseBirth(pBsl.getIdDatabaseBirth());
    accent.setIdDatabaseBirth(pBsl.getIdDatabaseBirth());
    accent.setItsDate(itsDate);
    accent.setDebit(pBsl.getItsAmount().abs());
    accent.setCredit(accent.getDebit());
    accent.setDescription(makeDescrForCreated(pBsl, pDateFormat, pLangDef));
    getSrvOrm().insertEntity(pReqVars, accent);
    accent.setIsNew(false);
    resultRecordId = accent.getItsId();
    resultDescription = makeBslResDescr(resultAction, pDateFormat, accent,
      accent.getItsDate(), pLangDef);
    pBsl.setResultAction(resultAction);
    pBsl.setResultRecordType(resultRecordType);
    pBsl.setResultRecordId(resultRecordId);
    pBsl.setResultDescription(resultDescription);
    getSrvOrm().updateEntity(pReqVars, pBsl);
  }
627463
@Override
  public final void makeOtherEntries(final Map<String, Object> pReqVars,
    final PurchaseInvoice pEntity, final IRequestData pRequestData,
      final boolean pIsNew) throws Exception {
    String actionAdd = pRequestData.getParameter("actionAdd");
    if ("makeAccEntries".equals(actionAdd)) {
      if (pEntity.getReversedId() != null) {
        //reverse none-reversed lines:
        PurchaseInvoiceLine pil = new PurchaseInvoiceLine();
        PurchaseInvoice reversed = new PurchaseInvoice();
        reversed.setItsId(pEntity.getReversedId());
        pil.setItsOwner(reversed);
        List<PurchaseInvoiceLine> reversedLines = getSrvOrm().
          retrieveListForField(pReqVars, pil, "itsOwner");
        String langDef = (String) pReqVars.get("langDef");
        for (PurchaseInvoiceLine reversedLine : reversedLines) {
          if (reversedLine.getReversedId() == null) {
            if (!reversedLine.getItsQuantity()
              .equals(reversedLine.getTheRest())) {
              throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
                "where_is_withdrawals_from_this_source");
            }
            PurchaseInvoiceLine reversingLine = new PurchaseInvoiceLine();
            reversingLine.setIdDatabaseBirth(getSrvOrm().getIdDatabase());
            reversingLine.setReversedId(reversedLine.getItsId());
            reversingLine.setWarehouseSite(reversedLine.getWarehouseSite());
            reversingLine.setInvItem(reversedLine.getInvItem());
            reversingLine.setUnitOfMeasure(reversedLine.getUnitOfMeasure());
            reversingLine.setItsCost(reversedLine.getItsCost());
            reversingLine.setItsQuantity(reversedLine.getItsQuantity()
              .negate());
            reversingLine.setItsTotal(reversedLine.getItsTotal().negate());
            reversingLine.setSubtotal(reversedLine.getSubtotal().negate());
            reversingLine.setTotalTaxes(reversedLine.getTotalTaxes().negate());
            reversingLine.setTaxesDescription(reversedLine
              .getTaxesDescription());
            reversingLine.setForeignPrice(reversedLine.getForeignPrice());
            reversingLine.setForeignSubtotal(reversedLine.getForeignSubtotal()
              .negate());
            reversingLine.setForeignTotalTaxes(reversedLine
              .getForeignTotalTaxes().negate());
            reversingLine.setForeignTotal(reversedLine.getForeignTotal()
              .negate());
            reversingLine.setIsNew(true);
            reversingLine.setItsOwner(pEntity);
            reversingLine.setDescription(getSrvI18n()
              .getMsg("reversed_entry_n", langDef) + reversedLine
                .getIdDatabaseBirth() + "-" + reversedLine.getItsId()); //local
            getSrvOrm().insertEntity(pReqVars, reversingLine);
            reversingLine.setIsNew(false);
            getSrvWarehouseEntry().load(pReqVars, reversingLine,
              reversingLine.getWarehouseSite());
            String descr;
            if (reversedLine.getDescription() == null) {
              descr = "";
            } else {
              descr = reversedLine.getDescription();
            }
            reversedLine.setDescription(descr + " " + getSrvI18n().getMsg(
              "reversing_entry_n", langDef) + reversingLine.getIdDatabaseBirth()
                + "-" + reversingLine.getItsId()); //only local
            reversedLine.setReversedId(reversingLine.getItsId());
            reversedLine.setTheRest(BigDecimal.ZERO);
            getSrvOrm().updateEntity(pReqVars, reversedLine);
            PurchaseInvoiceGoodsTaxLine pigtlt =
              new PurchaseInvoiceGoodsTaxLine();
            pigtlt.setItsOwner(reversedLine);
            List<PurchaseInvoiceGoodsTaxLine> tls = getSrvOrm()
              .retrieveListForField(pReqVars, pigtlt, "itsOwner");
            for (PurchaseInvoiceGoodsTaxLine pigtl : tls) {
              getSrvOrm().deleteEntity(pReqVars, pigtl);
            }
          }
        }
        PurchaseInvoiceServiceLine pisl = new PurchaseInvoiceServiceLine();
        pisl.setItsOwner(reversed);
        List<PurchaseInvoiceServiceLine> revServLines = getSrvOrm().
          retrieveListForField(pReqVars, pisl, "itsOwner");
        for (PurchaseInvoiceServiceLine reversedLine : revServLines) {
          if (reversedLine.getReversedId() == null) {
            PurchaseInvoiceServiceLine reversingLine =
              new PurchaseInvoiceServiceLine();
            reversingLine.setIdDatabaseBirth(getSrvOrm().getIdDatabase());
            reversingLine.setReversedId(reversedLine.getItsId());
            reversingLine.setService(reversedLine.getService());
            reversingLine.setAccExpense(reversedLine.getAccExpense());
            reversingLine.setItsCost(reversedLine.getItsCost().negate());
            reversingLine.setUnitOfMeasure(reversedLine.getUnitOfMeasure());
            reversingLine.setItsCost(reversedLine.getItsCost());
            reversingLine.setItsQuantity(reversedLine.getItsQuantity()
              .negate());
            reversingLine.setItsTotal(reversedLine.getItsTotal().negate());
            reversingLine.setSubtotal(reversedLine.getSubtotal().negate());
            reversingLine.setTotalTaxes(reversedLine.getTotalTaxes().negate());
            reversingLine.setTaxesDescription(reversedLine
              .getTaxesDescription());
            reversingLine.setForeignPrice(reversedLine.getForeignPrice());
            reversingLine.setForeignSubtotal(reversedLine.getForeignSubtotal()
              .negate());
            reversingLine.setForeignTotalTaxes(reversedLine
              .getForeignTotalTaxes().negate());
            reversingLine.setForeignTotal(reversedLine.getForeignTotal()
              .negate());
            reversingLine.setIsNew(true);
            reversingLine.setItsOwner(pEntity);
            getSrvOrm().insertEntity(pReqVars, reversingLine);
            reversingLine.setIsNew(false);
            reversedLine.setReversedId(reversingLine.getItsId());
            getSrvOrm().updateEntity(pReqVars, reversedLine);
            PurchaseInvoiceServiceTaxLine pigtlt =
              new PurchaseInvoiceServiceTaxLine();
            pigtlt.setItsOwner(reversedLine);
            List<PurchaseInvoiceServiceTaxLine> tls = getSrvOrm()
              .retrieveListForField(pReqVars, pigtlt, "itsOwner");
            for (PurchaseInvoiceServiceTaxLine pigtl : tls) {
              getSrvOrm().deleteEntity(pReqVars, pigtl);
            }
          }
        }
        PurchaseInvoiceTaxLine pitl = new PurchaseInvoiceTaxLine();
        pitl.setItsOwner(reversed);
        List<PurchaseInvoiceTaxLine> reversedTaxLines = getSrvOrm().
          retrieveListForField(pReqVars, pitl, "itsOwner");
        for (PurchaseInvoiceTaxLine reversedLine : reversedTaxLines) {
          if (reversedLine.getReversedId() == null) {
            PurchaseInvoiceTaxLine reversingLine = new PurchaseInvoiceTaxLine();
            reversingLine.setIdDatabaseBirth(getSrvOrm().getIdDatabase());
            reversingLine.setReversedId(reversedLine.getItsId());
            reversingLine.setItsTotal(reversedLine.getItsTotal().negate());
            reversingLine.setForeignTotalTaxes(reversedLine
              .getForeignTotalTaxes().negate());
            reversingLine.setTax(reversedLine.getTax());
            reversingLine.setIsNew(true);
            reversingLine.setItsOwner(pEntity);
            getSrvOrm().insertEntity(pReqVars, reversingLine);
            reversingLine.setIsNew(false);
            reversedLine.setReversedId(reversingLine.getItsId());
            getSrvOrm().updateEntity(pReqVars, reversedLine);
          }
        }
      }
      if (pEntity.getPrepaymentTo() != null) {
        if (pEntity.getReversedId() != null) {
          pEntity.getPrepaymentTo().setPurchaseInvoiceId(null);
        } else {
          pEntity.getPrepaymentTo().setPurchaseInvoiceId(pEntity.getItsId());
        }
        getSrvOrm().updateEntity(pReqVars, pEntity.getPrepaymentTo());
      }
    }
  }
629307
@Override
  public final void checkOtherFraudUpdate(final Map<String, Object> pAddParam,
    final GoodsLoss pEntity, final IRequestData pRequestData,
      final GoodsLoss pOldEntity) throws Exception {
    // nothing
  }
343323
@Override
  public final <T> void insertEntity(final Map<String, Object> pAddParam,
    final T pEntity) throws Exception {
    ColumnsValues columnsValues = evalColumnsValues(pAddParam, pEntity);
    long result = getSrvDatabase().executeInsert(pEntity.getClass()
      .getSimpleName().toUpperCase(), columnsValues);
    if (result != 1) {
      String query = getHlpInsertUpdate().evalSqlInsert(pEntity.getClass()
        .getSimpleName().toUpperCase(), columnsValues);
      throw new ExceptionWithCode(ISrvDatabase.ERROR_INSERT_UPDATE,
        "It should be 1 row inserted but it is "
          + result + ", query:\n" + query + ";\n");
    }
    String[] idName = columnsValues.getIdColumnsNames();
    if (idName.length == 1) { // if non-composite PK
      Field fieldId = getUtlReflection()
        .retrieveField(pEntity.getClass(), idName[0]);
      fieldId.setAccessible(true);
      Object idValue = fieldId.get(pEntity);
      if (idValue == null) {
        //It must be an autogenerated Integer or Long ID
        IRecordSet<RS> recordSet = null;
        try {
          String insertedIdName = "INSERTEDID";
          recordSet = getSrvDatabase().retrieveRecords(
            "select SCOPE_IDENTITY() as " + insertedIdName + ";");
          recordSet.moveToFirst();
          if (fieldId.getType() == Long.class) {
            fieldId.set(pEntity, recordSet.getLong(insertedIdName));
          } else if (fieldId.getType() == Integer.class) {
            fieldId.set(pEntity, recordSet.getInteger(insertedIdName));
          } else {
            String msg = "There is no rule to fill ID "
              + fieldId.getName().toUpperCase()
                + " of " + fieldId.getType() + " in "
                  + pEntity;
            throw new ExceptionWithCode(ExceptionWithCode.NOT_YET_IMPLEMENTED,
              msg);
          }
        } finally {
          if (recordSet != null) {
            recordSet.close();
          }
        }
      }
    }
  }
231605
@Override
  public final void makeFirstPrepareForSave(final Map<String, Object> pAddParam,
    final PaymentFrom pEntity,
      final IRequestData pRequestData) throws Exception {
    //BeigeORM refresh:
    pEntity.setAccCash(getSrvOrm()
      .retrieveEntity(pAddParam, pEntity.getAccCash()));
    if (pEntity.getAccCash().getSubaccType() != null
      && pEntity.getSubaccCashId() == null) {
      throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
        "select_subaccount");
    }
    if (pEntity.getSalesInvoice() != null) {
      SalesInvoice salesInvoice = getSrvOrm()
        .retrieveEntity(pAddParam, pEntity.getSalesInvoice());
      if (!salesInvoice.getHasMadeAccEntries()
        || salesInvoice.getReversedId() != null) {
        throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
          "sales_invoice_must_be_accounted");
      }
      pEntity.setSalesInvoice(salesInvoice);
    }
  }
521452
public final void doWork(final HttpServletRequest pReq,
    final HttpServletResponse pResp) throws ServletException, IOException {
    pReq.setCharacterEncoding("UTF-8");
    pResp.setCharacterEncoding("UTF-8");
    try {
      HashMap<String, Object> reqVars = new HashMap<String, Object>();
      HttpRequestData requestData = new HttpRequestData(pReq, pResp);
      requestData.setAttribute("reqVars", reqVars);
      IHandlerRequest hndlI18nRequest = (IHandlerRequest) this
        .factoryAppBeans.lazyGet("hndlI18nRequest");
      hndlI18nRequest.handle(reqVars, requestData);
      String nmRnd = pReq.getParameter("nmRnd");
      if (this.defaultJsp != null && "index".equals(this.defaultJsp)) {
        //TODO extract into handler
        if (pReq.getParameter("logoff") != null) {
          pReq.getSession().invalidate();
        }
        @SuppressWarnings("rawtypes")
        SrvAddTheFirstUser srvAddFiU = (SrvAddTheFirstUser) getServletContext()
          .getAttribute("srvAddTheFirstUser");
        if (srvAddFiU != null && !srvAddFiU.checkIsThereAnyUser()) {
          nmRnd = "addFirstUser";
        }
      }
      if (nmRnd == null) {
        nmRnd = this.defaultJsp;
      }
      if (this.handlerName != null) {
        IHandlerRequest handleRequest = (IHandlerRequest) this
          .factoryAppBeans.lazyGet(this.handlerName);
        handleRequest.handle(reqVars, requestData);
      }
      ISrvI18n srvI18n = (ISrvI18n) this.factoryAppBeans.lazyGet("ISrvI18n");
      UtlJsp utlJsp = (UtlJsp) this.factoryAppBeans.lazyGet("UtlJsp");
      pReq.setAttribute("srvI18n", srvI18n);
      pReq.setAttribute("utlJsp", utlJsp);
      //renderer maybe overridden:
      String nmRnRd = (String) pReq.getAttribute("nmRnd");
      if (nmRnRd != null) {
        nmRnd = nmRnRd;
      }
      //processor can set redirect servlet, e.g. transactional to non-one:
      String srvlRd = (String) pReq.getAttribute("srvlRed");
      if (srvlRd != null) {
        RequestDispatcher rd = getServletContext().getRequestDispatcher(srvlRd);
        rd.forward(pReq, pResp);
      } else {
        String path = dirJsp + nmRnd + ".jsp";
        RequestDispatcher rd = getServletContext().getRequestDispatcher(path);
        rd.include(pReq, pResp);
      }
    } catch (Exception e) {
      if (this.factoryAppBeans != null) {
        ILog logger = null;
        try {
          logger = (ILog) this.factoryAppBeans.lazyGet("ILog");
          logger.error(null, getClass(), "WORK", e);
        } catch (Exception e1) {
          e1.printStackTrace();
          e.printStackTrace();
        }
      } else {
        e.printStackTrace();
      }
      if (e instanceof ExceptionWithCode) {
        pReq.setAttribute("error_code",
          ((ExceptionWithCode) e).getCode());
        pReq.setAttribute("short_message",
          ((ExceptionWithCode) e).getShortMessage());
      } else {
        pReq.setAttribute("error_code",
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
      pReq.setAttribute("javax.servlet.error.status_code",
        HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      pReq.setAttribute("javax.servlet.error.exception", e);
      pReq.setAttribute("javax.servlet.error.request_uri",
        pReq.getRequestURI());
      pReq.setAttribute("javax.servlet.error.servlet_name", this.getClass()
        .getCanonicalName());
      pResp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
282633
public final <T> void prepareColumnValuesForUpdate(
    final ColumnsValues pColumnsValues,
      final T pEntity) throws Exception {
    //remove old version and ID columns:
    pColumnsValues.getLongsMap().remove(ISrvOrm.VERSIONOLD_NAME);
    TableSql tableSql = this.tablesMap.get(pEntity.getClass().getSimpleName());
    for (String idFldNm : tableSql.getIdColumnsNames()) {
      pColumnsValues.remove(idFldNm);
    }
  }