<dtml-comment>
title:
connection_id:erp5_sql_connection
max_rows:1000
max_cache:100
cache_time:0
class_name:ZSQLBrain
class_file:zsqlbrain.py
</dtml-comment>
<params>sort_on
resource_id_list=""
variante_id_list=""
id
default_source_title
default_source_reference</params>
SELECT DISTINCT
	item.uid, item.id, item.path, item.Description, item.simulation_state, item.default_destination_title
FROM
	catalog AS item

LEFT JOIN category
ON (category.category_uid=item.uid
AND category.base_category_uid = <dtml-var "portal_categories.aggregate.getUid()">)

LEFT JOIN stock
ON (stock.uid = category.uid)

LEFT JOIN movement
ON (movement.uid = category.uid)

LEFT JOIN movement AS next_movement
ON (next_movement.resource_uid = movement.resource_uid
AND next_movement.variation_text = movement.variation_text
AND next_movement.start_date > movement.start_date
AND not (next_movement.inventory is NULL))

<dtml-if expr="_.len(resource_id_list)>0">
, catalog AS resource
, category AS cat1
</dtml-if>
<dtml-if expr="_.len(variante_id_list)>0">
, catalog as variante
, category AS cat2
</dtml-if>

WHERE
	item.portal_type = "Piece Tissu"
AND	( stock.uid is NULL
OR ( stock.node_uid = <dtml-var "portal_categories.site.Stock_MP.Gravelines.getUid()">
AND ( stock.quantity >= 0
OR (stock.quantity < 0
AND not (movement.inventory is NULL) ) ) ) )
<dtml-in PieceTissu_searchConsumedList>AND item.uid <> <dtml-sqlvar uid type="int">
</dtml-in>
AND next_movement.uid is NULL

<dtml-if expr="_.len(resource_id_list)>0">
AND ( resource.id LIKE "<dtml-var expr="resource_id_list[0]">"
<dtml-in prefix="loop" expr="_.range(_.len(resource_id_list)-1)">
OR resource.id LIKE "<dtml-var expr="resource_id_list[loop_item+1]">"
</dtml-in>
)
AND cat1.uid=item.uid
AND cat1.category_uid=resource.uid
AND cat1.base_category_uid=<dtml-var "portal_categories.resource.uid">
</dtml-if>

<dtml-if expr="_.len(variante_id_list)>0">
AND ( variante.id LIKE "<dtml-var expr="variante_id_list[0]">"
<dtml-in prefix="loop" expr="_.range(_.len(variante_id_list)-1)">
OR variante.id LIKE "<dtml-var expr="variante_id_list[loop_item+1]">"
</dtml-in>
)
AND cat2.uid=item.uid
AND cat2.category_uid=variante.uid
AND cat2.base_category_uid=<dtml-var "portal_categories.coloris.uid">
</dtml-if>

<dtml-if id>
AND item.id LIKE <dtml-sqlvar id type="string">
</dtml-if>
<dtml-if default_source_title>
AND item.default_source_title LIKE <dtml-sqlvar default_source_title type="string">
</dtml-if>
<dtml-if default_source_reference>
AND item.default_source_reference LIKE <dtml-sqlvar default_source_reference type="string">
</dtml-if>

<dtml-if sort_on>ORDER BY
	<dtml-var sort_on>
</dtml-if>
