Search in sources :

Example 6 with MAsset

use of org.compiere.model.MAsset in project adempiere by adempiere.

the class ImportFixedAsset method doIt.

//	prepare
/**
	 *  Perrform process.
	 *  @return Message
	 *  @throws Exception
	 */
protected String doIt() throws java.lang.Exception {
    StringBuffer sql = null;
    int no = 0;
    if (p_AD_Client_ID == 0)
        p_AD_Client_ID = Env.getAD_Client_ID(getCtx());
    String sqlCheck = " AND AD_Client_ID=" + p_AD_Client_ID;
    //	Delete Old Imported
    if (p_DeleteOldImported) {
        sql = new StringBuffer("DELETE " + X_I_FixedAsset.Table_Name + " WHERE I_IsImported='Y'").append(sqlCheck);
        no = DB.executeUpdateEx(sql.toString(), get_TrxName());
        log.fine("Delete Old Imported =" + no);
    }
    //	Set Client, Org, IsActive, Created/Updated
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " " + "SET AD_Client_ID = COALESCE (AD_Client_ID,").append(p_AD_Client_ID).append(")," + " AD_Org_ID = COALESCE (AD_Org_ID,").append(p_AD_Org_ID).append(")," + " IsActive = COALESCE (IsActive, 'Y')," + " Created = COALESCE (Created, SysDate)," + " CreatedBy = COALESCE (CreatedBy, 0)," + " Updated = COALESCE (Updated, SysDate)," + " UpdatedBy = COALESCE (UpdatedBy, 0)," + " I_ErrorMsg = ' '," + " I_IsImported = 'N' " + "WHERE I_IsImported<>'Y' OR I_IsImported IS NULL");
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    log.info("Reset=" + no);
    //Goodwill
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET AD_Org_ID=(SELECT MAX(AD_Org_ID) FROM AD_Org org" + " WHERE ifa.OrgValue=org.Value AND org.IsSummary='N' AND org.AD_Client_ID=ifa.AD_Client_ID) " + "WHERE (AD_Org_ID IS NULL OR AD_Org_ID=0) AND OrgValue IS NOT NULL" + " AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    log.fine("Set Organization from Value=" + no);
    //end Goodwill
    // Check if Org is Null or 0
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Org, '" + "WHERE (AD_Org_ID IS NULL OR AD_Org_ID=0" + " OR EXISTS (SELECT * FROM AD_Org oo WHERE ifa.AD_Org_ID=oo.AD_Org_ID AND (oo.IsSummary='Y' OR oo.IsActive='N')))" + " AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    if (no != 0)
        log.warning("Invalid Org=" + no);
    // Check if Name is Null
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Name Is Mandatory, '" + "WHERE Name IS NULL AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    if (no != 0)
        log.warning("Invalid Name=" + no);
    // Asset Group From Value
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET A_Asset_Group_ID=(SELECT MAX(A_Asset_Group_ID) FROM A_Asset_Group t" + " WHERE ifa.A_Asset_Group_Value=t.Name AND ifa.AD_Client_ID=t.AD_Client_ID) " + "WHERE A_Asset_Group_ID IS NULL AND A_Asset_Group_Value IS NOT NULL" + " AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    log.fine("Set Asset Group from Value=" + no);
    // Check if Asset Group Have Asset Group Acct Record
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Asset Group Doesnt Have Asset Group Acct Record, ' " + //@win change to AND from OR
    "WHERE A_Asset_Group_ID IS NOT NULL AND A_Asset_Group_ID>0 " + //@win change to AND from OR
    "AND NOT EXISTS (SELECT 1 FROM A_Asset_Group_Acct aga WHERE ifa.A_Asset_Group_ID=aga.A_Asset_Group_ID) " + "AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    if (no != 0)
        log.warning("Invalid Asset Group=" + no);
    // Asset Type From Value
    /* commented by @win
		sql = new StringBuffer ("UPDATE "+MIFixedAsset.Table_Name+" ifa "
			  + "SET A_Asset_Type_ID=(SELECT MAX(A_Asset_Type_ID) FROM A_Asset_Type t"
			  + " WHERE ifa.A_Asset_Type_Value=t.Value AND ifa.AD_Client_ID=t.AD_Client_ID) "
			  + "WHERE A_Asset_Type_ID IS NULL AND A_Asset_Type_Value IS NOT NULL"
			  + " AND I_IsImported<>'Y'").append (sqlCheck);
		no = DB.executeUpdate(sql.toString(), get_TrxName());
		log.fine("Set Asset Type from Value=" + no);
		*/
    // BP From Value
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET C_BPartnerSR_ID=(SELECT MAX(C_BPartner_ID) FROM C_BPartner t" + " WHERE ifa.BPartner_Value=t.Value AND ifa.AD_Client_ID=t.AD_Client_ID) " + "WHERE C_BPartnerSR_ID IS NULL AND BPartner_Value IS NOT NULL" + " AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    log.fine("Set BP from Value=" + no);
    // City From Value
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET C_City_ID=(SELECT MAX(C_City_ID) FROM C_City t" + " WHERE ifa.C_City_Value=t.Name AND ifa.AD_Client_ID=t.AD_Client_ID) " + "WHERE C_City_ID IS NULL AND C_City_Value IS NOT NULL" + " AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    log.fine("Set City from Value=" + no);
    // Product 
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET M_Product_ID=(SELECT MAX(M_Product_ID) FROM M_Product t" + " WHERE ifa.ProductValue=t.Value AND ifa.AD_Client_ID=t.AD_Client_ID) " + "WHERE M_Product_ID IS NULL AND ProductValue IS NOT NULL" + " AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    log.fine("Set Product from Value=" + no);
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Product, ' " + "WHERE M_Product_ID IS NULL AND ProductValue IS NOT NULL" + " AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    if (no != 0)
        log.warning("Invalid Product=" + no);
    // Check if Product using Product Category has A Asset Category Set
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Product Using Product Category Without Asset Group Defined, ' " + "WHERE EXISTS (SELECT 1 FROM M_Product p " + "JOIN M_Product_Category pc ON p.M_Product_Category_ID=pc.M_Product_Category_ID " + "WHERE ifa.M_Product_ID=p.M_Product_ID " + "AND (pc.A_Asset_Group_ID=0 OR pc.A_Asset_Group_ID IS NULL)) " + "AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    if (no != 0)
        log.warning("Invalid Product Category=" + no);
    // Locator From Value
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " ifa " + "SET M_Locator_ID=(SELECT MAX(M_Locator_ID) FROM M_Locator t" + " WHERE ifa.LocatorValue=t.Value AND ifa.AD_Client_ID=t.AD_Client_ID) " + "WHERE M_Locator_ID IS NULL AND LocatorValue IS NOT NULL" + " AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    log.fine("Set Locator from Value=" + no);
    //Goodwill
    //Check current period, 0 means the asset is fully depreciated
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Current Period, ' " + "WHERE a_current_period < 0 OR a_current_period > uselifemonths" + " AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    if (no != 0)
        log.warning("Invalid Current Period=" + no);
    //Asset cost must not be null, 0, or negative numbers
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg ||'ERR=Invalid Asset Cost, ' " + "WHERE a_asset_cost < 1 AND I_IsImported<>'Y'").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    if (no != 0)
        log.warning("Invalid Asset Cost=" + no);
    double toleranceAmt = MSysConfig.getDoubleValue("TOLERANCE_AMT", 1, 0, 0);
    sql = new StringBuffer("UPDATE " + MIFixedAsset.Table_Name + " " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid Accumulated Depreciation, ' " + "WHERE ABS(((a_asset_cost / uselifemonths) * (a_current_period - 1)) - a_accumulated_depr) > " + BigDecimal.valueOf(toleranceAmt) + //Goodwill - no toleranceAmt check on fully depreciated asset (current period = 0)
    " AND I_IsImported<>'Y' AND a_current_period <> 0").append(sqlCheck);
    no = DB.executeUpdate(sql.toString(), get_TrxName());
    if (no != 0)
        log.warning("Invalid Accumulated Depreciation=" + no);
    if (p_IsValidateOnly)
        return "Data Was Validated";
    int cnt_ok = 0;
    int cnt_err = 0;
    String whereClause = "NVL(I_IsImported,'N')='N'" + sqlCheck;
    POResultSet<X_I_FixedAsset> rs = new Query(getCtx(), X_I_FixedAsset.Table_Name, whereClause, get_TrxName()).scroll();
    try {
        while (rs.hasNext()) {
            X_I_FixedAsset xfa = rs.next();
            MIFixedAsset ifa = new MIFixedAsset(getCtx(), xfa.getI_FixedAsset_ID(), get_TrxName());
            try {
                MAssetAddition assetAdd = MAssetAddition.createAsset(ifa);
                if (assetAdd == null) {
                    ifa.setI_ErrorMsg("Failed Create Assets");
                    cnt_err++;
                    assetAdd = null;
                    continue;
                }
                //	assetAdd.getA_Asset().setA_Asset_Group_ID(p_A_Asset_Group_ID);
                if (p_DateAcct != null)
                    assetAdd.setDateAcct(p_DateAcct);
                assetAdd.saveEx();
                //Process Asset Addition Based on Document Action
                if (!assetAdd.processIt(ifa.getDocAction())) {
                    ifa.setI_ErrorMsg("Failed Process Asset Addition");
                    cnt_err++;
                    assetAdd = null;
                    continue;
                }
                assetAdd.saveEx();
                //Goodwill - Set asset properties is imported on fully depreciated status
                if (ifa.getA_Current_Period() == 0) {
                    MAsset asset = new MAsset(getCtx(), assetAdd.getA_Asset_ID(), get_TrxName());
                    asset.setUseLifeYears(0);
                    asset.setUseLifeMonths(0);
                    asset.setLifeUseUnits(0);
                    asset.setUseUnits(0);
                    asset.saveEx();
                }
                //Goodwill - End set
                ifa.setI_IsImported(true);
                ifa.setI_ErrorMsg(null);
                ifa.setA_Asset_ID(assetAdd.getA_Asset_ID());
                ifa.setProcessed(true);
                ifa.saveEx();
                cnt_ok++;
            } catch (Exception e) {
                ifa.setI_ErrorMsg(e.getLocalizedMessage());
                cnt_err++;
                ifa.saveEx();
            }
        }
    } finally {
        DB.close(rs);
        rs = null;
        // Goodwill
        //	Set Error to indicator to not imported
        sql = new StringBuffer("UPDATE I_FixedAsset " + "SET I_IsImported='N', Updated=SysDate " + "WHERE I_IsImported<>'Y'").append(sqlCheck);
        no = DB.executeUpdate(sql.toString(), get_TrxName());
        addLog(0, null, new BigDecimal(no), "@Errors@");
        addLog(0, null, new BigDecimal(cnt_ok), "@A_Asset_ID@: @Inserted@");
        addLog(0, null, new BigDecimal(cnt_err), "@A_Asset_ID@: @Failed@");
    }
    return "";
}
Also used : MAssetAddition(org.compiere.model.MAssetAddition) X_I_FixedAsset(org.compiere.model.X_I_FixedAsset) Query(org.compiere.model.Query) MIFixedAsset(org.compiere.model.MIFixedAsset) MAsset(org.compiere.model.MAsset) BigDecimal(java.math.BigDecimal)

Example 7 with MAsset

use of org.compiere.model.MAsset in project adempiere by adempiere.

the class AssetServlet method streamAsset.

//	doPost
/**
	 * 	Stream asset
	 * 	@param request request
	 * 	@param response response
	 * 	@return "" or error message
	 */
protected String streamAsset(HttpServletRequest request, HttpServletResponse response) {
    //	Get Asset ID
    int A_Asset_ID = WebUtil.getParameterAsInt(request, "Asset_ID");
    if (A_Asset_ID == 0) {
        log.fine("No ID)");
        return "No Asset ID";
    }
    byte[] assetInfo = String.valueOf(A_Asset_ID).getBytes();
    //	Get Asset
    Properties ctx = JSPEnv.getCtx(request);
    HttpSession session = request.getSession(true);
    WebEnv.dump(request);
    MAsset asset = new MAsset(ctx, A_Asset_ID, null);
    if (asset.getA_Asset_ID() != A_Asset_ID) {
        log.fine("Asset not found - ID=" + A_Asset_ID);
        return "Asset not found";
    }
    //	Get WebUser & Compare with invoice
    WebUser wu = (WebUser) session.getAttribute(WebUser.NAME);
    if (wu.getC_BPartner_ID() != asset.getC_BPartner_ID()) {
        log.warning("A_Asset_ID=" + A_Asset_ID + " - BP_Invoice=" + asset.getC_BPartner_ID() + " <> BP_User=" + wu.getC_BPartner_ID());
        return "Your asset not found";
    }
    if (!asset.isDownloadable() || wu.isCreditStopHold() || !wu.isEMailVerified())
        return "Asset not downloadable";
    //	Name & URL
    String pd = WebUtil.getParameter(request, "PD");
    String dl_name = null;
    String dl_url = null;
    InputStream in = null;
    int M_ProductDownload_ID = 0;
    if (pd != null && pd.length() > 0) {
        MProductDownload[] pdls = asset.getProductDownloads();
        if (pdls != null) {
            for (int i = 0; i < pdls.length; i++) {
                if (pdls[i].getDownloadURL().indexOf(pd) != -1) {
                    M_ProductDownload_ID = pdls[i].getM_ProductDownload_ID();
                    dl_name = pd;
                    dl_url = pdls[i].getDownloadURL();
                    in = pdls[i].getDownloadStream(ctx.getProperty(WebSessionCtx.CTX_DOCUMENT_DIR));
                    break;
                }
            }
        }
    }
    log.fine(dl_name + " - " + dl_url);
    if (dl_name == null || dl_url == null || in == null)
        return "@NotFound@ @A_Asset_ID@: " + pd;
    /**
		Download SupportContract.pdf for Jorg Janke - jjanke@adempiere.org
		Version = 120 - Lot = . - SerNo = .
		Guarantee Date = 5/30/05
		Thank you for using Adempiere Customer Asset Management
		**/
    String lot = asset.getLot();
    if (lot == null || lot.length() == 0)
        lot = ".";
    String ser = asset.getSerNo();
    if (ser == null || ser.length() == 0)
        ser = ".";
    Object[] args = new Object[] { dl_name, wu.getName() + " - " + wu.getEmail(), asset.getVersionNo(), lot, ser, asset.getGuaranteeDate() };
    String readme = Msg.getMsg(ctx, "AssetDeliveryTemplate", args);
    //	Send File
    MAssetDelivery ad = confirmDelivery(asset, request, wu.getAD_User_ID());
    if (M_ProductDownload_ID != 0)
        ad.setM_ProductDownload_ID(M_ProductDownload_ID);
    ad.setDescription(dl_name);
    //
    float speed = 0;
    try {
        response.setContentType("application/zip");
        response.setHeader("Content-Location", "asset.zip");
        //	response.setContentLength(length);
        //	2k Buffer
        int bufferSize = 2048;
        response.setBufferSize(bufferSize);
        //
        log.fine(in + ", available=" + in.available());
        long time = System.currentTimeMillis();
        //	Zip Output Stream
        ServletOutputStream out = response.getOutputStream();
        //	Servlet out
        ZipOutputStream zip = new ZipOutputStream(out);
        zip.setMethod(ZipOutputStream.DEFLATED);
        zip.setLevel(Deflater.BEST_COMPRESSION);
        zip.setComment(readme);
        //	Readme File
        ZipEntry entry = new ZipEntry("readme.txt");
        entry.setExtra(assetInfo);
        zip.putNextEntry(entry);
        zip.write(readme.getBytes(), 0, readme.length());
        zip.closeEntry();
        //	Payload
        entry = new ZipEntry(dl_name);
        entry.setExtra(assetInfo);
        zip.putNextEntry(entry);
        byte[] buffer = new byte[bufferSize];
        int count = 0;
        int totalSize = 0;
        do {
            //	read delivery
            count = in.read(buffer, 0, bufferSize);
            if (count > 0) {
                totalSize += count;
                //	write zip
                zip.write(buffer, 0, count);
            }
        } while (count != -1);
        zip.closeEntry();
        //	Fini
        zip.finish();
        zip.close();
        in.close();
        time = System.currentTimeMillis() - time;
        speed = ((float) totalSize / 1024) / ((float) time / 1000);
        String msg = (totalSize / 1024) + "kB - " + time + " ms - " + speed + " kB/sec";
        log.fine(msg);
        //	Delivery Record
        ad.setDeliveryConfirmation(msg);
        ad.saveEx();
        asset.saveEx();
    } catch (IOException ex) {
        String msg = ex.getMessage();
        if (msg == null || msg.length() == 0)
            msg = ex.toString();
        log.warning(msg);
        //	Delivery Record
        try {
            if (msg.length() > 120)
                msg = msg.substring(0, 119);
            ad.setDeliveryConfirmation(msg);
            ad.save();
        //	asset.saveEx();	not delivered
        } catch (Exception ex1) {
            log.log(Level.SEVERE, "2 - " + ex);
        }
        //	nned to differentiate error message as response committed
        return "** Streaming error; Please Retry";
    }
    //
    return null;
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) HttpSession(javax.servlet.http.HttpSession) InputStream(java.io.InputStream) MProductDownload(org.compiere.model.MProductDownload) ZipEntry(java.util.zip.ZipEntry) IOException(java.io.IOException) Properties(java.util.Properties) MAsset(org.compiere.model.MAsset) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) ZipOutputStream(java.util.zip.ZipOutputStream) MAssetDelivery(org.compiere.model.MAssetDelivery) WebUser(org.compiere.util.WebUser)

Aggregations

MAsset (org.compiere.model.MAsset)7 MAssetDelivery (org.compiere.model.MAssetDelivery)3 MMailText (org.compiere.model.MMailText)2 MProductDownload (org.compiere.model.MProductDownload)2 MUser (org.compiere.model.MUser)2 MUserMail (org.compiere.model.MUserMail)2 EMail (org.compiere.util.EMail)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 BigDecimal (java.math.BigDecimal)1 URI (java.net.URI)1 Timestamp (java.sql.Timestamp)1 Properties (java.util.Properties)1 ZipEntry (java.util.zip.ZipEntry)1 ZipOutputStream (java.util.zip.ZipOutputStream)1 ServletException (javax.servlet.ServletException)1 ServletOutputStream (javax.servlet.ServletOutputStream)1 HttpSession (javax.servlet.http.HttpSession)1 I_M_InOut (org.compiere.model.I_M_InOut)1 MAssetAddition (org.compiere.model.MAssetAddition)1