예제 #1
0
/**
 * Resource Assignment Dialog
 *
 * @author Jorg Janke
 * @version $Id: VAssignmentDialog.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $
 *     <p>Zk Port
 * @author Low Heng Sin
 */
public class WAssignmentDialog extends Window implements EventListener {
  /** */
  private static final long serialVersionUID = -1762339564864115852L;

  /**
   * Assignment Dialog.
   *
   * <pre>
   * 		Creates a new assignment oor displays an assignment
   * 		Create new:	(ID == 0)
   * 			check availability & create assignment
   * 			(confirmed when order/incoice/timeExpense is processed)
   * 			alternatively let InfoResource do the assignment
   * 			return ID
   * 		Existing assignment: (ID != 0)
   * 			if confirmed - no change.
   * 			ability to delete or change assignment
   * 			return ID
   * 	</pre>
   *
   * @param mAssignment Assignment
   * @param allowZoom allow to zoom to schedule
   * @param allowDelete allow to delete recorde
   */
  public WAssignmentDialog(
      MResourceAssignment mAssignment, boolean allowZoom, boolean allowDelete) {
    super();
    this.setTitle(Msg.getMsg(Env.getCtx(), "VAssignmentDialog"));
    this.setAttribute("mode", "modal");
    this.setBorder("normal");

    log.config(mAssignment.toString());
    m_mAssignment = mAssignment;
    try {
      init();
      if (!allowZoom) confirmPanel.getButton("Zoom").setVisible(false);
      delete.setVisible(allowDelete);
    } catch (Exception e) {
      log.log(Level.SEVERE, "", e);
    }
    setDisplay(); //	from mAssignment
    //
    AEnv.showWindow(this);
  } //	VAssignmentDialog

  /** Assignment */
  private MResourceAssignment m_mAssignment;
  /** True if setting Value */
  private boolean m_setting = false;
  /** Logger */
  private static CLogger log = CLogger.getCLogger(WAssignmentDialog.class);
  /** Lookup with Resource & UOM */
  private HashMap<KeyNamePair, KeyNamePair> m_lookup = new HashMap<KeyNamePair, KeyNamePair>();

  //
  private Grid mainPanel = new Grid();
  private Label lResource = new Label(Msg.translate(Env.getCtx(), "S_Resource_ID"));
  private Listbox fResource = new Listbox(getResources());
  private Label lDate = new Label(Msg.translate(Env.getCtx(), "DateFrom"));
  private Datebox fDateFrom = new Datebox();
  private Timebox fTimeFrom = new Timebox();
  private Label lQty = new Label(Msg.translate(Env.getCtx(), "Qty"));
  private NumberBox fQty = new NumberBox(true);
  private Label lUOM = new Label();
  private Label lName = new Label(Msg.translate(Env.getCtx(), "Name"));
  private Label lDescription = new Label(Msg.translate(Env.getCtx(), "Description"));
  private Textbox fName = new Textbox();
  private Textbox fDescription = new Textbox();
  private ConfirmPanel confirmPanel =
      new ConfirmPanel(true, false, false, false, false, true /*, true*/);
  private Button delete = confirmPanel.createButton("Delete");
  private boolean m_cancel = false;

  /**
   * Static Init
   *
   * @throws Exception
   */
  private void init() throws Exception {
    fResource.setMold("select");
    fResource.addEventListener(Events.ON_SELECT, this);
    delete.addEventListener(Events.ON_CLICK, this);
    confirmPanel.addComponentsLeft(delete);
    confirmPanel.addActionListener(Events.ON_CLICK, this);
    //
    this.appendChild(mainPanel);
    mainPanel.makeNoStrip();
    mainPanel.setStyle("background-color: transparent");

    Rows rows = new Rows();
    mainPanel.appendChild(rows);
    Row row = new Row();
    row.appendChild(LayoutUtils.makeRightAlign(lResource));
    row.appendChild(fResource);
    row.appendChild(new Label(" "));
    rows.appendChild(row);

    row = new Row();
    row.setSpans("1, 2");
    row.appendChild(LayoutUtils.makeRightAlign(lDate));
    Div div = new Div();
    div.appendChild(fDateFrom);
    div.appendChild(fTimeFrom);
    fTimeFrom.setStyle("margin-left: 5px");
    row.appendChild(div);
    rows.appendChild(row);

    row = new Row();
    row.appendChild(LayoutUtils.makeRightAlign(lQty));
    row.appendChild(fQty);
    row.appendChild(lUOM);
    rows.appendChild(row);

    row = new Row();
    row.setSpans("1, 2");
    row.appendChild(LayoutUtils.makeRightAlign(lName));
    row.appendChild(fName);
    fName.setStyle("width: 100%");
    rows.appendChild(row);

    row = new Row();
    row.setSpans("1, 2");
    row.appendChild(LayoutUtils.makeRightAlign(lDescription));
    row.appendChild(fDescription);
    fDescription.setMultiline(true);
    fDescription.setRows(3);
    fDescription.setStyle("width: 100%");
    rows.appendChild(row);

    row = new Row();
    row.setSpans("3");
    row.appendChild(new Label(" "));
    rows.appendChild(row);

    row = new Row();
    row.setSpans("3");
    row.appendChild(confirmPanel);
    rows.appendChild(row);
    //
  } //	jbInit

  /** Initialize component & values from m_mAssignment */
  private void setDisplay() {
    m_setting = true;

    //	Set Resource
    int S_Resource_ID = m_mAssignment.getS_Resource_ID();
    KeyNamePair[] resources = new KeyNamePair[m_lookup.size()];
    m_lookup.keySet().toArray(resources);
    for (int i = 0; i < resources.length; i++) {
      if (resources[i].getKey() == S_Resource_ID) {
        fResource.setSelectedIndex(i);
        break;
      }
    }
    ListItem listItem = fResource.getSelectedItem();
    KeyNamePair check = new KeyNamePair((Integer) listItem.getValue(), listItem.getLabel());
    if (check == null || check.getKey() != S_Resource_ID) {
      if (m_mAssignment.getS_ResourceAssignment_ID() == 0) // 	new record select first
      fResource.setSelectedItem(fResource.getSelectedItem()); // 	initiates UOM display
      else log.log(Level.SEVERE, "Resource not found ID=" + S_Resource_ID);
    }

    //	Set Date, Qty
    fDateFrom.setValue(m_mAssignment.getAssignDateFrom());
    fTimeFrom.setValue(m_mAssignment.getAssignDateFrom());
    fQty.setValue(m_mAssignment.getQty());

    //	Name, Description
    fName.setValue(m_mAssignment.getName());
    fDescription.setValue(m_mAssignment.getDescription());

    //	Set Editor to R/O if confirmed
    boolean readWrite = true;
    if (m_mAssignment.isConfirmed()) readWrite = false;
    confirmPanel.getButton("Cancel").setVisible(readWrite);
    fResource.setEnabled(readWrite);
    fDateFrom.setReadonly(!readWrite);
    fQty.setEnabled(readWrite);

    m_setting = false;
  } //	dynInit

  /**
   * ************************************************************************ Get Assignment
   *
   * @return Assignment
   */
  public MResourceAssignment getMResourceAssignment() {
    return m_mAssignment;
  } //	getMResourceAssignment

  /**
   * Check availability and insert record
   *
   * @return true if saved/updated
   */
  private boolean cmd_save() {
    log.config("");
    //	Set AssignDateTo
    Calendar date = new GregorianCalendar();
    getDateAndTimeFrom(date);
    Timestamp assignDateFrom = new Timestamp(date.getTimeInMillis());
    BigDecimal qty = fQty.getValue();
    KeyNamePair uom = (KeyNamePair) m_lookup.get(fResource.getSelectedItem());
    int minutes = MUOMConversion.convertToMinutes(Env.getCtx(), uom.getKey(), qty);
    Timestamp assignDateTo = TimeUtil.addMinutess(assignDateFrom, minutes);
    m_mAssignment.setAssignDateTo(assignDateTo);
    //
    //	m_mAssignment.dump();
    return m_mAssignment.save();
  } //	cmdSave

  /**
   * ************************************************************************ Load Resources. called
   * from variable constructor
   *
   * @return Array with resources
   */
  private KeyNamePair[] getResources() {
    if (m_lookup.size() == 0) {
      String sql =
          MRole.getDefault()
              .addAccessSQL(
                  "SELECT r.S_Resource_ID, r.Name, r.IsActive," //	1..3
                      + "uom.C_UOM_ID,uom.UOMSymbol " //	4..5
                      + "FROM S_Resource r, S_ResourceType rt, C_UOM uom "
                      + "WHERE r.S_ResourceType_ID=rt.S_ResourceType_ID AND rt.C_UOM_ID=uom.C_UOM_ID",
                  "r",
                  MRole.SQL_FULLYQUALIFIED,
                  MRole.SQL_RO);
      try {
        PreparedStatement pstmt = DB.prepareStatement(sql, null);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
          StringBuffer sb = new StringBuffer(rs.getString(2));
          if (!"Y".equals(rs.getString(3))) sb.insert(0, '~').append('~'); // 	inactive marker
          //	Key		S_Resource_ID/Name
          KeyNamePair key = new KeyNamePair(rs.getInt(1), sb.toString());
          //	Value	C_UOM_ID/Name
          KeyNamePair value = new KeyNamePair(rs.getInt(4), rs.getString(5).trim());
          m_lookup.put(key, value);
        }
        rs.close();
        pstmt.close();
      } catch (SQLException e) {
        log.log(Level.SEVERE, sql, e);
      }
    }
    //	Convert to Array
    KeyNamePair[] retValue = new KeyNamePair[m_lookup.size()];
    m_lookup.keySet().toArray(retValue);
    Arrays.sort(retValue);
    return retValue;
  } //	getResources

  public void onEvent(Event e) throws Exception {
    if (m_setting) return;
    //	Update Assignment
    ListItem listItem = fResource.getSelectedItem();
    KeyNamePair resource =
        listItem != null
            ? new KeyNamePair((Integer) listItem.getValue(), listItem.getLabel())
            : null;
    if (resource != null) {
      int S_Resource_ID = resource.getKey();
      m_mAssignment.setS_Resource_ID(S_Resource_ID);
    }

    Calendar date = new GregorianCalendar();
    getDateAndTimeFrom(date);

    Timestamp assignDateFrom = new Timestamp(date.getTimeInMillis());
    if (assignDateFrom != null) m_mAssignment.setAssignDateFrom(assignDateFrom);
    if (fQty.getValue() != null) {
      BigDecimal qty = fQty.getValue();
      m_mAssignment.setQty(qty);
    }
    m_mAssignment.setName((String) fName.getValue());
    m_mAssignment.setDescription((String) fDescription.getValue());

    //	Resource - Look up UOM
    if (e.getTarget() == fResource) {
      Object o = m_lookup.get(fResource.getSelectedItem());
      if (o == null) lUOM.setValue(" ? ");
      else lUOM.setValue(o.toString());
    }

    //	Zoom - InfoResource
    else if (e.getTarget().getId().equals("Zoom")) {
      InfoSchedule is = new InfoSchedule(m_mAssignment, true);
      if (is.getMResourceAssignment() != null) {
        m_mAssignment = is.getMResourceAssignment();
        //	setDisplay();
        detach();
      }
      is = null;
    }

    //	cancel - return
    else if (e.getTarget().getId().equals("Cancel")) {
      m_cancel = true;
      detach();
    }

    //	delete - delete and return
    else if (e.getTarget().getId().equals("Delete")) {
      if (m_mAssignment.delete(true)) {
        m_mAssignment = null;
        detach();
      } else FDialog.error(0, this, "ResourceAssignmentNotDeleted");
    }

    //	OK - Save
    else if (e.getTarget().getId().equals("Ok")) {
      if (cmd_save()) detach();
    }
  }

  private void getDateAndTimeFrom(Calendar date) {
    Date dateFrom = fDateFrom.getValue();
    Date timeFrom = fTimeFrom.getValue();
    date.setTime(dateFrom);
    Calendar time = new GregorianCalendar();
    time.setTime(timeFrom);
    date.set(Calendar.HOUR, time.get(Calendar.HOUR));
    date.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
  }

  public boolean isCancelled() {
    return m_cancel;
  }
} //	VAssignmentDialog
예제 #2
0
/**
 * Create Manual Payments From (AP) Invoices or (AR) Credit Memos. Allows user to select Invoices
 * for payment. When Processed, PaySelection is created and optionally posted/generated and printed
 *
 * @author Jorg Janke
 * @version $Id: VPaySelect.java,v 1.3 2006/07/30 00:51:28 jjanke Exp $
 */
public class WPaySelect extends PaySelect
    implements IFormController, EventListener, WTableModelListener, ASyncProcess {
  /** @todo withholding */

  /** */
  private static final long serialVersionUID = -6031404894392912610L;

  private CustomForm form = new CustomForm();

  //
  private Panel mainPanel = new Panel();
  private Borderlayout mainLayout = new Borderlayout();
  private Panel parameterPanel = new Panel();
  private Label labelBankAccount = new Label();
  private Listbox fieldBankAccount = ListboxFactory.newDropdownListbox();
  private Grid parameterLayout = GridFactory.newGridLayout();
  private Label labelBankBalance = new Label();
  private Label labelCurrency = new Label();
  private Label labelBalance = new Label();
  private Checkbox onlyDue = new Checkbox();
  private Label labelBPartner = new Label();
  private Listbox fieldBPartner = ListboxFactory.newDropdownListbox();
  private Label dataStatus = new Label();
  private WListbox miniTable = ListboxFactory.newDataTable();
  private ConfirmPanel commandPanel =
      new ConfirmPanel(true, false, false, false, false, false, false);
  private Button bCancel = commandPanel.getButton(ConfirmPanel.A_CANCEL);
  private Button bGenerate = commandPanel.createButton(ConfirmPanel.A_PROCESS);
  private Button bRefresh = commandPanel.createButton(ConfirmPanel.A_REFRESH);
  private Label labelPayDate = new Label();
  private WDateEditor fieldPayDate = new WDateEditor();
  private Label labelPaymentRule = new Label();
  private Listbox fieldPaymentRule = ListboxFactory.newDropdownListbox();
  private Label labelDtype = new Label();
  private Listbox fieldDtype = ListboxFactory.newDropdownListbox();
  private Panel southPanel;

  @SuppressWarnings("unused")
  private ProcessInfo m_pi;

  private boolean m_isLock;

  /** Initialize Panel */
  public WPaySelect() {
    try {
      zkInit();
      dynInit();

      loadBankInfo();
      southPanel.appendChild(new Separator());
      southPanel.appendChild(commandPanel);
    } catch (Exception e) {
      log.log(Level.SEVERE, "", e);
    }
  } //	init

  /**
   * Static Init
   *
   * @throws Exception
   */
  private void zkInit() throws Exception {
    //
    form.appendChild(mainPanel);
    mainPanel.appendChild(mainLayout);
    mainPanel.setStyle("width: 100%; height: 100%; padding: 0; margin: 0");
    mainLayout.setHeight("100%");
    mainLayout.setWidth("99%");
    parameterPanel.appendChild(parameterLayout);
    //
    labelBankAccount.setText(Msg.translate(Env.getCtx(), "C_BankAccount_ID"));
    fieldBankAccount.addActionListener(this);
    labelBPartner.setText(Msg.translate(Env.getCtx(), "C_BPartner_ID"));
    fieldBPartner.addActionListener(this);
    bRefresh.addActionListener(this);
    labelPayDate.setText(Msg.translate(Env.getCtx(), "PayDate"));
    labelPaymentRule.setText(Msg.translate(Env.getCtx(), "PaymentRule"));
    fieldPaymentRule.addActionListener(this);
    labelDtype.setText(Msg.translate(Env.getCtx(), "C_DocType_ID"));
    fieldDtype.addActionListener(this);
    //
    labelBankBalance.setText(Msg.translate(Env.getCtx(), "CurrentBalance"));
    labelBalance.setText("0");
    onlyDue.setText(Msg.getMsg(Env.getCtx(), "OnlyDue"));
    dataStatus.setText(" ");
    dataStatus.setPre(true);
    //
    bGenerate.addActionListener(this);
    bCancel.addActionListener(this);
    //
    North north = new North();
    north.setStyle("border: none");
    mainLayout.appendChild(north);
    north.appendChild(parameterPanel);

    Rows rows = parameterLayout.newRows();
    Row row = rows.newRow();
    row.appendChild(labelBankAccount.rightAlign());
    row.appendChild(fieldBankAccount);
    row.appendChild(labelBankBalance.rightAlign());
    Panel balancePanel = new Panel();
    balancePanel.appendChild(labelCurrency);
    balancePanel.appendChild(labelBalance);
    row.appendChild(balancePanel);
    row.appendChild(new Space());

    row = rows.newRow();
    row.appendChild(labelBPartner.rightAlign());
    row.appendChild(fieldBPartner);
    row.appendChild(new Space());
    row.appendChild(onlyDue);
    row.appendChild(new Space());

    row = rows.newRow();
    row.appendChild(labelDtype.rightAlign());
    row.appendChild(fieldDtype);
    row.appendChild(new Space());
    row.appendChild(new Space());
    row.appendChild(new Space());

    row = rows.newRow();
    row.appendChild(labelPayDate.rightAlign());
    row.appendChild(fieldPayDate.getComponent());
    row.appendChild(labelPaymentRule.rightAlign());
    row.appendChild(fieldPaymentRule);
    row.appendChild(bRefresh);

    South south = new South();
    south.setStyle("border: none");
    mainLayout.appendChild(south);
    southPanel = new Panel();
    southPanel.appendChild(dataStatus);
    south.appendChild(southPanel);
    Center center = new Center();
    mainLayout.appendChild(center);
    center.appendChild(miniTable);
    //
    commandPanel.addButton(bGenerate);
    commandPanel.getButton(ConfirmPanel.A_OK).setVisible(false);
  } //  jbInit

  /** Dynamic Init. - Load Bank Info - Load BPartner - Init Table */
  private void dynInit() {
    ArrayList<BankInfo> bankAccountData = getBankAccountData();
    for (BankInfo bi : bankAccountData) fieldBankAccount.appendItem(bi.toString(), bi);

    if (fieldBankAccount.getItemCount() == 0) FDialog.error(m_WindowNo, form, "VPaySelectNoBank");
    else fieldBankAccount.setSelectedIndex(0);

    ArrayList<KeyNamePair> bpartnerData = getBPartnerData();
    for (KeyNamePair pp : bpartnerData) fieldBPartner.appendItem(pp.getName(), pp);
    fieldBPartner.setSelectedIndex(0);

    ArrayList<KeyNamePair> docTypeData = getDocTypeData();
    for (KeyNamePair pp : docTypeData) fieldDtype.appendItem(pp.getName(), pp);

    prepareTable(miniTable);

    miniTable.getModel().addTableModelListener(this);
    //
    fieldPayDate.setMandatory(true);
    fieldPayDate.setValue(new Timestamp(System.currentTimeMillis()));
  } //  dynInit

  /** Load Bank Info - Load Info from Bank Account and valid Documents (PaymentRule) */
  private void loadBankInfo() {
    BankInfo bi = (BankInfo) fieldBankAccount.getSelectedItem().getValue();
    if (bi == null) return;
    labelCurrency.setText(bi.Currency);
    labelBalance.setText(m_format.format(bi.Balance));

    //  PaymentRule
    fieldPaymentRule.removeAllItems();

    ArrayList<ValueNamePair> paymentRuleData = getPaymentRuleData(bi);
    for (ValueNamePair vp : paymentRuleData) fieldPaymentRule.appendItem(vp.getName(), vp);
    fieldPaymentRule.setSelectedIndex(0);
  } //  loadBankInfo

  /** Query and create TableInfo */
  private void loadTableInfo() {
    Timestamp payDate = (Timestamp) fieldPayDate.getValue();
    miniTable.setColorCompare(payDate);
    log.config("PayDate=" + payDate);

    BankInfo bi = (BankInfo) fieldBankAccount.getSelectedItem().getValue();

    ValueNamePair paymentRule = (ValueNamePair) fieldPaymentRule.getSelectedItem().getValue();
    KeyNamePair bpartner = (KeyNamePair) fieldBPartner.getSelectedItem().getValue();
    KeyNamePair docType = (KeyNamePair) fieldDtype.getSelectedItem().getValue();

    loadTableInfo(bi, payDate, paymentRule, onlyDue.isSelected(), bpartner, docType, miniTable);

    calculateSelection();
  } //  loadTableInfo

  /** Dispose */
  public void dispose() {
    SessionManager.getAppDesktop().closeActiveWindow();
  } //	dispose

  /**
   * ************************************************************************ ActionListener
   *
   * @param e event
   */
  public void onEvent(Event e) {
    //  Update Bank Info
    if (e.getTarget() == fieldBankAccount) loadBankInfo();

    //  Generate PaySelection
    else if (e.getTarget() == bGenerate) {
      generatePaySelect();
    } else if (e.getTarget() == bCancel) dispose();

    //  Update Open Invoices
    else if (e.getTarget() == fieldBPartner
        || e.getTarget() == bRefresh
        || e.getTarget() == fieldDtype) loadTableInfo();
  } //  actionPerformed

  /**
   * Table Model Listener
   *
   * @param e event
   */
  public void tableChanged(WTableModelEvent e) {
    if (e.getColumn() == 0) calculateSelection();
  } //  valueChanged

  /** Calculate selected rows. - add up selected rows */
  public void calculateSelection() {
    dataStatus.setText(calculateSelection(miniTable));
    //
    bGenerate.setEnabled(m_noSelected != 0);
  } //  calculateSelection

  /** Generate PaySelection */
  private void generatePaySelect() {
    if (miniTable.getRowCount() == 0) return;
    miniTable.setSelectedIndices(new int[] {0});
    calculateSelection();
    if (m_noSelected == 0) return;

    String msg =
        generatePaySelect(
            miniTable,
            (ValueNamePair) fieldPaymentRule.getSelectedItem().getValue(),
            new Timestamp(fieldPayDate.getComponent().getValue().getTime()),
            (BankInfo) fieldBankAccount.getSelectedItem().getValue());

    if (msg != null && msg.length() > 0) {
      FDialog.error(m_WindowNo, form, "SaveError", msg);
      return;
    }

    //  Ask to Post it
    if (!FDialog.ask(m_WindowNo, form, "VPaySelectGenerate?", "(" + m_ps.getName() + ")")) return;

    //  Prepare Process
    int AD_Proces_ID = 155; // 	C_PaySelection_CreatePayment

    //	Execute Process
    ProcessModalDialog dialog =
        new ProcessModalDialog(
            this,
            m_WindowNo,
            AD_Proces_ID,
            X_C_PaySelection.Table_ID,
            m_ps.getC_PaySelection_ID(),
            false);
    if (dialog.isValid()) {
      try {
        dialog.setWidth("500px");
        dialog.setVisible(true);
        dialog.setPage(form.getPage());
        dialog.doModal();
      } catch (SuspendNotAllowedException e) {
        log.log(Level.SEVERE, e.getLocalizedMessage(), e);
      } catch (InterruptedException e) {
        log.log(Level.SEVERE, e.getLocalizedMessage(), e);
      }
    }
  } //  generatePaySelect

  /** Lock User Interface Called from the Worker before processing */
  public void lockUI(ProcessInfo pi) {
    if (m_isLock) return;
    m_isLock = true;
    Clients.showBusy(null, true);
  } //  lockUI

  /** Unlock User Interface. Called from the Worker when processing is done */
  public void unlockUI(ProcessInfo pi) {
    if (!m_isLock) return;
    m_isLock = false;
    m_pi = pi;
    Clients.showBusy(null, false);

    // TODO: The response returned is always Cancel
    //		if (!FDialog.ask(0, form, "VPaySelectPrint?", "(" + m_pi.getSummary() + ")"))
    //		{
    //			dispose();
    //			return;
    //		}

    this.dispose();

    //  Start PayPrint
    int AD_Form_ID = 106; // 	Payment Print/Export
    ADForm form = SessionManager.getAppDesktop().openForm(AD_Form_ID);
    if (m_ps != null) {
      WPayPrint pp = (WPayPrint) form.getICustomForm();
      pp.setPaySelection(m_ps.getC_PaySelection_ID());
    }
  }

  public void executeASync(ProcessInfo pi) {}

  public boolean isUILocked() {
    return m_isLock;
  }

  public ADForm getForm() {
    return form;
  }
} //  VPaySelect