Commit 43b65274 authored by Alain Takoudjou's avatar Alain Takoudjou

slapos_accounting: migrate to new business template format

parent 6684c59f
<dtml-var table_0>.base_category_uid = <dtml-var "portal_categories.causality.getUid()">
AND <dtml-var table_1>.uid = <dtml-var table_0>.uid
AND <dtml-var table_1>.portal_type = 'Payment Transaction'
AND <dtml-var table_1>.simulation_state not in ('deleted', 'cancelled')
<dtml-var RELATED_QUERY_SEPARATOR>
<dtml-var table_0>.category_uid = <dtml-var query_table>.uid
......@@ -53,22 +53,6 @@ query_table="catalog"</string> </value>
<key> <string>max_rows_</string> </key>
<value> <int>0</int> </value>
</item>
<item>
<key> <string>src</string> </key>
<value> <string encoding="cdata"><![CDATA[
<dtml-var table_0>.base_category_uid = <dtml-var "portal_categories.causality.getUid()">\n
AND <dtml-var table_1>.uid = <dtml-var table_0>.uid\n
AND <dtml-var table_1>.portal_type = \'Payment Transaction\'\n
AND <dtml-var table_1>.simulation_state not in (\'deleted\', \'cancelled\')\n
\n
<dtml-var RELATED_QUERY_SEPARATOR>\n
<dtml-var table_0>.category_uid = <dtml-var query_table>.uid\n
\n
]]></string> </value>
</item>
<item>
<key> <string>title</string> </key>
<value> <string></string> </value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
......@@ -54,6 +54,12 @@
</tuple>
</value>
</item>
<item>
<key> <string>__translation_dict</string> </key>
<value>
<dictionary/>
</value>
</item>
<item>
<key> <string>categories</string> </key>
<value>
......
portal = context.getPortalObject()
portal.portal_catalog.searchAndActivate(
portal_type='Sale Packing List',
simulation_state='started',
causality_state='solved',
specialise_uid=portal.restrictedTraverse(portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()).getUid(),
method_id='Delivery_deliverStartedAggregatedSalePackingList',
activate_kw={'tag': tag},
)
context.activate(after_tag=tag).getId()
......@@ -48,20 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>portal = context.getPortalObject()\n
portal.portal_catalog.searchAndActivate(\n
portal_type=\'Sale Packing List\',\n
simulation_state=\'started\',\n
causality_state=\'solved\',\n
specialise_uid=portal.restrictedTraverse(portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()).getUid(),\n
method_id=\'Delivery_deliverStartedAggregatedSalePackingList\',\n
activate_kw={\'tag\': tag},\n
)\n
context.activate(after_tag=tag).getId()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
portal = context.getPortalObject()
portal.portal_catalog.searchAndActivate(
# XXX Filter directly the right open sale order
method_id='OpenSaleOrder_reindexIfIndexedBeforeLine',
portal_type="Open Sale Order",
children_portal_type="Open Sale Order Line",
activate_kw={'tag': tag},
)
context.activate(after_tag=tag).getId()
......@@ -48,21 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>portal = context.getPortalObject()\n
\n
portal.portal_catalog.searchAndActivate(\n
# XXX Filter directly the right open sale order\n
method_id=\'OpenSaleOrder_reindexIfIndexedBeforeLine\',\n
portal_type="Open Sale Order",\n
children_portal_type="Open Sale Order Line",\n
activate_kw={\'tag\': tag},\n
)\n
\n
context.activate(after_tag=tag).getId()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
portal = context.getPortalObject()
portal.portal_catalog.searchAndActivate(
method_id='HostingSubscription_requestUpdateOpenSaleOrder',
portal_type="Hosting Subscription",
causality_state="diverged",
activate_kw={'tag': tag, 'priority': 2},
activity_count=10,
packet_size=1, # HostingSubscription_trigger_Person_storeOpenSaleOrderJournal
)
context.activate(after_tag=tag).getId()
......@@ -48,22 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>portal = context.getPortalObject()\n
\n
portal.portal_catalog.searchAndActivate(\n
method_id=\'HostingSubscription_requestUpdateOpenSaleOrder\',\n
portal_type="Hosting Subscription",\n
causality_state="diverged",\n
activate_kw={\'tag\': tag, \'priority\': 2},\n
activity_count=10,\n
packet_size=1, # HostingSubscription_trigger_Person_storeOpenSaleOrderJournal\n
)\n
\n
context.activate(after_tag=tag).getId()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
portal = context.getPortalObject()
portal.portal_catalog.searchAndActivate(
portal_type='Open Sale Order',
validation_state='validated',
children_portal_type='Open Sale Order Line',
method_id='OpenSaleOrder_updatePeriod',
activate_kw={'tag': tag},
packet_size=1,
activity_count=100
)
context.activate(after_tag=tag).getId()
......@@ -48,21 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>portal = context.getPortalObject()\n
portal.portal_catalog.searchAndActivate(\n
portal_type=\'Open Sale Order\',\n
validation_state=\'validated\',\n
children_portal_type=\'Open Sale Order Line\',\n
method_id=\'OpenSaleOrder_updatePeriod\',\n
activate_kw={\'tag\': tag},\n
packet_size=1,\n
activity_count=100\n
)\n
context.activate(after_tag=tag).getId()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
portal = context.getPortalObject()
portal.portal_catalog.searchAndActivate(
portal_type=["Slave Instance", "Software Instance"],
causality_state="diverged",
method_id='Instance_solveInvoicingGeneration',
activate_kw={'tag': tag},
packet_size=1, # Separate calls to many transactions (calculation can take time)
activity_count=1,
)
context.activate(after_tag=tag).getId()
......@@ -48,22 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>portal = context.getPortalObject()\n
\n
portal.portal_catalog.searchAndActivate(\n
portal_type=["Slave Instance", "Software Instance"],\n
causality_state="diverged",\n
method_id=\'Instance_solveInvoicingGeneration\',\n
activate_kw={\'tag\': tag},\n
packet_size=1, # Separate calls to many transactions (calculation can take time)\n
activity_count=1,\n
)\n
\n
context.activate(after_tag=tag).getId()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
portal = context.getPortalObject()
portal.portal_catalog.searchAndActivate(
portal_type="Computer Consumption TioXML File",
validation_state="submitted",
method_id='ComputerConsumptionTioXMLFile_solveInvoicingGeneration',
activity_count=1,
packet_size=1,
activate_kw={'tag': tag, 'priority': 5}
)
context.activate(after_tag=tag).getId()
......@@ -48,22 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>portal = context.getPortalObject()\n
\n
portal.portal_catalog.searchAndActivate(\n
portal_type="Computer Consumption TioXML File",\n
validation_state="submitted",\n
method_id=\'ComputerConsumptionTioXMLFile_solveInvoicingGeneration\',\n
activity_count=1,\n
packet_size=1,\n
activate_kw={\'tag\': tag, \'priority\': 5}\n
)\n
\n
context.activate(after_tag=tag).getId()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
if params is None:
params = {}
from DateTime import DateTime
from Products.ERP5Type.DateUtils import addToDate
from Products.ZSQLCatalog.SQLCatalog import Query
def getAccountingDate(accounting_date):
accounting_day = 25
if accounting_date.day() <= accounting_day:
accounting_date = addToDate(accounting_date, dict(month=-1))
diff = accounting_day - accounting_date.day()
accounting_date = addToDate(accounting_date, dict(day=diff))
return accounting_date
accounting_date = params.get('accounting_date', DateTime().earliestTime())
portal = context.getPortalObject()
portal.portal_catalog.searchAndActivate(
portal_type='Sale Packing List',
simulation_state='confirmed',
causality_state='solved',
specialise_uid=portal.restrictedTraverse(portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()).getUid(),
method_id='Delivery_startConfirmedAggregatedSalePackingList',
activate_kw={'tag': tag},
**{'delivery.start_date': Query(range="max",
**{'delivery.start_date': getAccountingDate(accounting_date)})}
)
context.activate(after_tag=tag).getId()
......@@ -48,43 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string encoding="cdata"><![CDATA[
if params is None:\n
params = {}\n
\n
from DateTime import DateTime\n
from Products.ERP5Type.DateUtils import addToDate\n
from Products.ZSQLCatalog.SQLCatalog import Query\n
\n
def getAccountingDate(accounting_date):\n
accounting_day = 25\n
if accounting_date.day() <= accounting_day:\n
accounting_date = addToDate(accounting_date, dict(month=-1))\n
diff = accounting_day - accounting_date.day()\n
accounting_date = addToDate(accounting_date, dict(day=diff))\n
return accounting_date\n
\n
accounting_date = params.get(\'accounting_date\', DateTime().earliestTime())\n
\n
portal = context.getPortalObject()\n
portal.portal_catalog.searchAndActivate(\n
portal_type=\'Sale Packing List\',\n
simulation_state=\'confirmed\',\n
causality_state=\'solved\',\n
specialise_uid=portal.restrictedTraverse(portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()).getUid(),\n
method_id=\'Delivery_startConfirmedAggregatedSalePackingList\',\n
activate_kw={\'tag\': tag},\n
**{\'delivery.start_date\': Query(range="max",\n
**{\'delivery.start_date\': getAccountingDate(accounting_date)})}\n
)\n
context.activate(after_tag=tag).getId()\n
]]></string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
from DateTime import DateTime
from Products.ERP5Type.DateUtils import getClosestDate
portal = context.getPortalObject()
portal.portal_catalog.searchAndActivate(
portal_type='Sale Invoice Transaction',
simulation_state='confirmed',
causality_state='solved',
specialise_uid=portal.restrictedTraverse(portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()).getUid(),
method_id='Delivery_stopConfirmedAggregatedSaleInvoiceTransaction',
activate_kw={'tag': tag}
)
context.activate(after_tag=tag).getId()
......@@ -48,23 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from DateTime import DateTime\n
from Products.ERP5Type.DateUtils import getClosestDate\n
\n
portal = context.getPortalObject()\n
portal.portal_catalog.searchAndActivate(\n
portal_type=\'Sale Invoice Transaction\',\n
simulation_state=\'confirmed\',\n
causality_state=\'solved\',\n
specialise_uid=portal.restrictedTraverse(portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()).getUid(),\n
method_id=\'Delivery_stopConfirmedAggregatedSaleInvoiceTransaction\',\n
activate_kw={\'tag\': tag}\n
)\n
context.activate(after_tag=tag).getId()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
context.getPortalObject().portal_orders.slapos_aggregated_delivery_builder.build(
activate_kw={'tag': tag}
)
context.activate(after_tag=tag).getId()
......@@ -48,14 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>context.getPortalObject().portal_orders.slapos_aggregated_delivery_builder.build(\n
activate_kw={\'tag\': tag}\n
)\n
context.activate(after_tag=tag).getId()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
from DateTime import DateTime
portal = context.getPortalObject()
if context.getPortalType() != 'Sale Packing List':
raise TypeError('Incorrect delivery.')
isTransitionPossible = portal.portal_workflow.isTransitionPossible
if context.getSimulationState() == 'started' \
and len(context.checkConsistency()) == 0 \
and context.getCausalityState() == 'solved' \
and context.getSpecialise() == portal.portal_preferences.getPreferredAggregatedSaleTradeCondition():
comment = 'Delivered by alarm as all actions in started state are ready.'
if isTransitionPossible(context, 'stop'):
context.stop(comment=comment)
if isTransitionPossible(context, 'deliver'):
context.deliver(comment=comment)
......@@ -48,24 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from DateTime import DateTime\n
portal = context.getPortalObject()\n
if context.getPortalType() != \'Sale Packing List\':\n
raise TypeError(\'Incorrect delivery.\')\n
isTransitionPossible = portal.portal_workflow.isTransitionPossible\n
if context.getSimulationState() == \'started\' \\\n
and len(context.checkConsistency()) == 0 \\\n
and context.getCausalityState() == \'solved\' \\\n
and context.getSpecialise() == portal.portal_preferences.getPreferredAggregatedSaleTradeCondition():\n
comment = \'Delivered by alarm as all actions in started state are ready.\'\n
if isTransitionPossible(context, \'stop\'):\n
context.stop(comment=comment)\n
if isTransitionPossible(context, \'deliver\'):\n
context.deliver(comment=comment)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
from DateTime import DateTime
portal = context.getPortalObject()
if context.getPortalType() != 'Sale Packing List':
raise TypeError('Incorrect delivery.')
isTransitionPossible = portal.portal_workflow.isTransitionPossible
if context.getSimulationState() == 'confirmed' \
and len(context.checkConsistency()) == 0 \
and context.getCausalityState() == 'solved' \
and context.getSpecialise() == portal.portal_preferences.getPreferredAggregatedSaleTradeCondition():
comment = 'Start by alarm as all actions in confirmed state are ready.'
date = DateTime().earliestTime()
context.edit(start_date=date, stop_date=date)
if isTransitionPossible(context, 'start'):
context.start(comment=comment)
......@@ -48,24 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from DateTime import DateTime\n
portal = context.getPortalObject()\n
if context.getPortalType() != \'Sale Packing List\':\n
raise TypeError(\'Incorrect delivery.\')\n
isTransitionPossible = portal.portal_workflow.isTransitionPossible\n
if context.getSimulationState() == \'confirmed\' \\\n
and len(context.checkConsistency()) == 0 \\\n
and context.getCausalityState() == \'solved\' \\\n
and context.getSpecialise() == portal.portal_preferences.getPreferredAggregatedSaleTradeCondition():\n
comment = \'Start by alarm as all actions in confirmed state are ready.\'\n
date = DateTime().earliestTime()\n
context.edit(start_date=date, stop_date=date)\n
if isTransitionPossible(context, \'start\'):\n
context.start(comment=comment)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
portal = context.getPortalObject()
if context.getPortalType() != 'Sale Invoice Transaction':
raise TypeError('Incorrect delivery.')
isTransitionPossible = portal.portal_workflow.isTransitionPossible
if context.getSimulationState() == 'confirmed'\
and len(context.checkConsistency()) == 0\
and context.getCausalityState() == 'solved'\
and context.getSpecialise() == portal.portal_preferences.getPreferredAggregatedSaleTradeCondition():
comment = 'Stopped by alarm as all actions in confirmed state are ready.'
if isTransitionPossible(context, 'start'):
context.start(comment=comment)
if isTransitionPossible(context, 'stop'):
context.stop(comment=comment)
......@@ -48,23 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>portal = context.getPortalObject()\n
if context.getPortalType() != \'Sale Invoice Transaction\':\n
raise TypeError(\'Incorrect delivery.\')\n
isTransitionPossible = portal.portal_workflow.isTransitionPossible\n
if context.getSimulationState() == \'confirmed\'\\\n
and len(context.checkConsistency()) == 0\\\n
and context.getCausalityState() == \'solved\'\\\n
and context.getSpecialise() == portal.portal_preferences.getPreferredAggregatedSaleTradeCondition():\n
comment = \'Stopped by alarm as all actions in confirmed state are ready.\'\n
if isTransitionPossible(context, \'start\'):\n
context.start(comment=comment)\n
if isTransitionPossible(context, \'stop\'):\n
context.stop(comment=comment)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
from zExceptions import Unauthorized
if REQUEST is not None:
raise Unauthorized
from Products.ERP5Type.DateUtils import addToDate, getClosestDate
hosting_subscription = context
portal = context.getPortalObject()
workflow_item_list = portal.portal_workflow.getInfoFor(
ob=hosting_subscription,
name='history',
wf_id='instance_slap_interface_workflow')
start_date = None
for item in workflow_item_list:
start_date = item.get('time')
if start_date:
break
if start_date is None:
# Compatibility with old Hosting subscription
start_date = hosting_subscription.getCreationDate()
start_date = getClosestDate(target_date=start_date, precision='day')
return start_date
......@@ -48,36 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from zExceptions import Unauthorized\n
if REQUEST is not None:\n
raise Unauthorized\n
\n
from Products.ERP5Type.DateUtils import addToDate, getClosestDate\n
\n
hosting_subscription = context\n
portal = context.getPortalObject()\n
\n
workflow_item_list = portal.portal_workflow.getInfoFor(\n
ob=hosting_subscription,\n
name=\'history\',\n
wf_id=\'instance_slap_interface_workflow\')\n
start_date = None\n
for item in workflow_item_list:\n
start_date = item.get(\'time\')\n
if start_date:\n
break\n
\n
if start_date is None:\n
# Compatibility with old Hosting subscription\n
start_date = hosting_subscription.getCreationDate()\n
\n
start_date = getClosestDate(target_date=start_date, precision=\'day\')\n
\n
return start_date\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>REQUEST=None</string> </value>
......
from zExceptions import Unauthorized
if REQUEST is not None:
raise Unauthorized
from Products.ERP5Type.DateUtils import addToDate, getClosestDate
hosting_subscription = context
portal = context.getPortalObject()
start_date = context.HostingSubscription_calculateSubscriptionStartDate()
workflow_item_list = portal.portal_workflow.getInfoFor(
ob=hosting_subscription,
name='history',
wf_id='instance_slap_interface_workflow')
result_date = None
for item in workflow_item_list:
if item.get('slap_state') == 'destroy_requested':
end_date = item.get('time')
result_date = getClosestDate(target_date=end_date, precision='day')
if result_date <= end_date:
result_date = addToDate(result_date, to_add={'day': 1})
break
return result_date
......@@ -48,39 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string encoding="cdata"><![CDATA[
from zExceptions import Unauthorized\n
if REQUEST is not None:\n
raise Unauthorized\n
\n
from Products.ERP5Type.DateUtils import addToDate, getClosestDate\n
\n
hosting_subscription = context\n
portal = context.getPortalObject()\n
\n
start_date = context.HostingSubscription_calculateSubscriptionStartDate()\n
\n
workflow_item_list = portal.portal_workflow.getInfoFor(\n
ob=hosting_subscription,\n
name=\'history\',\n
wf_id=\'instance_slap_interface_workflow\')\n
result_date = None\n
for item in workflow_item_list:\n
if item.get(\'slap_state\') == \'destroy_requested\':\n
end_date = item.get(\'time\')\n
result_date = getClosestDate(target_date=end_date, precision=\'day\')\n
if result_date <= end_date:\n
result_date = addToDate(result_date, to_add={\'day\': 1})\n
break\n
\n
return result_date\n
]]></string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>REQUEST=None</string> </value>
......
from zExceptions import Unauthorized
if REQUEST is not None:
raise Unauthorized
if context.getCausalityState() == 'diverged':
person = context.getDestinationSectionValue(portal_type="Person")
# Template document does not have person relation
if person is not None:
person.Person_storeOpenSaleOrderJournal()
# Person_storeOpenSaleOrderJournal should fix all divergent Hosting Subscription in one run
assert context.getCausalityState() == 'solved'
......@@ -48,22 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from zExceptions import Unauthorized\n
if REQUEST is not None:\n
raise Unauthorized\n
\n
if context.getCausalityState() == \'diverged\':\n
\n
person = context.getDestinationSectionValue(portal_type="Person")\n
# Template document does not have person relation\n
if person is not None:\n
person.Person_storeOpenSaleOrderJournal()\n
# Person_storeOpenSaleOrderJournal should fix all divergent Hosting Subscription in one run\n
assert context.getCausalityState() == \'solved\'\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>REQUEST=None</string> </value>
......
instance = context
portal = instance.getPortalObject()
portal_workflow = portal.portal_workflow
if portal_workflow.isTransitionPossible(instance, 'converge'):
instance.converge()
slap_state = instance.getSlapState()
if slap_state == 'draft':
# Nothing to do except converging
pass
else:
started = "start_requested"
stopped = "stop_requested"
destroyed = "destroy_requested"
assert slap_state in [started, stopped, destroyed]
previous_length = instance.getInvoicingSynchronizationPointer(1)
history_list = portal_workflow.getInfoFor(ob=instance, name='history', wf_id='instance_slap_interface_workflow')
history_length = len(history_list)
history_entry = history_list[previous_length-1]
# no divergence if no new history entry
if (history_length != 1):
assert previous_length != history_length
setup_quantity = 0
update_quantity = 0
destroy_quantity = 0
current_delivery = instance.getCausalityValue()
if current_delivery is None:
# No previous packing list, so, one setup should be created
# Drop all useless draft line
i_in_draft_state = True
i = 0
while i_in_draft_state:
checking_history_entry = history_list[i]
previous_state = checking_history_entry['slap_state']
if previous_state != 'draft':
i_in_draft_state = False
previous_length = i
else:
setup_quantity += 1
i += 1
if slap_state == destroyed:
# Check if previous pointer was already in destroyed state
previous_state = history_entry['slap_state']
if previous_state != destroyed:
# Let's create destroyed packing list
destroy_quantity = 1
# 1 = entry to set document in draft state
update_quantity = history_length - previous_length - setup_quantity - destroy_quantity
# Time to create the PL
delivery_template = portal.restrictedTraverse(
portal.portal_preferences.getPreferredInstanceDeliveryTemplate())
delivery = delivery_template.Base_createCloneDocument(batch_mode=1)
hosting_subscription = instance.getSpecialiseValue(portal_type="Hosting Subscription")
person = hosting_subscription.getDestinationSectionValue(portal_type="Person")
delivery.edit(
title="%s API usage" % instance.getReference(),
destination=person.getRelativeUrl(),
destination_decision=person.getRelativeUrl(),
start_date=history_entry['time'],
stop_date=portal_workflow.getInfoFor(ob=instance, name='time', wf_id='instance_slap_interface_workflow'),
)
line_edit_kw = {
'aggregate_value_list': [instance, hosting_subscription],
}
if setup_quantity:
delivery_line_template = portal.restrictedTraverse(
portal.portal_preferences.getPreferredInstanceSetupMovementTemplate())
line = delivery_line_template.Base_createCloneDocument(batch_mode=1,
destination=delivery)
line.edit(
quantity=1,
title="%s setup %s" % (instance.getReference(), setup_quantity),
**line_edit_kw
)
if update_quantity > 0:
delivery_line_template = portal.restrictedTraverse(
portal.portal_preferences.getPreferredInstanceUpdateMovementTemplate())
line = delivery_line_template.Base_createCloneDocument(batch_mode=1,
destination=delivery)
line.edit(
quantity=update_quantity,
title="%s updated %i times" % (instance.getReference(), update_quantity),
**line_edit_kw
)
if destroy_quantity:
delivery_line_template = portal.restrictedTraverse(
portal.portal_preferences.getPreferredInstanceDestroyMovementTemplate())
line = delivery_line_template.Base_createCloneDocument(batch_mode=1,
destination=delivery)
line.edit(
quantity=destroy_quantity,
title="%s destroyed" % instance.getReference(),
**line_edit_kw
)
delivery.confirm()
delivery.start()
delivery.stop()
delivery.deliver()
delivery.startBuilding()
instance.edit(
invoicing_synchronization_pointer=history_length,
causality_value=delivery,
)
......@@ -48,133 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string encoding="cdata"><![CDATA[
instance = context\n
portal = instance.getPortalObject()\n
portal_workflow = portal.portal_workflow\n
\n
if portal_workflow.isTransitionPossible(instance, \'converge\'):\n
instance.converge()\n
\n
slap_state = instance.getSlapState()\n
\n
if slap_state == \'draft\':\n
# Nothing to do except converging\n
pass\n
else:\n
started = "start_requested"\n
stopped = "stop_requested"\n
destroyed = "destroy_requested"\n
assert slap_state in [started, stopped, destroyed]\n
\n
previous_length = instance.getInvoicingSynchronizationPointer(1)\n
history_list = portal_workflow.getInfoFor(ob=instance, name=\'history\', wf_id=\'instance_slap_interface_workflow\')\n
history_length = len(history_list)\n
history_entry = history_list[previous_length-1]\n
\n
# no divergence if no new history entry\n
if (history_length != 1):\n
assert previous_length != history_length\n
\n
setup_quantity = 0\n
update_quantity = 0\n
destroy_quantity = 0\n
\n
current_delivery = instance.getCausalityValue()\n
if current_delivery is None:\n
# No previous packing list, so, one setup should be created\n
# Drop all useless draft line\n
i_in_draft_state = True\n
i = 0\n
while i_in_draft_state:\n
checking_history_entry = history_list[i]\n
previous_state = checking_history_entry[\'slap_state\']\n
if previous_state != \'draft\':\n
i_in_draft_state = False\n
previous_length = i\n
else:\n
setup_quantity += 1\n
i += 1\n
\n
if slap_state == destroyed:\n
# Check if previous pointer was already in destroyed state\n
previous_state = history_entry[\'slap_state\']\n
if previous_state != destroyed:\n
# Let\'s create destroyed packing list\n
destroy_quantity = 1\n
\n
# 1 = entry to set document in draft state\n
update_quantity = history_length - previous_length - setup_quantity - destroy_quantity\n
\n
# Time to create the PL\n
delivery_template = portal.restrictedTraverse(\n
portal.portal_preferences.getPreferredInstanceDeliveryTemplate())\n
delivery = delivery_template.Base_createCloneDocument(batch_mode=1)\n
\n
hosting_subscription = instance.getSpecialiseValue(portal_type="Hosting Subscription")\n
person = hosting_subscription.getDestinationSectionValue(portal_type="Person")\n
\n
delivery.edit(\n
title="%s API usage" % instance.getReference(),\n
destination=person.getRelativeUrl(),\n
destination_decision=person.getRelativeUrl(),\n
start_date=history_entry[\'time\'],\n
stop_date=portal_workflow.getInfoFor(ob=instance, name=\'time\', wf_id=\'instance_slap_interface_workflow\'),\n
)\n
line_edit_kw = {\n
\'aggregate_value_list\': [instance, hosting_subscription],\n
}\n
\n
if setup_quantity:\n
delivery_line_template = portal.restrictedTraverse(\n
portal.portal_preferences.getPreferredInstanceSetupMovementTemplate())\n
line = delivery_line_template.Base_createCloneDocument(batch_mode=1,\n
destination=delivery)\n
line.edit(\n
quantity=1,\n
title="%s setup %s" % (instance.getReference(), setup_quantity),\n
**line_edit_kw\n
)\n
\n
if update_quantity > 0:\n
delivery_line_template = portal.restrictedTraverse(\n
portal.portal_preferences.getPreferredInstanceUpdateMovementTemplate())\n
line = delivery_line_template.Base_createCloneDocument(batch_mode=1,\n
destination=delivery)\n
line.edit(\n
quantity=update_quantity,\n
title="%s updated %i times" % (instance.getReference(), update_quantity),\n
**line_edit_kw\n
)\n
\n
if destroy_quantity:\n
delivery_line_template = portal.restrictedTraverse(\n
portal.portal_preferences.getPreferredInstanceDestroyMovementTemplate())\n
line = delivery_line_template.Base_createCloneDocument(batch_mode=1,\n
destination=delivery)\n
line.edit(\n
quantity=destroy_quantity,\n
title="%s destroyed" % instance.getReference(),\n
**line_edit_kw\n
)\n
\n
delivery.confirm()\n
delivery.start()\n
delivery.stop()\n
delivery.deliver()\n
delivery.startBuilding()\n
\n
instance.edit(\n
invoicing_synchronization_pointer=history_length,\n
causality_value=delivery,\n
)\n
]]></string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
from zExceptions import Unauthorized
if REQUEST is not None:
raise Unauthorized
order = context
portal = context.getPortalObject()
indexation_timestamp = portal.portal_catalog(
uid=order.getUid(),
select_dict={'indexation_timestamp': None})[0].indexation_timestamp
line_list = portal.portal_catalog(
portal_type="Open Sale Order Line",
parent_uid=order.getUid(),
indexation_timestamp={'query': indexation_timestamp, 'range': 'nlt'},
limit=1)
if len(line_list):
order.activate().immediateReindexObject()
......@@ -48,28 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from zExceptions import Unauthorized\n
if REQUEST is not None:\n
raise Unauthorized\n
\n
order = context\n
portal = context.getPortalObject()\n
indexation_timestamp = portal.portal_catalog(\n
uid=order.getUid(),\n
select_dict={\'indexation_timestamp\': None})[0].indexation_timestamp\n
\n
line_list = portal.portal_catalog(\n
portal_type="Open Sale Order Line", \n
parent_uid=order.getUid(),\n
indexation_timestamp={\'query\': indexation_timestamp, \'range\': \'nlt\'},\n
limit=1)\n
\n
if len(line_list):\n
order.activate().immediateReindexObject()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>REQUEST=None</string> </value>
......
from zExceptions import Unauthorized
if REQUEST is not None:
raise Unauthorized
if context.getValidationState() == 'validated':
person = context.getDestinationDecisionValue(portal_type="Person")
if person is not None:
person.Person_storeOpenSaleOrderJournal()
......@@ -48,18 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from zExceptions import Unauthorized\n
if REQUEST is not None:\n
raise Unauthorized\n
\n
if context.getValidationState() == \'validated\':\n
person = context.getDestinationDecisionValue(portal_type="Person")\n
if person is not None:\n
person.Person_storeOpenSaleOrderJournal()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>REQUEST=None</string> </value>
......
select_kw = kwargs.copy()
select_kw.pop('portal_type', None)
select_kw.pop('delivery_relative_url_list', None)
from Products.ERP5Type.Document import newTempSimulationMovement
from Products.ZSQLCatalog.SQLCatalog import Query, NegatedQuery, ComplexQuery
portal = context.getPortalObject()
business_process_uid_list = [
portal.business_process_module.slapos_consumption_business_process.getUid(),
portal.business_process_module.slapos_subscription_business_process.getUid()]
specialise_reference_list = [q.getReference() for q in portal.portal_catalog(specialise_uid=business_process_uid_list,
portal_type='Sale Trade Condition')]
select_dict= {'default_aggregate_portal_type': None}
select_kw.update(
limit=50, # just take a bit
portal_type='Sale Packing List Line',
simulation_state='delivered',
parent_specialise_reference=specialise_reference_list,
parent_specialise_portal_type='Sale Trade Condition',
select_dict=select_dict,
left_join_list=select_dict.keys(),
default_aggregate_portal_type=ComplexQuery(NegatedQuery(Query(default_aggregate_portal_type='Computer')),
Query(default_aggregate_portal_type=None), operator="OR"),
grouping_reference=None,
sort_on=(('modification_date', 'ASC'),) # the highest chance to find movement which can be delivered
)
movement_list = portal.portal_catalog(**select_kw)
specialise = portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()
temp_movement_list = []
id = 1
for movement in movement_list:
if movement.getGroupingReference() is not None:
continue
temp_movement = newTempSimulationMovement(
portal, movement.getRelativeUrl(),
quantity=movement.getQuantity(),
resource=movement.getResource(),
source=movement.getDestination(),
destination=movement.getDestination(),
source_section=movement.getSourceSection(),
destination_section=movement.getDestination(),
destination_decision=movement.getDestination(),
specialise=specialise,
price_currency=movement.getPriceCurrency()
)
if movement.getResource() == 'service_module/slapos_instance_subscription':
temp_movement.edit(price=0.83612040133800003)
else:
temp_movement.edit(price=0.0)
temp_movement_list.append(temp_movement)
id += 1
return temp_movement_list
......@@ -48,65 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>select_kw = kwargs.copy()\n
select_kw.pop(\'portal_type\', None)\n
select_kw.pop(\'delivery_relative_url_list\', None)\n
from Products.ERP5Type.Document import newTempSimulationMovement\n
from Products.ZSQLCatalog.SQLCatalog import Query, NegatedQuery, ComplexQuery\n
portal = context.getPortalObject()\n
\n
business_process_uid_list = [\n
portal.business_process_module.slapos_consumption_business_process.getUid(),\n
portal.business_process_module.slapos_subscription_business_process.getUid()]\n
specialise_reference_list = [q.getReference() for q in portal.portal_catalog(specialise_uid=business_process_uid_list,\n
portal_type=\'Sale Trade Condition\')]\n
select_dict= {\'default_aggregate_portal_type\': None}\n
\n
select_kw.update(\n
limit=50, # just take a bit\n
portal_type=\'Sale Packing List Line\',\n
simulation_state=\'delivered\',\n
parent_specialise_reference=specialise_reference_list,\n
parent_specialise_portal_type=\'Sale Trade Condition\',\n
select_dict=select_dict,\n
left_join_list=select_dict.keys(),\n
default_aggregate_portal_type=ComplexQuery(NegatedQuery(Query(default_aggregate_portal_type=\'Computer\')),\n
Query(default_aggregate_portal_type=None), operator="OR"),\n
grouping_reference=None,\n
sort_on=((\'modification_date\', \'ASC\'),) # the highest chance to find movement which can be delivered\n
)\n
movement_list = portal.portal_catalog(**select_kw)\n
\n
specialise = portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()\n
temp_movement_list = []\n
id = 1\n
for movement in movement_list:\n
if movement.getGroupingReference() is not None:\n
continue\n
temp_movement = newTempSimulationMovement(\n
portal, movement.getRelativeUrl(),\n
quantity=movement.getQuantity(),\n
resource=movement.getResource(),\n
source=movement.getDestination(),\n
destination=movement.getDestination(),\n
source_section=movement.getSourceSection(),\n
destination_section=movement.getDestination(),\n
destination_decision=movement.getDestination(),\n
specialise=specialise,\n
price_currency=movement.getPriceCurrency()\n
)\n
if movement.getResource() == \'service_module/slapos_instance_subscription\':\n
temp_movement.edit(price=0.83612040133800003)\n
else:\n
temp_movement.edit(price=0.0)\n
temp_movement_list.append(temp_movement)\n
id += 1\n
\n
return temp_movement_list\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>*args, **kwargs</string> </value>
......
# beware: the configuration of OrderBuilder_generateSlapOSAggregatedMovementList shall
# provide small amounts of movements
person_delivery_mapping = {}
portal = context.getPortalObject()
specialise = portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()
for movement in movement_list:
person = movement.getDestinationValue()
try:
delivery = person_delivery_mapping[person]
except KeyError:
delivery = person.Person_getAggregatedDelivery()
if delivery is None or delivery.getSimulationState() != 'confirmed':
delivery = portal.sale_packing_list_module.newContent(
portal_type='Sale Packing List',
source=movement.getDestination(),
destination=movement.getDestination(),
source_section=movement.getSourceSection(),
destination_section=movement.getDestination(),
destination_decision=movement.getDestination(),
specialise=specialise,
price_currency=movement.getPriceCurrency()
)
delivery.confirm('New aggregated delivery.')
person.Person_setAggregatedDelivery(delivery)
person_delivery_mapping[person] = delivery
return person_delivery_mapping.values()
......@@ -48,37 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string># beware: the configuration of OrderBuilder_generateSlapOSAggregatedMovementList shall\n
# provide small amounts of movements\n
person_delivery_mapping = {}\n
portal = context.getPortalObject()\n
\n
specialise = portal.portal_preferences.getPreferredAggregatedSaleTradeCondition()\n
for movement in movement_list:\n
person = movement.getDestinationValue()\n
try:\n
delivery = person_delivery_mapping[person]\n
except KeyError:\n
delivery = person.Person_getAggregatedDelivery()\n
if delivery is None or delivery.getSimulationState() != \'confirmed\':\n
delivery = portal.sale_packing_list_module.newContent(\n
portal_type=\'Sale Packing List\',\n
source=movement.getDestination(),\n
destination=movement.getDestination(),\n
source_section=movement.getSourceSection(),\n
destination_section=movement.getDestination(),\n
destination_decision=movement.getDestination(),\n
specialise=specialise,\n
price_currency=movement.getPriceCurrency()\n
)\n
delivery.confirm(\'New aggregated delivery.\')\n
person.Person_setAggregatedDelivery(delivery)\n
person_delivery_mapping[person] = delivery\n
return person_delivery_mapping.values()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>movement_list, *args, **kwargs</string> </value>
......
from Products.ERP5Type.Message import translateString
payment_transaction = context
payment_transaction.immediateReindexObject() # in order to avoid selection in OrderBuilder_getAccountingTransactionLineListSlapOS
comment = translateString("Initialised by Order Builder.")
payment_transaction.confirm(comment=comment)
......@@ -48,15 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from Products.ERP5Type.Message import translateString\n
payment_transaction = context\n
payment_transaction.immediateReindexObject() # in order to avoid selection in OrderBuilder_getAccountingTransactionLineListSlapOS\n
comment = translateString("Initialised by Order Builder.")\n
payment_transaction.confirm(comment=comment)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>related_simulation_movement_path_list=None, **kw</string> </value>
......
integration_site = context.getPortalObject().restrictedTraverse(
'portal_integrations/slapos_aggregated_delivery_integration_site')
person_id = context.getId().replace('-', '_')
try:
mapping = integration_site.getCategoryFromMapping('Causality/%s' % person_id, create_mapping_line=True, create_mapping=True)
except ValueError:
return None
return context.restrictedTraverse(mapping)
......@@ -48,19 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>integration_site = context.getPortalObject().restrictedTraverse(\n
\'portal_integrations/slapos_aggregated_delivery_integration_site\')\n
\n
person_id = context.getId().replace(\'-\', \'_\')\n
try:\n
mapping = integration_site.getCategoryFromMapping(\'Causality/%s\' % person_id, create_mapping_line=True, create_mapping=True)\n
except ValueError:\n
return None\n
return context.restrictedTraverse(mapping)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
integration_site = context.getPortalObject().restrictedTraverse(
'portal_integrations/slapos_aggregated_delivery_integration_site')
person_id = context.getId().replace('-', '_')
integration_site.Causality[person_id].setDestinationReference(delivery.getRelativeUrl())
......@@ -48,16 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>integration_site = context.getPortalObject().restrictedTraverse(\n
\'portal_integrations/slapos_aggregated_delivery_integration_site\')\n
\n
\n
person_id = context.getId().replace(\'-\', \'_\')\n
integration_site.Causality[person_id].setDestinationReference(delivery.getRelativeUrl())\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>delivery</string> </value>
......
from Products.ERP5Type.DateUtils import addToDate, getClosestDate
from DateTime import DateTime
portal = context.getPortalObject()
now = DateTime()
person = context
tag = '%s_%s' % (person.getUid(), script.id)
activate_kw = {'tag': tag}
if portal.portal_activities.countMessageWithTag(tag) > 0:
# nothing to do
return
def newOpenOrder(open_sale_order):
open_order_edit_kw = {
'effective_date': DateTime(),
'activate_kw': activate_kw,
}
if open_sale_order is None:
open_sale_order_template = portal.restrictedTraverse(
portal.portal_preferences.getPreferredOpenSaleOrderTemplate())
new_open_sale_order = open_sale_order_template.Base_createCloneDocument(batch_mode=1)
open_order_edit_kw.update({
'destination': person.getRelativeUrl(),
'destination_decision': person.getRelativeUrl(),
'title': "%s SlapOS Subscription" % person.getTitle(),
})
else:
new_open_sale_order = open_sale_order.Base_createCloneDocument(batch_mode=1)
open_sale_order.setExpirationDate(now, activate_kw=activate_kw)
new_open_sale_order.edit(**open_order_edit_kw)
new_open_sale_order.order(activate_kw=activate_kw)
new_open_sale_order.validate(activate_kw=activate_kw)
return new_open_sale_order
def storeWorkflowComment(document, comment):
portal.portal_workflow.doActionFor(document, 'edit_action', comment=comment)
def calculateOpenOrderLineStopDate(open_order_line, hosting_subscription):
end_date = hosting_subscription.HostingSubscription_calculateSubscriptionStopDate()
if end_date is None:
# Be sure that start date is different from stop date
next_stop_date = hosting_subscription.getNextPeriodicalDate(hosting_subscription.HostingSubscription_calculateSubscriptionStartDate())
current_stop_date = next_stop_date
while next_stop_date < now:
# Return result should be < now, it order to provide stability in simulation (destruction if it happen should be >= now)
current_stop_date = next_stop_date
next_stop_date = \
hosting_subscription.getNextPeriodicalDate(current_stop_date)
return addToDate(current_stop_date, to_add={'second': -1})
else:
stop_date = end_date
return stop_date
# Prevent concurrent transaction to update the open order
context.serialize()
# First, check the existing open order. Does some lines need to be removed, updated?
open_sale_order_list = portal.portal_catalog(
default_destination_uid=person.getUid(),
portal_type="Open Sale Order",
validation_state="validated",
limit=2,
)
open_sale_order_count = len(open_sale_order_list)
if open_sale_order_count == 0:
open_sale_order = None
elif open_sale_order_count == 1:
open_sale_order = open_sale_order_list[0].getObject()
else:
raise ValueError, "Too many open order '%s' found: %s" % (person.getRelativeUrl(), [x.path for x in open_sale_order_list])
delete_line_list = []
add_line_list = []
updated_hosting_subscription_dict = {}
deleted_hosting_subscription_dict = {}
if open_sale_order is not None:
for open_order_line in open_sale_order.contentValues(
portal_type='Open Sale Order Line'):
current_start_date = open_order_line.getStartDate()
current_stop_date = open_order_line.getStopDate()
# Prevent mistakes
assert current_start_date is not None
assert current_stop_date is not None
assert current_start_date < current_stop_date
hosting_subscription = open_order_line.getAggregateValue(portal_type='Hosting Subscription')
assert current_start_date == hosting_subscription.HostingSubscription_calculateSubscriptionStartDate()
# First check if the hosting subscription has been correctly simulated (this script may run only once per year...)
stop_date = calculateOpenOrderLineStopDate(open_order_line, hosting_subscription)
if current_stop_date != stop_date:
# Bingo, new subscription to generate
open_order_line.edit(
stop_date=stop_date,
activate_kw=activate_kw)
storeWorkflowComment(open_order_line,
'Stop date updated to %s' % stop_date)
if hosting_subscription.getSlapState() == 'destroy_requested':
# Line should be deleted
assert hosting_subscription.getCausalityState() == 'diverged'
delete_line_list.append(open_order_line.getId())
hosting_subscription.converge(comment="Last open order: %s" % open_order_line.getRelativeUrl())
deleted_hosting_subscription_dict[hosting_subscription.getRelativeUrl()] = None
updated_hosting_subscription_dict[hosting_subscription.getRelativeUrl()] = None
elif (hosting_subscription.getCausalityState() == 'diverged'):
hosting_subscription.converge(comment="Nothing to do on open order.")
updated_hosting_subscription_dict[hosting_subscription.getRelativeUrl()] = None
# Time to check the open order line to add (remaining diverged Hosting
# Subscription normally)
for hosting_subscription in portal.portal_catalog(
portal_type='Hosting Subscription',
default_destination_section_uid=context.getUid(),
causality_state="diverged"):
hosting_subscription = hosting_subscription.getObject()
if hosting_subscription.getCausalityState() == 'diverged':
# Simply check that it has never been simulated
assert len(portal.portal_catalog(
portal_type='Open Sale Order Line',
default_aggregate_uid=hosting_subscription.getUid(),
limit=1)) == 0
# Let's add
add_line_list.append(hosting_subscription)
else:
# Should be in the list of lines to remove
assert (hosting_subscription.getRelativeUrl() in deleted_hosting_subscription_dict) or \
(hosting_subscription.getRelativeUrl() in updated_hosting_subscription_dict)
manual_archive = False
if (add_line_list):
# No need to create a new open order to add lines
if open_sale_order is None:
open_sale_order = newOpenOrder(None)
manual_archive = True
open_order_explanation = ""
# Add lines
added_line_list = []
open_sale_order_line_template = portal.restrictedTraverse(
portal.portal_preferences.getPreferredOpenSaleOrderLineTemplate())
for hosting_subscription in add_line_list:
open_sale_order_line = open_sale_order_line_template.Base_createCloneDocument(batch_mode=1,
destination=open_sale_order)
start_date = hosting_subscription.HostingSubscription_calculateSubscriptionStartDate()
open_sale_order_line.edit(
activate_kw=activate_kw,
title=hosting_subscription.getTitle(),
start_date=start_date,
stop_date=calculateOpenOrderLineStopDate(open_sale_order_line, hosting_subscription),
aggregate_value=hosting_subscription,
)
storeWorkflowComment(open_sale_order_line, "Created for %s" % hosting_subscription.getRelativeUrl())
if (hosting_subscription.getSlapState() == 'destroy_requested'):
# Added line to delete immediately
delete_line_list.append(open_sale_order_line.getId())
hosting_subscription.converge(comment="Last open order: %s" % open_sale_order_line.getRelativeUrl())
else:
hosting_subscription.converge(comment="First open order: %s" % open_sale_order_line.getRelativeUrl())
added_line_list.append(open_sale_order_line.getId())
open_order_explanation += "Added %s." % str(added_line_list)
new_open_sale_order = None
if (delete_line_list):
# All Verifications done. Time to clone/create open order
new_open_sale_order = newOpenOrder(open_sale_order)
if manual_archive == True:
open_sale_order.archive()
open_order_explanation = ""
# Remove lines
new_open_sale_order.deleteContent(delete_line_list)
open_order_explanation += "Removed %s." % str(delete_line_list)
storeWorkflowComment(new_open_sale_order, open_order_explanation)
......@@ -48,194 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string encoding="cdata"><![CDATA[
from Products.ERP5Type.DateUtils import addToDate, getClosestDate\n
from DateTime import DateTime\n
\n
portal = context.getPortalObject()\n
now = DateTime()\n
person = context\n
tag = \'%s_%s\' % (person.getUid(), script.id)\n
activate_kw = {\'tag\': tag}\n
if portal.portal_activities.countMessageWithTag(tag) > 0:\n
# nothing to do\n
return\n
\n
def newOpenOrder(open_sale_order):\n
open_order_edit_kw = {\n
\'effective_date\': DateTime(),\n
\'activate_kw\': activate_kw,\n
}\n
if open_sale_order is None:\n
open_sale_order_template = portal.restrictedTraverse(\n
portal.portal_preferences.getPreferredOpenSaleOrderTemplate())\n
new_open_sale_order = open_sale_order_template.Base_createCloneDocument(batch_mode=1)\n
open_order_edit_kw.update({\n
\'destination\': person.getRelativeUrl(),\n
\'destination_decision\': person.getRelativeUrl(),\n
\'title\': "%s SlapOS Subscription" % person.getTitle(),\n
})\n
else:\n
new_open_sale_order = open_sale_order.Base_createCloneDocument(batch_mode=1)\n
open_sale_order.setExpirationDate(now, activate_kw=activate_kw)\n
new_open_sale_order.edit(**open_order_edit_kw)\n
new_open_sale_order.order(activate_kw=activate_kw)\n
new_open_sale_order.validate(activate_kw=activate_kw)\n
return new_open_sale_order\n
\n
def storeWorkflowComment(document, comment):\n
portal.portal_workflow.doActionFor(document, \'edit_action\', comment=comment)\n
\n
def calculateOpenOrderLineStopDate(open_order_line, hosting_subscription):\n
end_date = hosting_subscription.HostingSubscription_calculateSubscriptionStopDate()\n
if end_date is None: \n
# Be sure that start date is different from stop date\n
next_stop_date = hosting_subscription.getNextPeriodicalDate(hosting_subscription.HostingSubscription_calculateSubscriptionStartDate())\n
current_stop_date = next_stop_date\n
while next_stop_date < now:\n
# Return result should be < now, it order to provide stability in simulation (destruction if it happen should be >= now)\n
current_stop_date = next_stop_date\n
next_stop_date = \\\n
hosting_subscription.getNextPeriodicalDate(current_stop_date)\n
return addToDate(current_stop_date, to_add={\'second\': -1})\n
else:\n
stop_date = end_date\n
return stop_date\n
\n
# Prevent concurrent transaction to update the open order\n
context.serialize()\n
\n
# First, check the existing open order. Does some lines need to be removed, updated?\n
open_sale_order_list = portal.portal_catalog(\n
default_destination_uid=person.getUid(),\n
portal_type="Open Sale Order",\n
validation_state="validated",\n
limit=2,\n
)\n
open_sale_order_count = len(open_sale_order_list)\n
if open_sale_order_count == 0:\n
open_sale_order = None\n
elif open_sale_order_count == 1:\n
open_sale_order = open_sale_order_list[0].getObject()\n
else:\n
raise ValueError, "Too many open order \'%s\' found: %s" % (person.getRelativeUrl(), [x.path for x in open_sale_order_list])\n
\n
delete_line_list = []\n
add_line_list = []\n
\n
updated_hosting_subscription_dict = {}\n
deleted_hosting_subscription_dict = {}\n
\n
if open_sale_order is not None:\n
for open_order_line in open_sale_order.contentValues(\n
portal_type=\'Open Sale Order Line\'):\n
current_start_date = open_order_line.getStartDate()\n
current_stop_date = open_order_line.getStopDate()\n
\n
# Prevent mistakes\n
assert current_start_date is not None\n
assert current_stop_date is not None\n
assert current_start_date < current_stop_date\n
\n
hosting_subscription = open_order_line.getAggregateValue(portal_type=\'Hosting Subscription\')\n
assert current_start_date == hosting_subscription.HostingSubscription_calculateSubscriptionStartDate()\n
\n
# First check if the hosting subscription has been correctly simulated (this script may run only once per year...)\n
stop_date = calculateOpenOrderLineStopDate(open_order_line, hosting_subscription)\n
if current_stop_date != stop_date:\n
# Bingo, new subscription to generate\n
open_order_line.edit(\n
stop_date=stop_date,\n
activate_kw=activate_kw)\n
storeWorkflowComment(open_order_line,\n
\'Stop date updated to %s\' % stop_date)\n
\n
if hosting_subscription.getSlapState() == \'destroy_requested\':\n
# Line should be deleted\n
assert hosting_subscription.getCausalityState() == \'diverged\'\n
delete_line_list.append(open_order_line.getId())\n
hosting_subscription.converge(comment="Last open order: %s" % open_order_line.getRelativeUrl())\n
deleted_hosting_subscription_dict[hosting_subscription.getRelativeUrl()] = None\n
updated_hosting_subscription_dict[hosting_subscription.getRelativeUrl()] = None\n
\n
elif (hosting_subscription.getCausalityState() == \'diverged\'):\n
hosting_subscription.converge(comment="Nothing to do on open order.")\n
updated_hosting_subscription_dict[hosting_subscription.getRelativeUrl()] = None\n
\n
# Time to check the open order line to add (remaining diverged Hosting\n
# Subscription normally)\n
for hosting_subscription in portal.portal_catalog(\n
portal_type=\'Hosting Subscription\',\n
default_destination_section_uid=context.getUid(),\n
causality_state="diverged"):\n
hosting_subscription = hosting_subscription.getObject()\n
if hosting_subscription.getCausalityState() == \'diverged\':\n
# Simply check that it has never been simulated\n
assert len(portal.portal_catalog(\n
portal_type=\'Open Sale Order Line\',\n
default_aggregate_uid=hosting_subscription.getUid(),\n
limit=1)) == 0\n
\n
# Let\'s add\n
add_line_list.append(hosting_subscription)\n
else:\n
# Should be in the list of lines to remove\n
assert (hosting_subscription.getRelativeUrl() in deleted_hosting_subscription_dict) or \\\n
(hosting_subscription.getRelativeUrl() in updated_hosting_subscription_dict)\n
\n
manual_archive = False\n
if (add_line_list):\n
# No need to create a new open order to add lines\n
if open_sale_order is None:\n
open_sale_order = newOpenOrder(None)\n
manual_archive = True\n
\n
open_order_explanation = ""\n
# Add lines\n
added_line_list = []\n
open_sale_order_line_template = portal.restrictedTraverse(\n
portal.portal_preferences.getPreferredOpenSaleOrderLineTemplate())\n
for hosting_subscription in add_line_list:\n
open_sale_order_line = open_sale_order_line_template.Base_createCloneDocument(batch_mode=1,\n
destination=open_sale_order)\n
start_date = hosting_subscription.HostingSubscription_calculateSubscriptionStartDate()\n
open_sale_order_line.edit(\n
activate_kw=activate_kw,\n
title=hosting_subscription.getTitle(),\n
start_date=start_date,\n
stop_date=calculateOpenOrderLineStopDate(open_sale_order_line, hosting_subscription),\n
aggregate_value=hosting_subscription,\n
)\n
storeWorkflowComment(open_sale_order_line, "Created for %s" % hosting_subscription.getRelativeUrl())\n
if (hosting_subscription.getSlapState() == \'destroy_requested\'):\n
# Added line to delete immediately\n
delete_line_list.append(open_sale_order_line.getId())\n
hosting_subscription.converge(comment="Last open order: %s" % open_sale_order_line.getRelativeUrl())\n
else:\n
hosting_subscription.converge(comment="First open order: %s" % open_sale_order_line.getRelativeUrl())\n
added_line_list.append(open_sale_order_line.getId())\n
open_order_explanation += "Added %s." % str(added_line_list)\n
\n
new_open_sale_order = None\n
if (delete_line_list):\n
# All Verifications done. Time to clone/create open order\n
new_open_sale_order = newOpenOrder(open_sale_order)\n
if manual_archive == True:\n
open_sale_order.archive()\n
\n
open_order_explanation = ""\n
# Remove lines\n
new_open_sale_order.deleteContent(delete_line_list)\n
open_order_explanation += "Removed %s." % str(delete_line_list)\n
\n
storeWorkflowComment(new_open_sale_order, open_order_explanation)\n
]]></string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
if kw.get('created_by_builder', 0):
return
context.newContent(portal_type='Sale Invoice Transaction Line',
id='income',)
context.newContent(portal_type='Sale Invoice Transaction Line',
id='receivable', )
context.newContent(portal_type='Sale Invoice Transaction Line',
id='collected_vat',)
......@@ -48,19 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>if kw.get(\'created_by_builder\', 0): \n
return\n
\n
context.newContent(portal_type=\'Sale Invoice Transaction Line\',\n
id=\'income\',)\n
context.newContent(portal_type=\'Sale Invoice Transaction Line\',\n
id=\'receivable\', )\n
context.newContent(portal_type=\'Sale Invoice Transaction Line\',\n
id=\'collected_vat\',)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>*args, **kw</string> </value>
......
invoice = context
total_price = invoice.getTotalPrice()
accounting_price = invoice.AccountingTransaction_getTotalCredit()
precision = invoice.getPriceCurrencyValue().getQuantityPrecision()
return round(total_price, precision) == round(accounting_price, precision)
......@@ -48,16 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>invoice = context\n
\n
total_price = invoice.getTotalPrice()\n
accounting_price = invoice.AccountingTransaction_getTotalCredit()\n
precision = invoice.getPriceCurrencyValue().getQuantityPrecision()\n
return round(total_price, precision) == round(accounting_price, precision)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
invoice = context
specialise = context.getPortalObject().portal_preferences.getPreferredAggregatedSaleTradeCondition()
if invoice.getSpecialise() != specialise:
raise TypeError('Only invoice specialised by %s shall be checked' % specialise)
if len(invoice.getCausalityRelatedList(portal_type='Cloud Contract')) > 0:
# Nothing to compare
return True
delivery_list = invoice.getCausalityValueList(portal_type='Sale Packing List')
amount = len(delivery_list)
if amount != 1:
raise TypeError('Wrong amount %s of related packing lists' % amount)
delivery = delivery_list[0]
return delivery.getTotalPrice(use='use/trade/sale') == context.getTotalPrice(use='use/trade/sale')
......@@ -48,31 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string encoding="cdata"><![CDATA[
invoice = context\n
specialise = context.getPortalObject().portal_preferences.getPreferredAggregatedSaleTradeCondition()\n
if invoice.getSpecialise() != specialise:\n
raise TypeError(\'Only invoice specialised by %s shall be checked\' % specialise)\n
\n
if len(invoice.getCausalityRelatedList(portal_type=\'Cloud Contract\')) > 0:\n
# Nothing to compare\n
return True\n
\n
\n
delivery_list = invoice.getCausalityValueList(portal_type=\'Sale Packing List\')\n
amount = len(delivery_list)\n
if amount != 1:\n
raise TypeError(\'Wrong amount %s of related packing lists\' % amount)\n
delivery = delivery_list[0]\n
\n
return delivery.getTotalPrice(use=\'use/trade/sale\') == context.getTotalPrice(use=\'use/trade/sale\')\n
]]></string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
specialise = context.getSpecialiseValue(portal_type='Sale Trade Condition')
amount_list = specialise.getAggregatedAmountList(context)
if len(amount_list) != 1:
return False
precision = context.getPriceCurrencyValue().getQuantityPrecision()
amount = amount_list[0]
total_price = amount.getTotalPrice()
invoice_tax = 0.
for line in context.getMovementList(context.getPortalInvoiceMovementTypeList()):
if line.getUse() == 'trade/tax':
invoice_tax += line.getTotalPrice()
return round(total_price, precision) == round(invoice_tax, precision)
......@@ -48,27 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>specialise = context.getSpecialiseValue(portal_type=\'Sale Trade Condition\')\n
amount_list = specialise.getAggregatedAmountList(context)\n
if len(amount_list) != 1:\n
return False\n
\n
precision = context.getPriceCurrencyValue().getQuantityPrecision()\n
\n
amount = amount_list[0]\n
\n
total_price = amount.getTotalPrice()\n
\n
invoice_tax = 0.\n
for line in context.getMovementList(context.getPortalInvoiceMovementTypeList()):\n
if line.getUse() == \'trade/tax\':\n
invoice_tax += line.getTotalPrice()\n
\n
return round(total_price, precision) == round(invoice_tax, precision)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
from DateTime import DateTime
restrictedTraverse = context.getPortalObject().restrictedTraverse
person = context.getDestination()
reference = context.getReference()
input_movement_list = [restrictedTraverse(q) for q in
related_simulation_movement_path_list
if restrictedTraverse(q).getDestination() == person]
for delivery_line in input_movement_list:
delivery_line.setGroupingReference(reference)
if context.getCausalityState() == 'draft':
context.startBuilding()
if context.getStartDate() is None:
context.setStartDate(DateTime().earliestTime())
......@@ -48,25 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from DateTime import DateTime\n
restrictedTraverse = context.getPortalObject().restrictedTraverse\n
person = context.getDestination()\n
reference = context.getReference()\n
input_movement_list = [restrictedTraverse(q) for q in\n
related_simulation_movement_path_list\n
if restrictedTraverse(q).getDestination() == person]\n
\n
for delivery_line in input_movement_list:\n
delivery_line.setGroupingReference(reference)\n
if context.getCausalityState() == \'draft\':\n
context.startBuilding()\n
\n
if context.getStartDate() is None:\n
context.setStartDate(DateTime().earliestTime())\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>related_simulation_movement_path_list, *args, **kwargs</string> </value>
......
......@@ -48,11 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>return {\'price\': 0.0}\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>default=None, movement=None, REQUEST=None, **kw</string> </value>
......
from Products.ERP5Type.DateUtils import addToDate
from Products.ZSQLCatalog.SQLCatalog import Query
from DateTime import DateTime
portal = context.getPortalObject()
portal.portal_catalog.searchAndActivate(
portal_type='Sale Invoice Transaction',
simulation_state='confirmed',
causality_state='solved',
creation_date=Query(creation_date=addToDate(DateTime(), to_add={'day': -20}), range="min"),
method_id='SaleInvoiceTransaction_generateResourceConsumptionDocument',
activity_count=1,
packet_size=1,
activate_kw={'tag': tag}
)
context.activate(after_tag=tag, priority=5).getId()
......@@ -48,26 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from Products.ERP5Type.DateUtils import addToDate\n
from Products.ZSQLCatalog.SQLCatalog import Query\n
from DateTime import DateTime\n
\n
portal = context.getPortalObject()\n
portal.portal_catalog.searchAndActivate(\n
portal_type=\'Sale Invoice Transaction\',\n
simulation_state=\'confirmed\',\n
causality_state=\'solved\',\n
creation_date=Query(creation_date=addToDate(DateTime(), to_add={\'day\': -20}), range="min"),\n
method_id=\'SaleInvoiceTransaction_generateResourceConsumptionDocument\',\n
activity_count=1,\n
packet_size=1,\n
activate_kw={\'tag\': tag}\n
)\n
context.activate(after_tag=tag, priority=5).getId()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>tag, fixit, params</string> </value>
......
cpu_resource = context.service_module.cpu_load_percent
memory_resource = context.service_module.memory_used
disk_resource = context.service_module.disk_used
return [(cpu_resource.getTitle(), cpu_resource.getUid()),
(disk_resource.getTitle(), disk_resource.getUid()),
(memory_resource.getTitle(), memory_resource.getUid())]
......@@ -48,17 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>cpu_resource = context.service_module.cpu_load_percent\n
memory_resource = context.service_module.memory_used\n
disk_resource = context.service_module.disk_used\n
\n
return [(cpu_resource.getTitle(), cpu_resource.getUid()),\n
(disk_resource.getTitle(), disk_resource.getUid()),\n
(memory_resource.getTitle(), memory_resource.getUid())]\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
from Products.ERP5Type.DateUtils import addToDate
from DateTime import DateTime
from Products.ZSQLCatalog.SQLCatalog import Query
portal = context.getPortalObject()
for key in ['portal_type', 'sort_on']:
if key in query_kw:
query_kw.pop(key)
#if not 'limit' in query_kw:
# query_kw['limit'] = 31 # limit is for one month by default
if grouping_reference is not None:
query_kw['grouping_reference'] = grouping_reference
sale_packing_list = portal.portal_catalog.getResultValue(
portal_type='Sale Packing List',
reference=grouping_reference,
)
if not sale_packing_list: # Strange cannot find this packing list ?
return []
min_date = sale_packing_list.getStopDate()
min_date = addToDate(min_date, dict(day=-31)) # Get max 31 (one accounting period) latest published consumption lines
query_kw['movement.start_date'] = Query(range="min",
**{'movement.start_date': min_date})
cpu_resource_uid = context.service_module.cpu_load_percent.getUid()
memory_resource_uid = context.service_module.memory_used.getUid()
consumption_dict = {}
def getPackingListLineForResource(resource_uid_list):
return portal.portal_catalog(
portal_type="Sale Packing List Line",
default_resource_uid = resource_uid_list,
**query_kw
)
def setDetailLine(packing_list_line):
start_date = DateTime(packing_list_line.getStartDate()).strftime('%Y/%m/%d')
hosting_reference = packing_list_line.getAggregateReference(
portal_type='Hosting Subscription')
hosting_title = packing_list_line.getAggregateTitle(
portal_type='Hosting Subscription')
software_instance = packing_list_line.getAggregateValue(
portal_type='Software Instance')
if software_instance is None:
# In case we found SPL line not aggregated to instance and hosting
return
instance_reference = software_instance.getReference()
#default_line = {'date': {'hosting_ref': ['hs_title', {'instance_ref': ['inst_title', ['res1', 'res2', 'resN'] ] } ] } }
if not start_date in consumption_dict:
# Add new date line
consumption_dict[start_date] = {hosting_reference:
[hosting_title,
{instance_reference:
[software_instance.getTitle(),
[0.0, 0.0]
]
}
]
}
# Add new Hosting line
if not hosting_reference in consumption_dict[start_date]:
consumption_dict[start_date][hosting_reference] = [hosting_title,
{instance_reference:
[software_instance.getTitle(),
[0.0, 0.0]
]
}
]
# Add new instance line
if not instance_reference in consumption_dict[start_date][hosting_reference][1]:
consumption_dict[start_date][hosting_reference][1][instance_reference] = [
software_instance.getTitle(), [0.0, 0.0]
]
if packing_list_line.getResourceUid() == cpu_resource_uid:
quantity = round(float(packing_list_line.getQuantity()), 3)
consumption_dict[start_date][hosting_reference][1][instance_reference][1][0] = quantity
elif packing_list_line.getResourceUid() == memory_resource_uid:
quantity = round( (float(packing_list_line.getQuantity())/1024.0), 3)
consumption_dict[start_date][hosting_reference][1][instance_reference][1][1] = quantity
# Add CPU_LOAD consumption details
for packing_list_line in getPackingListLineForResource([cpu_resource_uid,
memory_resource_uid]):
setDetailLine(packing_list_line)
consumption_list = []
for date in sorted(consumption_dict):
for hosting_key in sorted(consumption_dict[date]):
hosting_title, instance_dict = consumption_dict[date][hosting_key]
for instance_value_list in instance_dict.values():
instance_title, values = instance_value_list
consumption_list.append([date, hosting_title, instance_title, values[0], values[1]])
return consumption_list
......@@ -48,107 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from Products.ERP5Type.DateUtils import addToDate\n
from DateTime import DateTime\n
from Products.ZSQLCatalog.SQLCatalog import Query\n
\n
portal = context.getPortalObject()\n
\n
for key in [\'portal_type\', \'sort_on\']:\n
if key in query_kw:\n
query_kw.pop(key)\n
#if not \'limit\' in query_kw:\n
# query_kw[\'limit\'] = 31 # limit is for one month by default\n
if grouping_reference is not None:\n
query_kw[\'grouping_reference\'] = grouping_reference\n
\n
sale_packing_list = portal.portal_catalog.getResultValue(\n
portal_type=\'Sale Packing List\',\n
reference=grouping_reference,\n
)\n
if not sale_packing_list: # Strange cannot find this packing list ?\n
return []\n
min_date = sale_packing_list.getStopDate()\n
min_date = addToDate(min_date, dict(day=-31)) # Get max 31 (one accounting period) latest published consumption lines\n
\n
query_kw[\'movement.start_date\'] = Query(range="min",\n
**{\'movement.start_date\': min_date})\n
\n
cpu_resource_uid = context.service_module.cpu_load_percent.getUid()\n
memory_resource_uid = context.service_module.memory_used.getUid()\n
consumption_dict = {}\n
\n
def getPackingListLineForResource(resource_uid_list):\n
return portal.portal_catalog(\n
portal_type="Sale Packing List Line",\n
default_resource_uid = resource_uid_list,\n
**query_kw\n
)\n
\n
def setDetailLine(packing_list_line):\n
start_date = DateTime(packing_list_line.getStartDate()).strftime(\'%Y/%m/%d\')\n
hosting_reference = packing_list_line.getAggregateReference(\n
portal_type=\'Hosting Subscription\')\n
hosting_title = packing_list_line.getAggregateTitle(\n
portal_type=\'Hosting Subscription\')\n
software_instance = packing_list_line.getAggregateValue(\n
portal_type=\'Software Instance\')\n
if software_instance is None:\n
# In case we found SPL line not aggregated to instance and hosting\n
return\n
instance_reference = software_instance.getReference()\n
#default_line = {\'date\': {\'hosting_ref\': [\'hs_title\', {\'instance_ref\': [\'inst_title\', [\'res1\', \'res2\', \'resN\'] ] } ] } }\n
if not start_date in consumption_dict:\n
# Add new date line\n
consumption_dict[start_date] = {hosting_reference: \n
[hosting_title, \n
{instance_reference: \n
[software_instance.getTitle(), \n
[0.0, 0.0]\n
]\n
}\n
]\n
}\n
# Add new Hosting line\n
if not hosting_reference in consumption_dict[start_date]:\n
consumption_dict[start_date][hosting_reference] = [hosting_title, \n
{instance_reference: \n
[software_instance.getTitle(), \n
[0.0, 0.0]\n
]\n
}\n
]\n
# Add new instance line\n
if not instance_reference in consumption_dict[start_date][hosting_reference][1]:\n
consumption_dict[start_date][hosting_reference][1][instance_reference] = [\n
software_instance.getTitle(), [0.0, 0.0]\n
]\n
if packing_list_line.getResourceUid() == cpu_resource_uid:\n
quantity = round(float(packing_list_line.getQuantity()), 3)\n
consumption_dict[start_date][hosting_reference][1][instance_reference][1][0] = quantity\n
elif packing_list_line.getResourceUid() == memory_resource_uid:\n
quantity = round( (float(packing_list_line.getQuantity())/1024.0), 3)\n
consumption_dict[start_date][hosting_reference][1][instance_reference][1][1] = quantity\n
\n
\n
# Add CPU_LOAD consumption details\n
for packing_list_line in getPackingListLineForResource([cpu_resource_uid,\n
memory_resource_uid]):\n
setDetailLine(packing_list_line)\n
\n
consumption_list = []\n
for date in sorted(consumption_dict):\n
for hosting_key in sorted(consumption_dict[date]):\n
hosting_title, instance_dict = consumption_dict[date][hosting_key]\n
for instance_value_list in instance_dict.values():\n
instance_title, values = instance_value_list\n
consumption_list.append([date, hosting_title, instance_title, values[0], values[1]])\n
\n
return consumption_list\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>grouping_reference=None, **query_kw</string> </value>
......
portal = context.getPortalObject()
if context.getPortalType() == "Computer":
# Get the Latest Sale Packing List
sale_packing_list_line = portal.portal_catalog.getResultValue(
portal_type='Sale Packing List Line',
simulation_state='delivered',
sort_on=[('movement.start_date', 'DESC')],
aggregate_uid=context.getUid(),
limit=1)
if sale_packing_list_line is not None:
sale_packing_list = sale_packing_list_line.getParent()
#request = context.getPortalObject().REQUEST
return sale_packing_list.Base_redirect('Base_viewListMode?proxy_form_id=SalePackingList_view&proxy_field_id=listbox')
# Redirect to web site to hide the indexation process
context.Base_redirect('view', keep_items={'portal_status_message':context.Base_translateString('No Consumption Report for this computer.')})
......@@ -48,34 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string encoding="cdata"><![CDATA[
portal = context.getPortalObject()\n
\n
if context.getPortalType() == "Computer":\n
\n
# Get the Latest Sale Packing List\n
sale_packing_list_line = portal.portal_catalog.getResultValue(\n
portal_type=\'Sale Packing List Line\',\n
simulation_state=\'delivered\',\n
sort_on=[(\'movement.start_date\', \'DESC\')],\n
aggregate_uid=context.getUid(),\n
limit=1)\n
\n
if sale_packing_list_line is not None:\n
sale_packing_list = sale_packing_list_line.getParent()\n
\n
#request = context.getPortalObject().REQUEST\n
return sale_packing_list.Base_redirect(\'Base_viewListMode?proxy_form_id=SalePackingList_view&proxy_field_id=listbox\')\n
\n
# Redirect to web site to hide the indexation process\n
context.Base_redirect(\'view\', keep_items={\'portal_status_message\':context.Base_translateString(\'No Consumption Report for this computer.\')})\n
]]></string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
from zExceptions import Unauthorized
if REQUEST is not None:
raise Unauthorized
document = context
portal = document.getPortalObject()
result = []
if context.getValidationState() in ["cancelled", "shared"]:
return
try:
tioxml_dict = document.ComputerConsumptionTioXMLFile_parseXml()
except KeyError:
document.reject(comment="Fail")
return
if tioxml_dict is None:
document.reject(comment="Not usable TioXML data")
else:
computer = context.getContributorValue(portal_type="Computer")
delivery_title = tioxml_dict['title']
movement_list = []
for movement in tioxml_dict["movement"]:
reference = movement['reference']
# It had been reported for the computer itself so it is pure
# informative.
if computer.getReference() == reference:
aggregate_value_list = [computer]
person = computer.getSourceAdministrationValue(portal_type="Person")
else:
if reference.startswith("slapuser"):
reference = reference.replace("slapuser", "slappart")
# Find the partition / software instance / user
partition = portal.portal_catalog.getResultValue(
parent_uid=computer.getUid(),
reference=reference,
portal_type="Computer Partition",
validation_state="validated")
if partition.getSlapState() != 'busy':
continue
assert partition.getSlapState() == 'busy', "partition %s is not busy" % reference
instance = portal.portal_catalog.getResultValue(
default_aggregate_uid=partition.getUid(),
portal_type="Software Instance",
validation_state="validated")
if instance is None:
# There is no software instance for this partition anymore
# so we just skip this partial consumption.
continue
subscription = instance.getSpecialiseValue(
portal_type="Hosting Subscription")
try:
person = subscription.getDestinationSectionValue(
portal_type="Person")
except:
raise ValueError(instance.getRelativeUrl())
aggregate_value_list = [partition, instance, subscription]
movement_list.append(dict(
title=movement['title'],
quantity=movement['quantity'],
aggregate_value_list=aggregate_value_list,
resource=movement['resource'],
person=person.getRelativeUrl()
)
)
# Time to create the PL
person = computer.getSourceAdministrationValue(portal_type="Person")
delivery_template = portal.restrictedTraverse(
portal.portal_preferences.getPreferredInstanceDeliveryTemplate())
delivery = delivery_template.Base_createCloneDocument(batch_mode=1)
delivery.edit(
title=delivery_title,
destination=person.getRelativeUrl(),
destination_decision=person.getRelativeUrl(),
start_date=context.getCreationDate(),
)
for movement in movement_list:
service = portal.restrictedTraverse(movement['resource'])
delivery.newContent(
portal_type="Sale Packing List Line",
title=movement['title'],
quantity=movement['quantity'],
aggregate_value_list=movement['aggregate_value_list'],
destination=movement['person'],
destination_decision=movement['person'],
destination_section=movement['person'],
resource_value=service,
quantity_unit=service.getQuantityUnit(),
)
delivery.confirm(comment="Created from %s" % context.getRelativeUrl())
delivery.start()
delivery.stop()
delivery.deliver()
delivery.startBuilding()
result.append(delivery.getRelativeUrl())
document.share(comment="Created packing list: %s" % result)
return result
......@@ -48,124 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from zExceptions import Unauthorized\n
if REQUEST is not None:\n
raise Unauthorized\n
\n
document = context\n
portal = document.getPortalObject()\n
result = []\n
\n
if context.getValidationState() in ["cancelled", "shared"]:\n
return\n
\n
try:\n
tioxml_dict = document.ComputerConsumptionTioXMLFile_parseXml()\n
except KeyError:\n
document.reject(comment="Fail")\n
return \n
\n
if tioxml_dict is None:\n
document.reject(comment="Not usable TioXML data")\n
else:\n
\n
computer = context.getContributorValue(portal_type="Computer")\n
delivery_title = tioxml_dict[\'title\']\n
\n
movement_list = []\n
for movement in tioxml_dict["movement"]:\n
reference = movement[\'reference\']\n
\n
# It had been reported for the computer itself so it is pure\n
# informative.\n
if computer.getReference() == reference:\n
aggregate_value_list = [computer]\n
person = computer.getSourceAdministrationValue(portal_type="Person")\n
else:\n
if reference.startswith("slapuser"):\n
reference = reference.replace("slapuser", "slappart") \n
# Find the partition / software instance / user\n
partition = portal.portal_catalog.getResultValue(\n
parent_uid=computer.getUid(),\n
reference=reference,\n
portal_type="Computer Partition",\n
validation_state="validated")\n
\n
if partition.getSlapState() != \'busy\':\n
continue\n
\n
assert partition.getSlapState() == \'busy\', "partition %s is not busy" % reference\n
\n
instance = portal.portal_catalog.getResultValue(\n
default_aggregate_uid=partition.getUid(),\n
portal_type="Software Instance",\n
validation_state="validated")\n
\n
if instance is None:\n
# There is no software instance for this partition anymore\n
# so we just skip this partial consumption.\n
continue\n
\n
subscription = instance.getSpecialiseValue(\n
portal_type="Hosting Subscription")\n
\n
try:\n
person = subscription.getDestinationSectionValue(\n
portal_type="Person")\n
except:\n
raise ValueError(instance.getRelativeUrl())\n
\n
aggregate_value_list = [partition, instance, subscription]\n
\n
movement_list.append(dict(\n
title=movement[\'title\'],\n
quantity=movement[\'quantity\'],\n
aggregate_value_list=aggregate_value_list,\n
resource=movement[\'resource\'],\n
person=person.getRelativeUrl()\n
)\n
)\n
\n
# Time to create the PL\n
person = computer.getSourceAdministrationValue(portal_type="Person")\n
delivery_template = portal.restrictedTraverse(\n
portal.portal_preferences.getPreferredInstanceDeliveryTemplate())\n
delivery = delivery_template.Base_createCloneDocument(batch_mode=1)\n
\n
delivery.edit(\n
title=delivery_title,\n
destination=person.getRelativeUrl(),\n
destination_decision=person.getRelativeUrl(),\n
start_date=context.getCreationDate(),\n
)\n
\n
for movement in movement_list:\n
service = portal.restrictedTraverse(movement[\'resource\'])\n
delivery.newContent(\n
portal_type="Sale Packing List Line",\n
title=movement[\'title\'],\n
quantity=movement[\'quantity\'],\n
aggregate_value_list=movement[\'aggregate_value_list\'],\n
destination=movement[\'person\'],\n
destination_decision=movement[\'person\'],\n
destination_section=movement[\'person\'],\n
resource_value=service,\n
quantity_unit=service.getQuantityUnit(),\n
)\n
delivery.confirm(comment="Created from %s" % context.getRelativeUrl())\n
delivery.start()\n
delivery.stop()\n
delivery.deliver()\n
delivery.startBuilding()\n
\n
result.append(delivery.getRelativeUrl())\n
document.share(comment="Created packing list: %s" % result)\n
\n
return result\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>REQUEST=None</string> </value>
......
from zExceptions import Unauthorized
if REQUEST is not None:
raise Unauthorized
portal = context.getPortalObject()
computer = context
reference = "TIOCONS-%s-%s" % (computer.getReference(), source_reference)
version = "%s" % context.getPortalObject().portal_ids.generateNewId(
id_group=('slap_tioxml_consumption_reference', reference), default=1)
document = portal.consumption_document_module.newContent(
portal_type="Computer Consumption TioXML File",
source_reference=source_reference,
title="%s consumption (%s)" % (computer.getReference(), source_reference),
reference=reference,
version=version,
data=consumption_xml,
classification="personal",
publication_section="other",
contributor_value=computer,
)
document.submit()
return document.getRelativeUrl()
......@@ -48,34 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from zExceptions import Unauthorized\n
if REQUEST is not None:\n
raise Unauthorized\n
\n
portal = context.getPortalObject()\n
computer = context\n
\n
reference = "TIOCONS-%s-%s" % (computer.getReference(), source_reference)\n
version = "%s" % context.getPortalObject().portal_ids.generateNewId(\n
id_group=(\'slap_tioxml_consumption_reference\', reference), default=1)\n
\n
document = portal.consumption_document_module.newContent(\n
portal_type="Computer Consumption TioXML File",\n
source_reference=source_reference,\n
title="%s consumption (%s)" % (computer.getReference(), source_reference),\n
reference=reference,\n
version=version,\n
data=consumption_xml,\n
classification="personal",\n
publication_section="other",\n
contributor_value=computer,\n
)\n
document.submit()\n
return document.getRelativeUrl()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>source_reference, consumption_xml, REQUEST=None</string> </value>
......
resource_uid = context.service_module.cpu_load_percent.getUid()
return context.HostingSubscription_getStatForResource(resource_uid, **kw)
......@@ -48,13 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>resource_uid = context.service_module.cpu_load_percent.getUid()\n
\n
return context.HostingSubscription_getStatForResource(resource_uid, **kw)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>**kw</string> </value>
......
resource_uid = context.service_module.disk_used.getUid()
return context.HostingSubscription_getStatForResource(resource_uid, **kw)
......@@ -48,13 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>resource_uid = context.service_module.disk_used.getUid()\n
\n
return context.HostingSubscription_getStatForResource(resource_uid, **kw)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>**kw</string> </value>
......
resource_uid = context.service_module.memory_used.getUid()
return context.HostingSubscription_getStatForResource(resource_uid, **kw)
......@@ -48,13 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>resource_uid = context.service_module.memory_used.getUid()\n
\n
return context.HostingSubscription_getStatForResource(resource_uid, **kw)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>**kw</string> </value>
......
from DateTime import DateTime
from Products.ZSQLCatalog.SQLCatalog import Query
from Products.ERP5Type.Document import newTempDocument
portal = context.getPortalObject()
start_date = query_kw.pop('start_date', None)
stop_date = query_kw.pop('stop_date', None)
software_instance_uid = query_kw.pop('software_instance', None)
hosting_subscription_uid = query_kw.pop('hosting_subscription_uid', None)
resource_uid = query_kw.pop('resource_service', None)
comparison_operator = query_kw.pop('resource_operator', None)
resource_value = query_kw.pop('resource_value', None)
if not software_instance_uid and not hosting_subscription_uid:
return []
if start_date:
query_kw['movement.start_date'] = dict(range='min', query=start_date)
if stop_date:
query_kw['movement.stop_date'] = dict(range='ngt',
query=stop_date.latestTime())
if software_instance_uid and software_instance_uid != 'all':
query_kw['aggregate_uid'] = software_instance_uid
elif hosting_subscription_uid and hosting_subscription_uid != 'all':
query_kw['aggregate_uid'] = hosting_subscription_uid
elif context.getPortalType() == 'Person':
validation_state = query_kw.pop('hosting_validation_state', None)
hosting_uid_list = []
for subscription in portal.portal_catalog(
portal_type='Hosting Subscription',
validation_state=validation_state,
default_destination_section_uid=context.getUid()):
if validation_state == 'validated' and subscription.getSlapState() == 'destroy_requested':
continue
if validation_state == 'archived' and subscription.getSlapState() != 'destroy_requested':
continue
hosting_uid_list.append(subscription.getUid())
if hosting_uid_list:
query_kw['aggregate_uid'] = hosting_uid_list
else:
return []
elif context.getPortalType() in ['Software Instance', 'Hosting Subscription',
'Computer']:
query_kw['aggregate_uid'] = context.getUid()
else:
return []
cpu_resource_uid = context.service_module.cpu_load_percent.getUid()
memory_resource_uid = context.service_module.memory_used.getUid()
disk_resource_uid = context.service_module.disk_used.getUid()
resource_uid_list = [cpu_resource_uid, memory_resource_uid, disk_resource_uid]
if resource_uid and comparison_operator and resource_value:
resource_uid_list = [resource_uid]
query_kw['quantity'] = dict(quantity=resource_value, range=comparison_operator)
consumption_dict = {}
def getPackingListLineForResource(resource_uid_list):
return portal.portal_catalog(
portal_type="Sale Packing List Line",
default_resource_uid = resource_uid_list,
**query_kw
)
def setDetailLine(packing_list_line):
start_date = DateTime(packing_list_line.getStartDate()).strftime('%Y/%m/%d')
hosting_s = packing_list_line.getAggregateValue(
portal_type='Hosting Subscription')
software_instance = packing_list_line.getAggregateValue(
portal_type='Software Instance')
computer_partition = packing_list_line.getAggregateValue(
portal_type='Computer Partition')
if software_instance is None:
# In case we found SPL line not aggregated to instance and hosting
return
hosting_reference = hosting_s.getReference()
instance_reference = software_instance.getReference()
computer_title = ""
if computer_partition is not None:
computer = computer_partition.getParent()
computer_title = computer.getTitle() if computer.getCpuCore() is None else '%s (%s CPU Cores)' % (computer.getTitle(), computer.getCpuCore())
#default_line = {'date': {'hosting_ref': ['hs_title', {'instance_ref': ['inst_title', ['res1', 'res2', 'resN'] ] } ] } }
if not start_date in consumption_dict:
# Add new date line
consumption_dict[start_date] = {hosting_reference:
[hosting_s.getTitle(),
{instance_reference:
[software_instance.getTitle(),
[0.0, 0.0, 0.0],
software_instance.getRelativeUrl(),
computer_title
]
},
hosting_s.getRelativeUrl()
]
}
# Add new Hosting line
if not hosting_reference in consumption_dict[start_date]:
consumption_dict[start_date][hosting_reference] = [hosting_s.getTitle(),
{instance_reference:
[software_instance.getTitle(),
[0.0, 0.0, 0.0],
software_instance.getRelativeUrl(),
computer_title
]
},
hosting_s.getRelativeUrl()
]
# Add new instance line
if not instance_reference in consumption_dict[start_date][hosting_reference][1]:
consumption_dict[start_date][hosting_reference][1][instance_reference] = [
software_instance.getTitle(), [0.0, 0.0, 0.0], software_instance.getRelativeUrl(),
computer_title
]
if packing_list_line.getResourceUid() == cpu_resource_uid:
quantity = round(float(packing_list_line.getQuantity()), 3)
consumption_dict[start_date][hosting_reference][1][instance_reference][1][0] = quantity
elif packing_list_line.getResourceUid() == memory_resource_uid:
quantity = round( float(packing_list_line.getQuantity()), 3)
consumption_dict[start_date][hosting_reference][1][instance_reference][1][1] = quantity
elif packing_list_line.getResourceUid() == disk_resource_uid:
quantity = round( float(packing_list_line.getQuantity()), 3)
consumption_dict[start_date][hosting_reference][1][instance_reference][1][2] = quantity
# Add CPU_LOAD consumption details
for packing_list_line in getPackingListLineForResource(resource_uid_list):
setDetailLine(packing_list_line)
consumption_list = []
i = 1
# Sort on movement.start_date in catalog doesn't work !
for date in sorted(consumption_dict, reverse=True):
for hosting_key in sorted(consumption_dict[date]):
hosting_title, instance_dict, hs_url = consumption_dict[date][hosting_key]
for instance_value_list in instance_dict.values():
instance_title, values, instance_url, computer_title = instance_value_list
line = newTempDocument(portal, instance_url, uid="%s_%s" % (context.getUid(), i))
line.edit(
title=hosting_title,
start_date=date,
instance_title=instance_title,
cpu_load=values[0],
memory_used=values[1],
disk_used=values[2],
computer_title=computer_title,
hosting_url=hs_url,
instance_url=instance_url
)
consumption_list.append(line)
i += 1
return consumption_list
......@@ -48,164 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from DateTime import DateTime\n
from Products.ZSQLCatalog.SQLCatalog import Query\n
from Products.ERP5Type.Document import newTempDocument\n
\n
portal = context.getPortalObject()\n
\n
start_date = query_kw.pop(\'start_date\', None)\n
stop_date = query_kw.pop(\'stop_date\', None)\n
software_instance_uid = query_kw.pop(\'software_instance\', None)\n
hosting_subscription_uid = query_kw.pop(\'hosting_subscription_uid\', None)\n
resource_uid = query_kw.pop(\'resource_service\', None)\n
comparison_operator = query_kw.pop(\'resource_operator\', None)\n
resource_value = query_kw.pop(\'resource_value\', None)\n
\n
if not software_instance_uid and not hosting_subscription_uid:\n
return []\n
\n
if start_date:\n
query_kw[\'movement.start_date\'] = dict(range=\'min\', query=start_date)\n
if stop_date:\n
query_kw[\'movement.stop_date\'] = dict(range=\'ngt\', \n
query=stop_date.latestTime())\n
\n
if software_instance_uid and software_instance_uid != \'all\':\n
query_kw[\'aggregate_uid\'] = software_instance_uid\n
elif hosting_subscription_uid and hosting_subscription_uid != \'all\':\n
query_kw[\'aggregate_uid\'] = hosting_subscription_uid\n
elif context.getPortalType() == \'Person\':\n
validation_state = query_kw.pop(\'hosting_validation_state\', None)\n
hosting_uid_list = []\n
for subscription in portal.portal_catalog(\n
portal_type=\'Hosting Subscription\',\n
validation_state=validation_state,\n
default_destination_section_uid=context.getUid()):\n
if validation_state == \'validated\' and subscription.getSlapState() == \'destroy_requested\':\n
continue\n
if validation_state == \'archived\' and subscription.getSlapState() != \'destroy_requested\':\n
continue\n
hosting_uid_list.append(subscription.getUid())\n
if hosting_uid_list:\n
query_kw[\'aggregate_uid\'] = hosting_uid_list\n
else:\n
return []\n
elif context.getPortalType() in [\'Software Instance\', \'Hosting Subscription\',\n
\'Computer\']:\n
query_kw[\'aggregate_uid\'] = context.getUid()\n
else:\n
return []\n
\n
cpu_resource_uid = context.service_module.cpu_load_percent.getUid()\n
memory_resource_uid = context.service_module.memory_used.getUid()\n
disk_resource_uid = context.service_module.disk_used.getUid()\n
resource_uid_list = [cpu_resource_uid, memory_resource_uid, disk_resource_uid]\n
if resource_uid and comparison_operator and resource_value:\n
resource_uid_list = [resource_uid]\n
query_kw[\'quantity\'] = dict(quantity=resource_value, range=comparison_operator)\n
\n
consumption_dict = {}\n
\n
def getPackingListLineForResource(resource_uid_list):\n
return portal.portal_catalog(\n
portal_type="Sale Packing List Line",\n
default_resource_uid = resource_uid_list,\n
**query_kw\n
)\n
\n
def setDetailLine(packing_list_line):\n
start_date = DateTime(packing_list_line.getStartDate()).strftime(\'%Y/%m/%d\')\n
hosting_s = packing_list_line.getAggregateValue(\n
portal_type=\'Hosting Subscription\')\n
software_instance = packing_list_line.getAggregateValue(\n
portal_type=\'Software Instance\')\n
computer_partition = packing_list_line.getAggregateValue(\n
portal_type=\'Computer Partition\')\n
if software_instance is None:\n
# In case we found SPL line not aggregated to instance and hosting\n
return\n
hosting_reference = hosting_s.getReference()\n
instance_reference = software_instance.getReference()\n
computer_title = ""\n
if computer_partition is not None:\n
computer = computer_partition.getParent()\n
computer_title = computer.getTitle() if computer.getCpuCore() is None else \'%s (%s CPU Cores)\' % (computer.getTitle(), computer.getCpuCore())\n
#default_line = {\'date\': {\'hosting_ref\': [\'hs_title\', {\'instance_ref\': [\'inst_title\', [\'res1\', \'res2\', \'resN\'] ] } ] } }\n
if not start_date in consumption_dict:\n
# Add new date line\n
consumption_dict[start_date] = {hosting_reference: \n
[hosting_s.getTitle(), \n
{instance_reference: \n
[software_instance.getTitle(), \n
[0.0, 0.0, 0.0],\n
software_instance.getRelativeUrl(),\n
computer_title\n
]\n
},\n
hosting_s.getRelativeUrl()\n
]\n
}\n
# Add new Hosting line\n
if not hosting_reference in consumption_dict[start_date]:\n
consumption_dict[start_date][hosting_reference] = [hosting_s.getTitle(),\n
{instance_reference: \n
[software_instance.getTitle(), \n
[0.0, 0.0, 0.0],\n
software_instance.getRelativeUrl(),\n
computer_title\n
]\n
},\n
hosting_s.getRelativeUrl()\n
]\n
# Add new instance line\n
if not instance_reference in consumption_dict[start_date][hosting_reference][1]:\n
consumption_dict[start_date][hosting_reference][1][instance_reference] = [\n
software_instance.getTitle(), [0.0, 0.0, 0.0], software_instance.getRelativeUrl(),\n
computer_title\n
]\n
if packing_list_line.getResourceUid() == cpu_resource_uid:\n
quantity = round(float(packing_list_line.getQuantity()), 3)\n
consumption_dict[start_date][hosting_reference][1][instance_reference][1][0] = quantity\n
elif packing_list_line.getResourceUid() == memory_resource_uid:\n
quantity = round( float(packing_list_line.getQuantity()), 3)\n
consumption_dict[start_date][hosting_reference][1][instance_reference][1][1] = quantity\n
elif packing_list_line.getResourceUid() == disk_resource_uid:\n
quantity = round( float(packing_list_line.getQuantity()), 3)\n
consumption_dict[start_date][hosting_reference][1][instance_reference][1][2] = quantity\n
\n
# Add CPU_LOAD consumption details\n
for packing_list_line in getPackingListLineForResource(resource_uid_list):\n
setDetailLine(packing_list_line)\n
\n
consumption_list = []\n
i = 1\n
# Sort on movement.start_date in catalog doesn\'t work !\n
for date in sorted(consumption_dict, reverse=True):\n
for hosting_key in sorted(consumption_dict[date]):\n
hosting_title, instance_dict, hs_url = consumption_dict[date][hosting_key]\n
for instance_value_list in instance_dict.values():\n
instance_title, values, instance_url, computer_title = instance_value_list\n
line = newTempDocument(portal, instance_url, uid="%s_%s" % (context.getUid(), i))\n
line.edit(\n
title=hosting_title,\n
start_date=date,\n
instance_title=instance_title,\n
cpu_load=values[0],\n
memory_used=values[1],\n
disk_used=values[2],\n
computer_title=computer_title,\n
hosting_url=hs_url,\n
instance_url=instance_url\n
)\n
consumption_list.append(line)\n
i += 1\n
\n
return consumption_list\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>**query_kw</string> </value>
......
from Products.ZSQLCatalog.SQLCatalog import Query
portal = context.getPortalObject()
query_kw.update(query_kw['selection'].getParams())
start_date = query_kw.pop('start_date', None)
stop_date = query_kw.pop('stop_date', None)
software_instance_uid = query_kw.pop('software_instance', None)
hosting_subscription_uid = query_kw.pop('hosting_subscription_uid', None)
if not software_instance_uid and not hosting_subscription_uid:
return ''
if start_date:
query_kw['movement.start_date'] = dict(range='min', query=start_date)
if stop_date:
query_kw['movement.stop_date'] = dict(range='ngt',
query=stop_date.latestTime())
if software_instance_uid and software_instance_uid != 'all':
query_kw['aggregate_uid'] = software_instance_uid
elif hosting_subscription_uid and hosting_subscription_uid != 'all':
query_kw['aggregate_uid'] = hosting_subscription_uid
elif context.getPortalType() == 'Person':
validation_state = query_kw.pop('hosting_validation_state', 'validated')
hosting_uid_list = []
for subscription in portal.portal_catalog(
portal_type='Hosting Subscription',
validation_state=validation_state,
default_destination_section_uid=context.getUid()):
if validation_state == 'validated' and subscription.getSlapState() == 'destroy_requested':
continue
if validation_state == 'archived' and subscription.getSlapState() != 'destroy_requested':
continue
hosting_uid_list.append(subscription.getUid())
if hosting_uid_list:
query_kw['aggregate_uid'] = hosting_uid_list
else:
return ''
elif context.getPortalType() in ['Software Instance', 'Hosting Subscription']:
query_kw['aggregate_uid'] = context.getUid()
else:
return ''
total_quantity = 0
for packing_list_line in portal.portal_catalog(
portal_type="Sale Packing List Line",
default_resource_uid = resource_uid,
**query_kw
):
total_quantity += float(packing_list_line.getQuantity())
return round(total_quantity, 3)
......@@ -48,62 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>from Products.ZSQLCatalog.SQLCatalog import Query\n
portal = context.getPortalObject()\n
\n
query_kw.update(query_kw[\'selection\'].getParams())\n
start_date = query_kw.pop(\'start_date\', None)\n
stop_date = query_kw.pop(\'stop_date\', None)\n
software_instance_uid = query_kw.pop(\'software_instance\', None)\n
hosting_subscription_uid = query_kw.pop(\'hosting_subscription_uid\', None)\n
\n
if not software_instance_uid and not hosting_subscription_uid:\n
return \'\'\n
\n
if start_date:\n
query_kw[\'movement.start_date\'] = dict(range=\'min\', query=start_date)\n
if stop_date:\n
query_kw[\'movement.stop_date\'] = dict(range=\'ngt\', \n
query=stop_date.latestTime())\n
\n
if software_instance_uid and software_instance_uid != \'all\':\n
query_kw[\'aggregate_uid\'] = software_instance_uid\n
elif hosting_subscription_uid and hosting_subscription_uid != \'all\':\n
query_kw[\'aggregate_uid\'] = hosting_subscription_uid\n
elif context.getPortalType() == \'Person\':\n
validation_state = query_kw.pop(\'hosting_validation_state\', \'validated\')\n
hosting_uid_list = []\n
for subscription in portal.portal_catalog(\n
portal_type=\'Hosting Subscription\',\n
validation_state=validation_state,\n
default_destination_section_uid=context.getUid()):\n
if validation_state == \'validated\' and subscription.getSlapState() == \'destroy_requested\':\n
continue\n
if validation_state == \'archived\' and subscription.getSlapState() != \'destroy_requested\':\n
continue\n
hosting_uid_list.append(subscription.getUid())\n
if hosting_uid_list:\n
query_kw[\'aggregate_uid\'] = hosting_uid_list\n
else:\n
return \'\'\n
elif context.getPortalType() in [\'Software Instance\', \'Hosting Subscription\']:\n
query_kw[\'aggregate_uid\'] = context.getUid()\n
else:\n
return \'\'\n
\n
total_quantity = 0\n
for packing_list_line in portal.portal_catalog(\n
portal_type="Sale Packing List Line",\n
default_resource_uid = resource_uid,\n
**query_kw\n
):\n
total_quantity += float(packing_list_line.getQuantity())\n
\n
return round(total_quantity, 3)\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>resource_uid, **query_kw</string> </value>
......
portal = context.getPortalObject()
invoice = context
document = portal.portal_catalog.getResultValue(
portal_type="User Consumption HTML File",
validation_state="shared",
follow_up_uid=invoice.getUid()
)
if document is None:
document = portal.consumption_document_module.newContent(
portal_type="User Consumption HTML File",
title="Invoice Resource Comsuption %s" % invoice.getTitle(),
reference="INVOICE-RC-%s" % invoice.getReference(),
classification="personal/private",
data=invoice.SaleInvoiceTransaction_getPrintoutResourceContent(),
publication_section="other",
contributor_value=invoice.getDestination(),
follow_up=invoice.getRelativeUrl()
)
document.submit()
document.share()
return document.getRelativeUrl()
......@@ -48,34 +48,6 @@
</object>
</value>
</item>
<item>
<key> <string>_body</string> </key>
<value> <string>portal = context.getPortalObject()\n
invoice = context\n
document = portal.portal_catalog.getResultValue(\n
portal_type="User Consumption HTML File",\n
validation_state="shared",\n
follow_up_uid=invoice.getUid()\n
)\n
\n
if document is None:\n
document = portal.consumption_document_module.newContent(\n
portal_type="User Consumption HTML File",\n
title="Invoice Resource Comsuption %s" % invoice.getTitle(),\n
reference="INVOICE-RC-%s" % invoice.getReference(),\n
classification="personal/private",\n
data=invoice.SaleInvoiceTransaction_getPrintoutResourceContent(),\n
publication_section="other",\n
contributor_value=invoice.getDestination(),\n
follow_up=invoice.getRelativeUrl()\n
)\n
\n
document.submit()\n
document.share()\n
\n
return document.getRelativeUrl()\n
</string> </value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string></string> </value>
......
......@@ -38,46 +38,6 @@
<tuple/>
</value>
</item>
<item>
<key> <string>_text</string> </key>
<value> <unicode encoding="cdata"><![CDATA[
<tal:block tal:define="aggregated_reference python: context.getCausalityReference(portal_type=\'Sale Packing List\', checked_permission=\'View\');\n
quantity_renderer nocall:here/portal_skins/erp5_trade/Base_viewTradeFieldLibrary/my_view_mode_quantity/render_pdf;\n
resource_details_list python: context.Base_getUserConsumptionDetailList(aggregated_reference)">\n
<aside tal:define="global index python: 0; page_limit python: 36;"\n
tal:condition="python: aggregated_reference and resource_details_list" class="ressource">\n
<h1><span>Resource Consumption Details</span></h1>\n
<table class="resource">\n
<thead>\n
<tr>\n
<th><span>N&#x00b0;</span></th>\n
<th><span>Date</span></th>\n
<th><span>Hosting Subscription</span></th>\n
<th><span>Instance Name</span></th>\n
<th><span>CPU Load</span></th>\n
<th><span>Memory Used</span></th>\n
</tr>\n
</thead>\n
<tbody>\n
<tal:block tal:repeat="item_list python: resource_details_list">\n
<tal:block tal:define="global index python: index + 1"></tal:block>\n
<tr tal:attributes="class python: \'page-break\' if (index % page_limit) == 0 else \'\'">\n
<td tal:content="python: index"></td>\n
<td tal:content="python: item_list[0]"></td>\n
<td tal:content="python: item_list[1]"></td>\n
<td tal:content="python: item_list[2]"></td>\n
<td tal:content="python: quantity_renderer(item_list[3]) + \' %\'"></td>\n
<td tal:content="python: quantity_renderer(item_list[4]) + \' GB\'"></td>\n
</tr>\n
</tal:block>\n
</tbody>\n
</table>\n
</aside>\n
</tal:block>
]]></unicode> </value>
</item>
<item>
<key> <string>content_type</string> </key>
<value> <string>text/html</string> </value>
......
<tal:block tal:define="aggregated_reference python: context.getCausalityReference(portal_type='Sale Packing List', checked_permission='View');
quantity_renderer nocall:here/portal_skins/erp5_trade/Base_viewTradeFieldLibrary/my_view_mode_quantity/render_pdf;
resource_details_list python: context.Base_getUserConsumptionDetailList(aggregated_reference)">
<aside tal:define="global index python: 0; page_limit python: 36;"
tal:condition="python: aggregated_reference and resource_details_list" class="ressource">
<h1><span>Resource Consumption Details</span></h1>
<table class="resource">
<thead>
<tr>
<th><span>N&#x00b0;</span></th>
<th><span>Date</span></th>
<th><span>Hosting Subscription</span></th>
<th><span>Instance Name</span></th>
<th><span>CPU Load</span></th>
<th><span>Memory Used</span></th>
</tr>
</thead>
<tbody>
<tal:block tal:repeat="item_list python: resource_details_list">
<tal:block tal:define="global index python: index + 1"></tal:block>
<tr tal:attributes="class python: 'page-break' if (index % page_limit) == 0 else ''">
<td tal:content="python: index"></td>
<td tal:content="python: item_list[0]"></td>
<td tal:content="python: item_list[1]"></td>
<td tal:content="python: item_list[2]"></td>
<td tal:content="python: quantity_renderer(item_list[3]) + ' %'"></td>
<td tal:content="python: quantity_renderer(item_list[4]) + ' GB'"></td>
</tr>
</tal:block>
</tbody>
</table>
</aside>
</tal:block>
\ No newline at end of file
portal = context.getPortalObject()
select_dict= {'default_aggregate_uid': None}
portal.portal_catalog.searchAndActivate(
portal_type=('Slave Instance', 'Software Instance'),
validation_state='validated',
default_aggregate_uid=None,
select_dict=select_dict,
left_join_list=select_dict.keys(),
method_id='SoftwareInstance_requestValidationPayment',
packet_size=1, # Separate calls to many transactions
activate_kw={'tag': tag}
)
context.activate(after_tag=tag).getId()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment