I'm trying to filter an eZPublish fetch.
I've got a class which has an object relationS attribute. My filter allows to fetch objects of this class filtered by the object relations attribute.
I've started using the Enhanced Object Relations Filtering extension (http://projects.ez.no/index.php/enhanced_object_relation_filter), but this one only works with "AND" conditions and I want "OR".
I was able to edit the file to add the "OR" logic and this is what I got:
<?php
class EORExtendedFilter
{
function CreateSqlParts( $params )
{
$db =& eZDB::instance();
$tables = array();
$joins = array();
// foreach filtered attribute, we add a join the relation table and filter
// on the attribute ID + object ID
foreach( $params as $param )
{
if ( !is_array( $param ) )
continue;
if ( !is_numeric( $param[0] ) )
{
$classAttributeId = eZContentObjectTreeNode::classAttributeIDByIdentifier( $param[0] );
}
else
{
$classAttributeId = $param[0];
}
// multiple objects ids
if ( is_array($param[1]) )
{
foreach( $param[1] as $objectId )
{
$join = array(); // 'OR' logic
if ( is_numeric( $objectId ) )
{
$tableName = 'eor_link_' . $objectId;
$tables[] = 'ezcontentobject_link ' . $tableName;
$join[] = $tableName . '.from_contentobject_id = ezcontentobject.id';
$join[] = $tableName . '.from_contentobject_version = ezcontentobject.current_version';
$join[] = $tableName . '.contentclassattribute_id = ' . $classAttributeId;
$join[] = $tableName . '.to_contentobject_id = ' . $objectId;
}
// 'OR' logic
$joins[] = $join;
}
}
// single object id
else
{
$objectId = $param[1];
$tableName = 'eor_link_' . $objectId;
$tables[] = 'ezcontentobject_link ' . $tableName;
$joins[] = $tableName . '.from_contentobject_id = ezcontentobject.id';
$joins[] = $tableName . '.from_contentobject_version = ezcontentobject.current_version';
$joins[] = $tableName . '.contentclassattribute_id = ' . $classAttributeId;
$joins[] = $tableName . '.to_contentobject_id = ' . $objectId;
}
}
if ( !count( $tables ) or !count( $joins ) )
{
$tables = $joins = '';
}
else
{
$tables = "\n, " . implode( "\n, ", $tables );
// 'OR' logic
if ( is_array($param[1]) )
{
$andClauses = array();
foreach ($joins as $attr)
{
$andClauses[] = implode( " AND\n ", $attr );
}
$joins = implode( " OR\n ", $andClauses ) . " AND\n ";
}
else
{
$joins = implode( " AND\n ", $joins ) . " AND\n ";
}
}
return array( 'tables' => $tables, 'joins' => $joins );
}
}
This extended attribute filter produces this string :
eor_link_126.from_contentobject_id = ezcontentobject.id AND eor_link_126.from_contentobject_version = ezcontentobject.current_version AND eor_link_126.contentclassattribute_id = 537 AND eor_link_126.to_contentobject_id = 126 OR (eor_link_127.from_contentobject_id = ezcontentobject.id AND eor_link_127.from_contentobject_version = ezcontentobject.current_version AND eor_link_127.contentclassattribute_id = 537 AND eor_link_127.to_contentobject_id = 127 AND
I know it misses some parenthesis so I edited the string to test it directly in phpMyAdmin. This is the query:
SELECT DISTINCT
ezcontentobject.*,
ezcontentobject_tree.*,
ezcontentclass.serialized_name_list as class_serialized_name_list,
ezcontentclass.identifier as class_identifier,
ezcontentclass.is_container as is_container
, ezcontentobject_name.name as name, ezcontentobject_name.real_translation
, a0.sort_key_int
FROM
ezcontentobject_tree,
ezcontentobject,ezcontentclass
, ezcontentobject_name
, ezcontentobject_attribute a0
, ezcontentobject_link eor_link_126
, ezcontentobject_link eor_link_127
WHERE
ezcontentobject_tree.parent_node_id = 1443 and
((eor_link_126.from_contentobject_id = ezcontentobject.id AND
eor_link_126.from_contentobject_version = ezcontentobject.current_version AND
eor_link_126.contentclassattribute_id = 537 AND
eor_link_126.to_contentobject_id = 126) OR
(eor_link_127.from_contentobject_id = ezcontentobject.id AND
eor_link_127.from_contentobject_version = ezcontentobject.current_version AND
eor_link_127.contentclassattribute_id = 537 AND
eor_link_127.to_contentobject_id = 127)) AND
a0.contentobject_id = ezcontentobject.id AND
a0.contentclassattribute_id = 191 AND
a0.version = ezcontentobject_name.content_version AND
( a0.language_id & ezcontentobject.language_mask > 0 AND
( ( ezcontentobject.language_mask - ( ezcontentobject.language_mask & a0.language_id ) ) & 1 )
+ ( ( ( ezcontentobject.language_mask - ( ezcontentobject.language_mask & a0.language_id ) ) & 2 ) )
<
( a0.language_id & 1 )
+ ( ( a0.language_id & 2 ) )
)
AND
ezcontentclass.version=0 AND
ezcontentobject_tree.contentobject_id = ezcontentobject.id AND
ezcontentclass.id = ezcontentobject.contentclass_id AND
ezcontentobject.contentclass_id IN ( 17 ) AND
ezcontentobject_tree.contentobject_id = ezcontentobject_name.contentobject_id and
ezcontentobject_tree.contentobject_version = ezcontentobject_name.content_version and
( ezcontentobject_name.language_id & ezcontentobject.language_mask > 0 AND
( ( ezcontentobject.language_mask - ( ezcontentobject.language_mask & ezcontentobject_name.language_id ) ) & 1 )
+ ( ( ( ezcontentobject.language_mask - ( ezcontentobject.language_mask & ezcontentobject_name.language_id ) ) & 2 ) )
<
( ezcontentobject_name.language_id & 1 )
+ ( ( ezcontentobject_name.language_id & 2 ) )
)
AND ezcontentobject_tree.is_invisible = 0
AND
ezcontentobject.language_mask & 3 > 0
ORDER BY a0.sort_key_int DESC
LIMIT 0, 10
The thing is, when I execute the query above, nothing is returned because the query never stops. The CPU hits 100% and I have to restart mysql which means it's not a syntax issue.
Here is the explain of the query :
If anyone has any clue about this it will be very helpful.
I've solved it by rewriting everything using eZPersistentObject::fetchObjectList().
Related
I'm trying to handle TP and SL for orders, but I'm still getting errors. I want my stoploss to be at a moving average called MA_Slow and the takeprofit to a number of pips over my initial position. I'm getting 138s and 130s. Any ideas?
// if open position set sl at Slow_MA and tp if specified
for (int i = OrdersTotal(); i>=0; i-- )
if ( OrderSelect(i,SELECT_BY_POS) == true )
if ( OrderSymbol() == _Symbol )
if ( OrderType() == OP_BUY )
{
RefreshRates();
if ( Bid - OrderOpenPrice() > Slow_MA )
if ( OrderStopLoss() < Slow_MA )
{
retval = OrderModify( OrderTicket(), OrderOpenPrice(), NormalizeDouble(Slow_MA, Digits), NormalizeDouble(OrderOpenPrice() + ( TakeProfit * 0.0001 ),Digits), 5, Lime );
if(!retval) Print("Error in OrderModify, Buy Order #",OrderTicket() ," Error code=",GetLastError());
Print("Buy order ", OrderTicket(), " modified. SL = ", DecOut(OrderStopLoss(),5));
}
}
else // mod SL for Sell orders
{
RefreshRates();
if ( OrderOpenPrice() - Ask < Slow_MA )
if ( OrderStopLoss() > Slow_MA )
{
retval = OrderModify( OrderTicket(), OrderOpenPrice(), NormalizeDouble(Slow_MA, Digits), NormalizeDouble(OrderOpenPrice() - ( TakeProfit * 0.0001 ), Digits), 5, Lime );
if(!retval) Print("Error in OrderModify, Sell Order #",OrderTicket() ," Error code=",GetLastError());
Print("Sell order ", OrderTicket(), " modified. SL = ", DecOut(OrderStopLoss(),5));
}
}
Batch apex class not covering execute method
Batch Apex Class : Trying to cover execute method but not covered in image above.
This batch class is on aggregate result. Please suggest me how to cover this batch class
It is working on search result of order if the status is based on filter then in execute method it will aggregate the value of fulfilment id of all orders related to it. based on their order status it executes.
global class UpdateOrderIntegrationStatus_Batch implements
Database.Batchable<AggregateResult>, Database.Stateful{
String status_filter = 'Waiting On Prior Order';
String query = 'select count(Id) cnt, Fulfillment__c from Apttus_Config2__Order__c'
+' where Fulfillment__c <> null and Order_Integration_Status__c = \''+status_filter + '\''
+' group by Fulfillment__c '
+' limit 50000';
public UpdateOrderIntegrationStatus_Batch(){}
public UpdateOrderIntegrationStatus_Batch(string q){
query = q;
}
global Iterable<AggregateResult> start(Database.BatchableContext BC){
//system.debug('>>>> query : ' + query)
return new AggregateResultIterable(query);
}
global void execute(Database.BatchableContext BC, List<sobject> results){
set<Id> fufillmentIds = new set<Id>();
for(Sobject sObj:results){
AggregateResult ar = (AggregateResult)sObj;
fufillmentIds.add((Id) ar.get('Fulfillment__c'));
}
List<Contract> fulfillments = [select id,(select Id, Order_Integration_Status__c from Orders__r order by Name asc) from Contract where id IN:fufillmentIds];
List<Apttus_Config2__Order__c> orderToUpdate = new List<Apttus_Config2__Order__c>();
String priorOrderIntegrationStatus = '';
for(Contract fulfillmentObj: fulfillments){
priorOrderIntegrationStatus = '';
for(Apttus_Config2__Order__c order: fulfillmentObj.Orders__r){
if(order.Order_Integration_Status__c == 'Processed'){
priorOrderIntegrationStatus = order.Order_Integration_Status__c;
}
else if(order.Order_Integration_Status__c == 'Error'){
break;
}
else if(order.Order_Integration_Status__c == status_filter && priorOrderIntegrationStatus == 'Processed' ){
order.Order_Integration_Status__c = 'Ready';
orderToUpdate.add(order);
priorOrderIntegrationStatus = order.Order_Integration_Status__c;
break;
}
else{
priorOrderIntegrationStatus = order.Order_Integration_Status__c; //For other statuses like Ready, Not Ready, Pending etc.
continue;
}
}
}
if(orderToUpdate <> null && orderToUpdate.size() > 0){
Database.update(orderToUpdate, false);
}
}
global void finish(Database.BatchableContext BC){
System.debug('UpdateOrderIntegrationStatus_Batch Finished');
}
}
Test Batch class:
#isTest
public class UpdateOrderIntegrationStatus_Batch_Test {
public static testMethod void testBatch() {
Test.StartTest();
Account acc =APTS_BvdUtility.createAccount();
Contact con = APTS_BvdUtility.createContact(acc.Id);
Apttus_Config2__AccountLocation__c acclocation = APTS_BvdUtility.createAccountLocation('Test Loc', acc.Id, con.Id);
Opportunity opp = APTS_BvdUtility.createOpportunity('Test Opp ', acc.Id, con.Id);
Apttus_Config2__PriceList__c priceList = APTS_BvdUtility.createPriceList('Test PriceBook') ;
Apttus_Proposal__Proposal__c quote = APTS_BvdUtility.createQuote(acc, opp, priceList.Id, 'quoteName');
Apttus_Config2__Order__c newOrder = new Apttus_Config2__Order__c();
newOrder.Apttus_QPConfig__ProposalId__c = quote.Id;
newOrder.Apttus_Config2__Status__c = 'Pending';
newOrder.AC_Billing_Street_1__c = '234';
newOrder.AC_Shipping_Street_1__c = '234';
newOrder.Ultimate_Parent_Account_ID__c = quote.Apttus_Proposal__Account__c;
newOrder.Apttus_Config2__BillToAccountId__c = quote.Apttus_Proposal__Account__c;
newOrder.Apttus_Config2__ShipToAccountId__c = quote.Apttus_Proposal__Account__c;
newOrder.Apttus_Config2__RelatedOpportunityId__c = quote.Apttus_Proposal__Opportunity__c;
newOrder.Apttus_Config2__OrderStartDate__c = quote.Apttus_Proposal__ExpectedStartDate__c;
newOrder.Apttus_Config2__OrderEndDate__c = quote.Apttus_Proposal__ExpectedEndDate__c;
newOrder.Apttus_Config2__SoldToAccountId__c = quote.Apttus_Proposal__Account__c;
newOrder.Apttus_Config2__PriceListId__c = quote.Apttus_QPConfig__PriceListId__c;
newOrder.Apttus_Config2__Type__c = quote.Apttus_QPConfig__ABOType__c;
newOrder.Language__c = 'English';
newOrder.Billing_Cycle__c = 'Annual';
newOrder.Detailed_Invoice__c = true;
newOrder.Bill_To_Contracting_Party__c = 'Test123';
newOrder.Ship_To_Contracting_Party__c = 'Test123';
newOrder.Bill_To_Location__c = acclocation.Id;
newOrder.Ship_To_Location__c = acclocation.id;
newOrder.Bill_To_Ultimate_Parent_Account_ID__c = quote.Apttus_Proposal__Account__c;
newOrder.Ship_To_Ultimate_Parent_Account_ID__c = quote.Apttus_Proposal__Account__c;
newOrder.Apttus_Config2__ActivatedDate__c = System.today();
newOrder.Apttus_Config2__OrderDate__c = System.today();
newOrder.CurrencyIsoCode = quote.CurrencyIsoCode;
newOrder.Apttus_Config2__ActivatedDate__c = System.Date.today();
newOrder.Order_Integration_Status__c='Waiting On Prior Order';
insert newOrder;
String testseqname = 'CONTRACT_NUMBER';
double testseqnumber = 1234;
Sequence_Number__c sn = new Sequence_Number__c(Name = testseqname, Next_Sequence_Number__c = testseqnumber);
insert sn;
List<SObject> contracts = new List<Contract>();
Contract fulfillment = new Contract();
fulfillment.Fulfillment_Total__c = 6000;
fulfillment.AccountId = acc.Id;
fulfillment.Opportunity__c = opp.Id;
fulfillment.Renewal_Opportunity__c = opp.Id;
fulfillment.CurrencyIsoCode = newOrder.CurrencyIsoCode;
fulfillment.CustomerSignedDate = system.today();
fulfillment.Status = 'Client Signed';
fulfillment.End_Date__c = newOrder.Apttus_Config2__OrderEndDate__c;
fulfillment.StartDate = newOrder.Apttus_Config2__OrderStartDate__c;
fulfillment.Latest_Order__c = newOrder.Id;
fulfillment.Billing_Integration_Status__c = 'Ready';
fulfillment.RecordTypeId = System.Label.Sales_Contract_RecordTypeID;
fulfillment.Original_Order_Submit_Date__c = newOrder.Apttus_Config2__ActivatedDate__c.date();
fulfillment.BusinessUnit__c = 'Bureau van Dijk Electronic Publishing Inc.';
fulfillment.Contract_Sequence_Number__c = 993360;
// insert fulfillment;
contracts.add(fulfillment);
insert contracts;
List<Contract> contrList = [select id,(select Id, Order_Integration_Status__c from Orders__r order by Name asc) from Contract where id =:contracts[0].Id];
newOrder.Order_Integration_Status__c='Processed';
update newOrder;
String status_filter = 'Waiting On Prior Order';
String query = 'select count(Id) cnt, Fulfillment__c from Apttus_Config2__Order__c'
+' where Fulfillment__c <> null and Order_Integration_Status__c = \''+status_filter + '\''
+' group by Fulfillment__c '
+' limit 50000';
/* String query = 'select id,(select Id, Order_Integration_Status__c from Orders__r order
by Name asc) from Contract';
String query = 'select count(Id) cnt, Fulfillment__c from Apttus_Config2__Order__c'
+' where Fulfillment__c =\''+contrList[0].Id +'\' and Order_Integration_Status__c =
\''+status_filter + '\''
+' group by Fulfillment__c '
+' limit 50000';
*/
UpdateOrderIntegrationStatus_Batch obj = new UpdateOrderIntegrationStatus_Batch();
UpdateOrderIntegrationStatus_Batch obj1 = new UpdateOrderIntegrationStatus_Batch(query);
// obj1.execute(BC, contracts);
ID batchprocessid = Database.executeBatch(obj);
ID batchprocessid1 = Database.executeBatch(obj1,10);
List<Apttus_Config2__Order__c> orders =[select Id,
Order_Integration_Status__c,Fulfillment__c from Apttus_Config2__Order__c where
Fulfillment__c=:contracts[0].Id];
for(Apttus_Config2__Order__c ord : orders){
system.assertEquals('Processed', ord.Order_Integration_Status__c);
}
Test.StopTest();
}
}
I have a function that finds the siblings of a post in Wordpress, the previous three, and the next three. However, at the moment, it orders it by the date published, which is not what I want. In wordpress, I have a plugin which allows the user to re-order the post, and this is how it displays on the site. I need this query to order it not by date, but by the order of the post. Would this be possible?
function get_post_siblings( $limit = 3, $date = '' ) {
global $wpdb, $post;
if( empty( $date ) )
$date = $post->post_date;
//$date = '2009-06-20 12:00:00'; // test data
$limit = absint( $limit );
if( !$limit )
return;
$p = $wpdb->get_results( "
(
SELECT
p1.post_title,
p1.post_date,
p1.post_name,
p1.ID
FROM
$wpdb->posts p1
WHERE
p1.post_date < '$date' AND
p1.post_type = 'work' AND
p1.post_status = 'publish'
ORDER by
p1.post_date DESC
LIMIT
$limit
)
UNION
(
SELECT
p2.post_title,
p2.post_date,
p2.post_name,
p2.ID
FROM
$wpdb->posts p2
WHERE
p2.post_date > '$date' AND
p2.post_type = 'work' AND
p2.post_status = 'publish'
ORDER by
p2.post_date DESC
LIMIT
$limit
)
ORDER by post_date DESC
" );
$i = 0;
$adjacents = array();
for( $c = count($p); $i < $c; $i++ )
if( $i < $limit )
$adjacents['prev'][] = $p[$i];
else
$adjacents['next'][] = $p[$i];
return $adjacents;
}
Hi i have a problem in QueryByilder in Doctrine. i wrote a Query that has 2 parameter and they affect in where statement. i want to ignore where statement if the related parameter was null. for example if $play = 3 and $theater = null the query must return all tickets with play 3 and whatever theater
this is my code:
public function getAllSearchedTickets($play,$teater){
return $this->getEntityManager()->createQuery('
select s from mtadminBundle:ReserveLocation s
join s.reserve a
join a.sance b
where a.acceptCode != 0
and b.play = :play
and b.teater = :teater')
->setParameters(array('play'=>$play,'teater'=>$teater))->getResult();
}
thank you.
You should use the QueryBuilder for this, to do it more efficiently, I'll show you how you do yours and then the same with the QueryBuilder as example:
Yours:
public function getAllSearchedTickets($play,$teater){
$query = 'select s from mtadminBundle:ReserveLocation s'.
'join s.reserve a'.
'join a.sance b'.
'where a.acceptCode != 0');
$paramArray = array();
if( $play ) {
$query .= ' and b.play = :play';
$paramArray['play'] = $play;
}
if( $teater ) {
$query .= ' and b.teater = :teater';
$paramArray['teater '] = $teater;
}
return $this->getEntityManager()->createQuery($query)
->setParameters($paramArray)->getResult();
}
QueryBuilder:
public function getAllSearchedTickets($play,$teater){
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
$queryBuilder->select('s')
->from('mtadminBundle:ReserveLocation', 's')
->join('s.reserve', 'a')
->join('a.sance', 'b')
->where('a.acceptCode != 0');
if( $play ) {
$queryBuilder->andWhere('b.play = :play');
$queryBuilder->setParameter('play', $play);
}
if( $teater ) {
$queryBuilder->andWhere('b.teater = :teater');
$queryBuilder->setParameter('teater', $teater);
}
return $queryBuilder->getResult();
}
I have catalog price rules for some categories. In frontend, in category.tpl, I have to notify if there are special prices bound to that specific category or some of its parents.
For now, I'm building a function on the controller that finds it with a query. I was wandering if there was some shortcut for doing this.
I wrote a function (a CategoryController method) to solve my problem and I share:
public function get_category_promo(){
//get the active country, since promo are also country-based
if($this->context->customer->isLogged()){
$current_country = Customer::getCurrentCountry($this->context->customer->id);
} else {
$current_country = $this->context->country->id;
}
$db = Db::getInstance();
$sql = '
SELECT
truncate(`reduction`,0) as reduction,
`reduction_type`,
`from`,
`to`,
`type` as category_type,
`value` as id_category,
`id_parent` as category_parent,
`level_depth` as depth
FROM
`'._DB_PREFIX_.'specific_price_rule_condition` rule_condition
INNER JOIN
`'._DB_PREFIX_.'specific_price_rule_condition_group` rule_group
on rule_condition.`id_specific_price_rule_condition_group` = rule_group.`id_specific_price_rule_condition_group`
INNER JOIN
`'._DB_PREFIX_.'specific_price_rule` price_rule
on price_rule.`id_specific_price_rule` = rule_group.`id_specific_price_rule`
INNER JOIN
`'._DB_PREFIX_.'category` category
on rule_condition.`value` = category.`id_category`
WHERE rule_condition.`type` = "category"';
$parents = $this->category->getParentsCategories();
array_shift($parents);//first is == this->category so I shift it out
$sql_aux = ' and (rule_condition.`value` = ' . $this->category->id_category;
foreach($parents as $parent){
$sql_aux .= ' or rule_condition.`value` = ' . $parent["id_category"];
}
$sql_aux .= ')';
$sql_aux .= ' and price_rule.`id_country` = ' . $current_country;
$sql_aux .= ' order by level_depth desc';
$sql .= $sql_aux;
$promo_data = $db->executeS($sql);
$promo_data = count($promo_data) > 0 ? $promo_data : null;
if(!$promo_data) return false;//stop
function validate_date($promo){
//if there are no dates
if((int)$promo['to'] == 0 && (int)$promo['from'] == 0) return true;
//if there is end promo date
if((int)$promo['to'] != 0){
$to = new DateTime($promo['to']);
//...and is still valid
if($to >= new DateTime('NOW')) return true;
}
}//end validate
//refine query results
$filtered = array_values(array_filter($promo_data,'validate_date'));
$promo_data = $filtered[0];//if there are more than one promo on the same category, the promo on the higher depth is used form the system, so I need only that promo
//promo without dates. Only refine to/from to better use in smarty
if((int)$promo_data['to'] == 0 && (int)$promo_data['from'] == 0){
$promo_data['to'] = 0;
$promo_data['from'] = 0;
$this->context->smarty->assign('promo_data', $promo_data);
return true;
}
if((int)$promo_data['to'] != 0){//promo ha send date
$to = new DateTime($promo_data['to']);
if($to >= new DateTime('NOW')){
$promo_data['to'] = $to->format('d-m-Y');
} else {
return false;//not a valid date
}
}
if((int)$promo_data['from'] != 0){
$from = new DateTime($promo_data['from']);
$promo_data['from'] = $from->format('d-m-Y');
} else {
$promo_data['from'] = 0;
}
$this->context->smarty->assign('promo_data', $promo_data);
}//end get_category_promo