Vertec Python functions

Description of Vertec Python functions

Product line

Standard

|

Expert

Operating mode

CLOUD ABO

|

ON-PREMISES

Modules

Services & CRM

Budget & Phases

Purchases

Resource Planning

Business Intelligence

Created: 04.03.2013
Machine translated
Updated: 15.11.2024 | setdocumentcontent() and setemailcontent() on activity from Vertec 6.7.0.15.

Overview

The module “vtcapp”

The Vertec installation includes a Vertec Python library (module), which is automatically available in the Python scripts after installation and is called vtcapp.

The module has the following methods/features:

Method / feature description Sample code
__doc__
Documentation of a feature.
>>> print vtcapp.__doc__ 
Interface module to host application.
argobject

Up-to-date Vertec object. This variable is always available, so the call can be made without vtcapp..
See also the description in the article Python Scripts.

projekt = argobject
checkcreate(class:string): int

Checks whether the user has the right to create objects of the specified class.

Return value is 0 or 1 (False, True)

>>> print vtcapp.checkcreate('Projekt')
1
checkfeature(featurecode: string): boolean

Checks whether a particular feature is licensed.

The feature codes are according to Vertec feature matrix (e.g. fcPhasen for phases).

Return value is False or True

>>> vtcapp.checkfeature('fcPhasen')
True
convertwordtopdf(wordDoc: string): string

Converts a Word document of type .docx to a PDF.

The corresponding Word document must be created and read:

in_file = open("C:\<yourPath>\BeispielWordFürEmail.docx", "rb")
wordDoc = in_file.read()

Conversion:

pdfDoc = vtcapp.convertwordtopdf(wordDoc)
createoutlookmail(to, subject, body=”“, cc=”“, bcc=”“, attachments=[], show=True, onBehalfOf=”“)

Python method from version 6.4.0.4, which allows to create an email message on the client via Outlook.

Works with the desktop app and the cloud app. If you are working with the web app, the sendmail() method can be used.

  • to: String. Recipient addresses, separated by ;, if several.
  • subject: String. Subject of the email.
  • body:
    • String. The actual email text. Can be HTML or plaintext. HTML is recognized as such and then created as an Outlook HTML Mail.
    • Starting with version 6.5.0.21, a Word document can also be used (see example below).

Optional:

  • body: Optional from version 6.7. If body not specified, an empty string or None, nothing is set in the created email.
  • cc: String, Optional, Keyword*. cc addresses, separated by ;, if more than one.
  • bcc: String, Optional, Keyword*. Bcc addresses, separated by ;, if more than one.
  • attachments: List of tuples, Optional, Keyword. List of attachments as tuple of two strings[(file name, content)], see example below.
  • show: Boolean, Optional, Keyword*. At True, the email is created and shown, at False, the email is saved in the “Drafts” folder and not shown. Default value is True.
  • onBehalfOf: String, Optional. Sends the email with a different sender. Example: vtcapp.createoutlookmail("dokumentation@vertec.com", "Betreff XYZ", onBehalfOf="noreply@vertec.com") opens an email with the sender noreply@vertec.com.

*Keyword means that you can specify the optional values with the parameter as a keyword, e.g. CC="abc@vertec.com". This way you do not need a specific quantity of commas as placeholders for optional values that are not specified.

Examples:

  • Simplest case, body as string:
    vtcapp.createoutlookmail("dokumentation@vertec.com", "Dokumentation", "Dies ist der einfachste Fall")
  • Using Word documents as body:

Note: Use spreadsheets in your Word documents and avoid tab stops because they cannot be processed in the email.

  1. The corresponding Word document must be created and read:
    in_file = open("C:\<yourPath>\BeispielWordFuerEmail.docx", "rb") 
    fileData = in_file.read()
  2. Generate the email with the method:
    vtcapp.createoutlookmail('dokumentation@vertec.com', 'Test E-Mail from Word', fileData)
  • Keywords (show is specified by keyword):
    vtcapp.createoutlookmail("dokumentation@vertec.com", "Dokumentation", "jetzt benutzen wir show per keyword", show=False)
  • Attachments:
    akt = argobject
    attachments=[('File1.txt', 'This is the content of file 1'),('Anhang.pdf', akt.content)] 
    vtcapp.createoutlookmail("dokumentation@vertec.com", "Dokumentation", "Eine E-Mail mit attachments", attachments=attachments, show=False)
    The attachment name cannot be empty.
  • Body in HTML
    html="<html><body><p>Hallo</p><p>Dies ist eine Outlook Nachricht in HTML.</p><p>Es ist ziemlich einfach, verwenden Sie HTML BODY und P (Paragraph) wie hier dargestellt, und schon entsteht eine strukturierte E-Mail.</p><p>Möchten Sie <b>fettgedruckten</b>, <i>kursiven</i>, <u>unterstrichenen</u> Text, verwenden Sie die entsprechenden Tags.<span style=\"color: red\">Sie können auch eine andere Farbe verwenden.</span></p><p>Freundliche Grüsse</p><p>Ihr Vertec Team</p></body></html>" vtcapp.createoutlookmail("dokumentation@vertec.com", "Dokumentation", html)
createlist(classname, [list]): list
From version 6.1.0.14. With this a Vertec list can be created, on which OCL can then be evaluated.
  • classname: the class name of the objects that will be included in the list. The class name is necessary so that the list itself contains static type information and can serve as a basis for evaluating OCL expressions.
  • list (optional): the optional List argument allows the construction of a list directly from another list. If not set, the generated list is empty and can be populated via the append() or extend() method (see list of available methods on Vertec lists).

Starting with version 6.2.0.7 the Python methods evalocl(), getwithsql() and getmemberwithsql() automatically return vertec lists, see Vertec lists.

mylist = vtcapp.createlist('Projekt')
mylist.append(argobject)

or

liste = vtcapp.createlist("Projekt", vtcapp.evalocl("projekt->select(code.sqllike('A%'))"))
liste2 = liste.evalocl("self->select(aktiv)")
createobject(class: string)
Creates new object of the specified class.
leistung = vtcapp.createobject("OffeneLeistung")
currentlogin(): project editor
Up-to-date registered user
>>> bearbeiter = vtcapp.currentlogin()
>>> bearbeiter.name
Christoph Keller
currentobject
See the description in the article Python Scripts.
projekt = currentobject
disableevents()

Starting with Vertec 6.7.0.7 always use Disabledevents() instead.

With disableevents(), the event scripting can be turned off. This then affects the entire Vertec session (other Vertec sessions or desktop apps are not affected).
This feature is used, for example, if you want to modify a certain attribute that would otherwise execute an event.

Can be used with enableevents() re-enabled. Requires extended user rights. Not allowed

in the Python editor for security reasons.    

# Ganzes Script
try:
    vtcapp.disableevents()
    main()
finally:
    vtcapp.enableevents()

# Teil eines Scripts
vtcapp.disableevents()
rechnung.datum = vtcapp.currentdate()
vtcapp.enableevents()
DisabledEvents()

From version 6.7.0.7. Must be with will be called on:

with vtcapp.DisabledEvents():

 Within this method, is turned off, affecting the entire Vertec session (other Vertec sessions or desktop apps are not affected).

Used, for example, to modify a certain attribute that would otherwise execute an event.

Requires extended user rights. Not allowed in the Python editor for security reasons.

with vtcapp.DisabledEvents():
    rechnung.datum = vtcapp.currentdate()
evalocl(expression: string): expressiontype
Evaluate global OCL expression.
projektListe = vtcapp.evalocl("Projekt.allinstances->orderby(code)")
evaloclstring(obj: object, expStr: string): string
Evaluate OCL expression within a string. Return value: fully evaluated string.
>>> vtcapp.evaloclstring(argobject,"Bearbeiter: %name% ist %stufe.asstring%")
Bearbeiter: Christoph Keller ist Senior Consultant
evaltovariable(obj: object, ocl: string, varname: string)
Evaluates an OCL and saves the value in an OCL variable. The variable can then be queried globally with evalocl().

As of version 6.1.0.14, the variable name “self” may no longer be used, since this is a keyword. A corresponding error message appears.

>>> projekt = vtcapp.evalocl("projekt->select(code='TRASTA')->first")
>>> vtcapp.evaltovariable(projekt, "rechnungen->first", "varRechnung")
>>> vtcapp.evalocl("varRechnung")
15070005, TRASTA
>>> projekt.evalocl("varRechnung")
15070005, TRASTA
executefile(command: string, [argumentString: string])

Before 6.4.0.10: executefile(path: string)

Opens a file on the client (without web app). The file path must be accessible from the client.

Starting with version 6.4.0.10, Command Line Parameters are also supported. For this, optional arguments can be passed. The previous simple case still works.

Parameter parsing is as follows:

  • No parsing takes place in command. Spaces are interpreted as part of the path.
  • Parsing takes place in argumentString, where the arguments are separated by spaces, unless they are enclosed in double quotation marks ““.

As of Vertec 6.5.0.11 only files of the type .doc, .docx, .xls, .xlsx, .pdf, .csv, .txt, .zip, .png, .jpg, .jpeg, .bmp, .gif, .eml and from Vertec 6.5.0.15 .ics(same Whitelist as for sendfile()). For all others, a dialog appears asking if Vertec can open the file:

  • If Yes, the path and name of the file are remembered, and the dialog does not appear again when the file is called up again.
    This is done by an entry in the registry in the key: HKEY_CURRENT_USER\Software\Vertec\ExecuteFileWhiteList. Whitelisting refers only to the executable file and path, not to any arguments.
  • If no, there is no write access to this part of the registry and the file cannot be remembered. A warning is written to the Log File (Vertec.Cloud.log or Vertec.Desktop.log)

Examples:

pfad = r'S:\Dokumente\Kontakte\Bistro Cooper\Brief.docx'
vtcapp.executefile(pfad)

The r in front of the path causes control characters to be ignored. Because the backslash is a control character in certain combinations for Python, otherwise the path may be misinterpreted or fragmented and an error may occur.

vtcapp.executefile("calc.exe")

opens the Windows computer.

From 6.4.0.10 also:

vtcapp.executefile('notepad++.exe', r'-lpython "C:\Dokumente\Mein Script.py"')
executefolder(path: string)

Opens the specified folder on the client (without web app), e.g. in Windows Explorer. The path must be accessible from the client.

If the folder does not exist yet, a message will appear whether it should be created:

In a script this has to be queried and the folder has to be created in the code if no message is to appear on the interface. This can be done e.g. via the Python module os (does not work with Restricted Scripting ).

import os
pfad = r'S:\Dokumente\Kontakte\Bistro Cooper'
if os.path.isdir(pfad):
  vtcapp.executefolder(pfad)

The r in front of the path causes control characters to be ignored. Because the backslash is a control character in certain combinations for Python, otherwise the path may be misinterpreted or fragmented and an error may occur.

executereport(rootObj, optarg, reportObj, [saveAs, showDialog, doPrint, showApp]): report

Allows calling and executing Reports based on a report object. For
a table of availability with the different systems, see the executereport() or executeserverwordreport() section below.

  • rootObj: The object on which the report is run. Only a single object can be specified, not a list.
  • optarg: Corresponds to the optional address on the print dialog. Optional argument. If not used, specify parameters with None.
  • reportObj: A Vertec report definition (report class). The report is executed based on this definition.
    • If the report is a Legacy Word Report , you can also specify a path for the Office template instead of the report object.
    • The settings of the report object for Save as and Show dialog can still be overridden via the corresponding arguments of this method.
  • saveAs: Optional. Path to save the report (if Office report). This string can also contain OCL expressions (separated by %).
    • If an empty string is specified, no file is saved.
    • If None is passed, the SaveAs settings are applied from the report object (reportObj).
  • showDialog: Show dialog with save as etc. (if Office report). Optional. Possible values: True or False.
    Starting with version 6.1.0.14, the display of messages like “overwrite existing file” and “create new path” is also controlled by this setting. If this parameter is not set, the corresponding setting is applied from the report object (reportObj).
  • doPrint: Optional. Possible values: True or False. This value is only considered for Office-generated legacy reports prior to version 6.6.0.8. If True, the report will be printed directly without opening the corresponding Office application.        
  • showApp: Specifies whether to show the report open. Optional. Possible values: True or False.

Examples:

Show a Word report for invoice without dialog and without saving a file:

vtcapp.executereport(rech, None, rechTempl, "", showDialog=False)

The variable rechTempl must contain the report object for an invoice, the variable rech the invoice object.

Starting with version 6.4.0.8 the method returns the report output as a byte string (only if reportObj is a Vertec report definition, not if a path is specified). This can be further processed and, for example, attached to an email via vtcapp.createoutlookmail().

rechTempl = vtcapp.evalocl("bericht->select(eintragid='BerichtScriptInvoiceWithList')->first")
pdf = vtcapp.executereport(argobject, None, rechTempl, "", showDialog=False)
vtcapp.createoutlookmail("mail@adresse.com", "Betreffend", "Inhalt", attachments=[('rechnung.pdf', pdf)])
executereport2(rootObj, optarg, reportObj, [saveAs, showDialog, doPrint, showApp]): (report, activity)

Starting with version 6.4.0.22. Allows calling and executing Reports based on a report object.

The method returns a tuple consisting of the report output as a byte string and the associated activity.

For the description of the parameters, see executereport() above. Only a Vertec report definition (class report) can be passed as reportObj, no file paths.

See the executereport() or executeserverwordreport() section below for a table of availability with the different systems.

rechTempl = vtcapp.evalocl("bericht->select(eintragid='BerichtScriptInvoiceWithList')->first")

reportdoc, activity = vtcapp.executereport2(argobject, None, rechTempl)

The return value of the method is a tuple:

  • Content of the resulting report document is (byte string).
  • The created activity object or None

An activity is only created when a report is saved.

executeserverwordreport(rootObj, optarg, templatePath, [outputFormat, saveAs, showDialog, showApp])

Starting with version 6.1.0.11. This method is used to run Vertec-generated legacy word reports without a report object. See the executereport() or executeserverwordreport() section below for
a table of availability with the different systems.

  • rootObj : The object on which the report is run. Only a single object can be specified, no list can be specified.
  • optarg : Corresponds to the optional address on the print dialog. Optional argument. If not used, specify parameters with None.
  • templatePath: A path for the Word template.
  • outputFormat : A string for the output format. Accepted: “DOCX” or “PDF”. Default: “DOCX”
  • saveAs : Path to save the report as a string. This string can also contain OCL expressions (separated by %). If an empty string is specified or the argument is omitted, no file is saved. Default: ““
  • showDialog : Display dialog with save as etc. as boolean. Default: False
  • showApp: : Boolean indicating whether to show the report open. Default: True
vtcapp.executeserverwordreport(argobject, None, r"C:\Program Files (x86)\Vertec\Reports\Deutsch\Brief.dot", "", "C:\\Dokumente\\Vertec\\Test", True, True)
executorl(url)

Opens the specified URL on the client (all full-featured apps).

The URL must be accessible from the client. In the web app, it must be a publicly accessible path; access to the local client is not possible.

For example, to open a website in the browser:

vtcapp.executeurl("https://www.vertec.com")

Or a Vertec Breadcrumb URL:

vtcapp.executeurl("vertec://CK-676/eigene+Projekte-49/COMINSTALL-2880/")

the same works as a short version, in which only the IDs are specified:

vtcapp.executeurl("vertec://676/49/2880/")
fetchlinkmembers(objectlist, membername): objectlist
From version 6.4. Loads the sublist (membername) into memory for a list of objects (objectlist), and at the same time makes the multilink current, which means that the list will not be reloaded when the link is accessed. Therefore, the call should fetchlinkmembers() immediately prior to the re-use of the list.
# Loop durch die Phasen von Projekten, welche mindestens eine Phase "erteilt" haben
projekte = vtcapp.getwithsql("Projekt", "bold_id IN (SELECT projekt FROM projektphase WHERE status=1)", "")
vtcapp.fetchlinkmembers(projekte, "phasen")
for projekt in projekte:
    x = projekt.evalocl("phasen->select(status=1)")
generateinvoicenumber()

Creates the next Vertec invoice number according to the system settings Invoice / Fee Note.

rech = argobject
rech.nummer = vtcapp.generateinvoicenumber()
getcurrentobject()

Returns the object selected in the tree and can be called from Ocl call operators using OCL Call operators.

 
getmailattachment(content, idx): bytestring

From version 6.5. Allows downloading an email attachment of an activity.

Returns the contents of the attachment as a byte string as the return value.

Since the names of the attachments are not necessarily unique, it must be identified by Idx.

filecontent = vtcapp.getmailattachment(activity.content, 0)
outfile.write(filecontent)
outfile.close()
getmailattachments(content): list(string)

Starting with version 6.5. Returns a list of attachment names of an activity.

filename = vtcapp.getmailattachments(activity.content)[0]
outfile = open('C:/data/' + filename, 'wb')
getmemberwithsql(obj: object, membername: string, where: string, order: string): list of objects

Allows querying members of an object via SQL.
The executing user must have administrator rights or the SQL Query right.
For granting temporary administrator rights, the variant of extended permissions is available.

projekt = argobject
li=vtcapp.getmemberwithsql(projekt, "offeneleistungen", "xwertext>200", "") 
print len(li)
>>> 3
getobjectbyentryid(classname: string, entryid: string): object

Starting with version 6.6.0.2. Gets the object with the specified class and Entry Id .

Both parameters must always be specified.

If the class classname does not exist or does not inherit from type Eintrag, an error is thrown.

If no or more objects are found, an error is thrown.

Note: The objects are loaded internally via SQL. Thus, only objects that are already stored in the database are found. For newly created objects, a vtcapp.updatedatabase() so that the object is found using this method.

obj = vtcapp.getobjectbyentryid("Ordner", "FolderPublicProjectBySectors")
getobjectbyid(id: int, string or long*): object

Gets the object with the specified Internal Id .

If the id is not present, an error is thrown.

Note: The objects are loaded internally via SQL. Thus, only objects already stored in the database are found. For newly created objects, first a vtcapp.updatedatabase() so that the object is found using this method.

* Starting with Vertec 6.7.0.4.

obj = vtcapp.getobjectbyid(62162)

or

obj = vtcapp.getobjectbyid("62162")
getpropertyvalue(propname: string): value

Returns the value of the system setting (Property) with the specified name.

The return value depends on the type of the property.

>>> print vtcapp.getpropertyvalue("firma")
LKT Engineering GmbH, Hamburg
getvertecserveraddress(): string

Returns the address at which the Vertec cloud server is available from the internet.

vtcapp.executeurl(vtcapp.getvertecserveraddress())
getwithsql(class: string, where: string, order: string, [idfilterfield: string, objectlist: list]): list of objects

Before version 6.3.0.8:
getwithsql(klasse: string, where: string, order: string): list of objects

 

This global SQL statement is used to filter lists to be filtered in a performance-optimized way directly on the database (see the article Performance-optimized access to vertec objects ).

A call via getwithsql() is only useful if a Where clause is needed. For unfiltered lists, use evalocl() () instead of getwithsql().

The executing user must have administrator rights or the SQL Query right. For granting temporary administrator rights, the variant of extended permissions is available.

  • class: Class name as string.
  • where: SQL WHERE clause. This can also be used using the methods sqlwhere() and sqlwherebetweendate() created.
  • order: SQL sort expression, usually a field name of the specified class.
    Can only be used if no idfilterfield/objectlist is specified.
Optionally, from version 6.3.0.8 onward, the following filter criteria can be specified:
  • idfilterfeld: Name of the member to filter the list by.
  • objectlist: List of objects to search for in the field specified under idfilterfield.

In Vertec versions before 6.7.0.9 (before Firebird 5) you have to work with these filter criteria for lists (not the result list, but the filter criteria list, in the example on the right the projekte) of more than 1500 entries, otherwise an error message will appear.

Without optional filter criteria:

projektlist = vtcapp.getwithsql("Projekt", "bold_id IN (SELECT projekt FROM projektphase WHERE status=1)", "code")

With optional filter criteria:

projekte = argobject.evalocl("eigProjekte")
leistungen = vtcapp.getwithsql("OffeneLeistung","", "datum", "projekt", projekte) 

 

getwithsqlbymember(klasse: string, member: string, expression: string, order [optional]: string): list of objects
Starting with version 6.3.0.8. Allows searching for objects of a class based on a single member comparison for users without SQL privileges (the general SQL search methods getwithsql and getmemberwithsql are restricted by SQL privilege because they can be invoked with any SQL WHERE clause.
  • class: Class name as string.
  • member: Membername as string
  • expression: comparison string (without delimiter). It can contain % placeholders, any string delimiters within
    the string will be escaped. The comparison is case-insensitive.
  • order: SQL sort expression, usually a field name of the specified class.

When the feature is called, the permission of the current user is checked on the member used for the selection. The user must have class-wide read rights on the member for the search to work. Otherwise, there is an error.

projektlist = vtcapp.getwithsqlbymember("Projekt", "Code", "COM%")
importconfigset(xmltext: string/file)

Starting with Vertec 6.7.0.7:

importconfigset(xmltext: string/file): string

Imports a config set into Vertec and applies it.

Valid XML text is passed as a string or file as a config set.

Note the encoding: Until 6.3.0.12, the passed XML text must be in ANSI format, from 6.3.0.13 in UTF-8.

Starting with Vertec 6.7.0.7, the feature returns a string containing possible errors during the import.

vtcapp.importconfigset("""<?xml version="1.0" encoding="utf-8"?>
<configset name="test" author="test"> <requirements /> <references/> 
<objects/> <settings> <system-setting name="GlobalDokPfad">C:\Dokumente</system-setting>
</settings></configset>""")

Or as of 6.3.0.13:

xml="""<?xml version="1.0" encoding="utf-8"?>
<configset name="test" author="test"> <requirements /> <references/> 
<objects/> <settings> <system-setting name="GlobalDokPfad">C:\Dokumente</system-setting>
</settings></configset>""".encode('utf-8')
vtcapp.importconfigset(xml)

Or as a file:

f = open(r"C:\Projekte\Vertec\ConfigSet\ConfigSet.xml")
vtcapp.importconfigset(f.read())
inputbox(caption: string, prompt: string[, default: string]): string
Show simple input field.
  • caption: title of the form
  • prompt: introductory text
  • default: Optional. Default value

The structure of the buttons and the return values works according to article msgbox/inputbox: description of the parameters.

print vtcapp.inputbox("Titel", "Geben Sie einen Text ein:")
>>> test
log(category: string, level: int, msg: string)

Log Message in Vertec Logging System. Levels available:

  • 10: Debug Log
  • 20: Info Log
  • 30: Warning Log
  • 40: Error Log
  • 50: Fatal Log
projekt = argobject
leistung = projekt.evalocl("offeneleistungen->first")
if leistung:
    try:
        leistung.xwertext = 0
    except:
        vtcapp.log("Leistungen anpassen", 30, "Keine Berechtigung")
msgbox(msg: string)
Show message box (versions before 6.0)

Information is always used as the title and Info is always used as the dialog type (button/symbol combination).

vtcapp.msgbox("Das ist ein Test")
msgbox(text: string [, buttons: int, title: string]): int

Show message box (versions from 6.0)

The feature supports (optional) arguments for buttons and titles.

The structure of the buttons and the return values works according to article msgbox/inputbox: description of the parameters.

 

vtcapp.msgbox("Dies ist mein Text", 1, "Vertec")
msgtomime(msgcontent): mimecontent

From version 6.5.0.11 up to and including version 6.6. Converts .msg Convert files to MIME format so that emails (activities) can be shown directly in Vertec.

.msg Files and links them to activities.

Existing emails as .msg Files, e.g. from the application with the Vertec Outlook add-in, can be converted using the adjacent script. The script only works without Restricted Scripting , i.e. not in the cloud suite, and not with Sharepoint paths. It runs on a list of activities (up to date container) and converts all .msg files around (the emails are migrated from the drive paths to Vertec).

import os 

for act in argobject.eintraege: 
    if act.effpfad and os.path.exists(act.effpfad): 
        try: 
            f = open(act.effpfad, 'rb')
            act.content = vtcapp.msgtomime(f.read()) 
        except Exception as e: 
            print('error on activity %s: %s' % (act, e)) 
        else: 
            print('path is empty or doesn\'t exist on activity %s' % act)
pdfcombine(doc1:string, doc2:string): string

Starting with version 6.5.0.7. This method merges 2 PDF documents. The PDF documents are passed as a byte string.

newpdf = vtcapp.pdfcombine(pdf1, pdf2)
pdfextract(doc:string, pagefrom:int, pagetill:int): string
Starting with version 6.5.0.7. This method extracts one or more pages. The parameters pagefrom and pagetill correspond to the first and last pages, respectively, and must be specified.
newpdf = vtcapp.pdfextract(pdf1, pagefrom, pagetill)
pdfpagecount(doc:string): int
Starting with version 6.5.0.7. This method specifies the number of pages in the document.
pages = vtcapp.pdfpagecount(pdf1)
processbi(from: String, to: String, generator: String)

Method for calculating Bi data for the business intelligence module.

Corresponds to the calculation of the BI data on a Measure and triggers the calculation of the generator given as a parameter.

From and To dates are specified as a string in the format “Year-Month”.

The generator must be specified in the same way as for the measures, i.e. “<Modulname>.<Generatorname>,” see example.

Requires administrator rights.

This method can also be automated, for example, via a planned task .

For the calculation of all generators of all active measures, see the method vtcapp.standardprocessbi() below.

Example: From January 2018 to February 2020:

vtcapp.processbi("2018-01", "2020-02", "OffersGenerator.OffersGenerator")
querycallback(state): dict
Query a previously registered callback via registercallback.

As soon as the callback has been executed, the feature returns a dictionary with all supplied parameters (incl. State). As long as the callback has not been executed yet, None returned. Successfully queried callbacks cannot be queried again, as the registration will no longer exist.
When querying via querycallback in a loop (polling), it is important to include a delay with the help of time.sleep calls so that the session is not blocked.

Example code:

state=vtcapp.registercallback()
# nur zur Demonstration: der Aufruf sollte natürlich über einen OAuth Authentifizierungs Server gehen
vtcapp.executeurl("https://myserver.vertec-mobile.com/callback?State=%s&message=ASecretMessage" % state)
time.sleep(3.0) # kurz warten bis browser offen
values=vtcapp.querycallback(state)
print(values["message"])
readinvoicedocument(binaryData)

Starting with version 6.5.0.7. The Python feature readinvoicedocument accepts the PDF, JPG and PNG formats of accounts payable documents and processes the QR code contained therein, which it returns as a data object. Starting with version 6.5.0.11 EPC QR code is also supported.

Property description
Name Name of the payee
Address Payee address information
Zip Postal code of the payee
City (disambiguation) City of the payee
Country Country of payee
Amount Gross amount
Currency currency
Accounts Account
Reference Reference number
*DocumentNumber External number
*DocumentDate Date
*DueDate Due date

*Optional data: will only be output if the QR code contains additional information .

Finally, the data object can be print() to be issued.

In addition, the feature can also be used in a planned task .

Example script:

kreditorbeleg = open("C:\Users\Name\Desktop\QrCodeBeleg.pdf",'rb').read()
belegdaten = vtcapp.readinvoicedocument(kreditorbeleg)
lieferanten = vtcapp.getwithsqlbymember("Adresseintrag", "name", belegdaten.Name)
lieferant = lieferanten[0]
currency = vtcapp.getwithsqlbymember("Waehrung", "bezeichnung", belegdaten.Currency)[0]

kreditor=vtcapp.createobject("Kreditor")
kreditor.lieferant = lieferant
kreditor.belegbild = kreditorbeleg

kreditor.esrteilnehmer = belegdaten.Account
kreditor.esrcode = belegdaten.Reference
kreditor.waehrung = currency
kreditor.betragbrutto = belegdaten.Amount

if hasattr(belegdaten, 'DocumentNumber'):
    kreditor.nummer = belegdaten.DocumentNumber

if hasattr(belegdaten, 'DocumentDate'):
    kreditor.datum = belegdaten.DocumentDate

if hasattr(belegdaten, 'DueDate'):
    kreditor.xfaelligdatum = belegdaten.DueDate

if len(kreditor.auslagen) == 1:
    outlay = kreditor.auslagen[0]
    outlay.anzahl = None
    outlay.xwertintfwbrutto = belegdaten['Amount']
registercallback(): string

Registers a callback on the cloud server to transmit an authentication code. This is required e.g. for authentication via OAuth. The return value is a randomly generated state string, which must be passed during the callback in order to be accepted. The callback is executed as an http get request to the cloud server, as an example https://mein.vertec-cloud.com/callback?state=<statestring>&code=<authentisierungscode>. The parameters transmitted with the callback can then be queried via vtcapp.querycallback.

Example code:

state=vtcapp.registercallback()
# nur zur Demonstration: der Aufruf sollte natürlich über einen OAuth Authentifizierungs Server gehen
vtcapp.executeurl("https://myserver.vertec-mobile.com/callback?State=%s&message=ASecretMessage" % state)
time.sleep(3.0) # kurz warten bis browser offen
values=vtcapp.querycallback(state)
print(values["message"])
rendertemplate(templateString, data): unicode string
As of version 6.3.0.9 there is a general-purpose template engine in Python. It is based on that of the Jinja2 template engine ( http://jinja.pocoo.org).

For easy use in Vertec, this method is available. It is also available in Restricted Scripting mode (cloud suite) and returns a Unicode string.

The templateString argument can be a string or a Unicode string, and can contain Jinja2 specific markups.

For passing the data, the following options are available as additional arguments of the feature:

  • Python Dictionary with string values as keys. Defines the variables available in the template.
  • Any quantity of keyword arguments that define the variables available in the template.
  • No further argument, the template is then processed without data.
Alternatively, it is also possible to use the template engine directly by importing the jinja2 package. However, this application is not cloud suite compatible and is not recommended.

The most important structures are:

  • A block is enclosed by {% ... %}. It contains a control statement or a variable assignment.
    • {% if proj.code == "ABC" %} ... {% endif %}. An If statement in a block is used to conditionally output an area of the template. A if must be completed by a endif. Optionally, a {% else %} in between is allowed.
    • {% for proj in projects %} ... {% endfor %}. A for statement allows the iteration of a template range. Must be completed by endfor.
  • An expression is separated with {{ ... }}. An expression is evaluated in the context of the template and mixed as a string into the output of the template.
Complete documentation of the possibilities in templates can be found at http://jinja.pocoo.org/docs/2.10/templates/.
# Beispiel Code für Ausgabe einer Projektliste

templateText = """
My own projects
===============
{% for proj in projects %}
Project: {{ proj.code }}, {{ proj.beschrieb }}
{% endfor %}
===============
"""

projects = vtcapp.evalocl("timSession->first.login.eigProjekte")
rendered_text = vtcapp.rendertemplate(templateText, projects = projects)

print rendered_text
requestfilefromclient(dialogTitle: string, directory: string, filter: string [, fileName: string]): (filename, file)

Before version 6.4.0.22:
requestfilefromclient(title: string, path: string, filter: string [, abspath: string]): (filepath, file)

Adjustment of the filter expression with Vertec version 6.3.0.12: The format can also contain several file types per filter. The changes are not backward compatible, with the new version the expressions have to be adjusted.

Starting with version 6.3.0.4. The user can select a local file in the client application. This is then transmitted to the server and is available as a binary stream for further processing as a return value of the Python method.
  • dialogTitle: Title of the dialog
  • directory: Path of the directory to be opened in the dialog. If the path does not exist, the desktop will be shown.
  • filter: Filter expression to limit the selection of files in the dialog. The filter expression changes with version 6.3.0.12, please see examples on the right.
  • fileName: Absolute path of the file to be uploaded. This parameter is optional. If it is specified, no dialog will be shown in versions prior to 6.5.0.11.
    Starting with Vertec 6.5.0.11, a dialog will be shown that warns the user that Vertec wants to read this file, which the user can acknowledge with Yes or No. If no, the process will be aborted and an exception will be thrown.

The method returns a tuple consisting of file name and file contents (before version 6.4.0.22, the method returns a tuple consisting of absolute file path including file name and file contents).

The maximum file size to upload is 50 MB.
There is a blacklist of directories from which files may not be requested, e.g. the Windows environment variable SYSTEMROOT (typically C:\Windows).

If the user clicks on Cancel in the dialog, the error message appears in Python: RuntimeError: The file upload was canceled by the user.

Web App

If a client-side path is specified (parameter abspath), an error message appears in the web app.

The start directory (parameters path) is ignored.

In versions prior to 6.4.0.8, the File dialog cannot show a custom dialog title. The title parameter is not taken into account until version 6.4.0.8.

The filter does not show the designation, it only says “All support types (...)” and then the endings individually.

vtcapp.requestfilefromclient("Hallo Welt", r"C:\MyDirectory", "Python|*.py|Text|*.txt|XML|*.xml")

  1. Wildcard must be specified (*.py instead of .py)
  2. Filter expression consists of filter pairs, whereby each filter pair requires a name and expression.
  3. Pipes must be used as separators both between couples and within a couple between name and expression.
  4. In case of multiple file extensions, they must be separated by semicolons instead of commas:

    vtcapp.requestfilefromclient("Hallo Welt", r"C:\MyDirectory", "Office Documents|*.docx;*.xlsx|Text|*.txt|XML|*.xml")
    Opens a dialog with the title “Hello World” in the C:\MyDirectory directory which allows uploading Office, TXT or XML files.

It also supports a simple syntax:

vtcapp.requestfilefromclient("Hallo Welt", r"C:\MyDirectory", "*.txt")
Opens a dialog with the title “Hello World” in the directory C:\MyDirectory, which allows uploading TXT files.

vtcapp.requestfilefromclient("Hallo Welt", r"C:\MyDirectory", "*.txt;*.xml")
Opens a dialog with the title “Hello World” in the directory C:\MyDirectory, which allows uploading TXT or XML files.

vtcapp.requestfilefromclient("", "", "", r"C:\MyDirectory\MyFile.txt")
Uploads the file.

vtcapp.requestfilefromclient("Hallo Welt", r"C:\Windows\System32", "*.dll")
Throws an error message because this directory is not allowed to be accessed

vtcapp.requestfilefromclient("", "", "", r"C:\Windows\System32\cmd.exe")
Throws an error message because this directory is not allowed to be accessed

Version before Vertec 6.3.0.12:

vtcapp.requestfilefromclient("Hallo Welt", r"C:\MyDirectory", "Python|.py,Text|.txt,XML|.xml")
Opens a dialog with the title “Hello World” in the C:\MyDirectory directory which allows uploading PY, TXT or XML files.

roundcurrency(amount, currency=None): float

Rounds the specified amount, taking into account the Project > Use rounding rules system setting.

If a Currency is optionally provided, the value entered on it is additionally Runden auf taken into account.

No indication of currency:

amount = argobject.total
vtcapp.roundcurrency(amount)
5105.89

With currency indication:

amount = argobject.total
curr = argobject.waehrung
vtcapp.roundcurrency(amount, curr)
5105.9
scriptexecute(scripttext, argobject=None)

Allows you to call a Vertec script.

  • scripttext: The actual code is passed as script text. This can be, for example, the text of a script registered in Vertec or the code itself.
  • argobject: This parameter allows you to specify the object on which to run the script. If this parameter is omitted, the script will be called on the up-to-date Vertec object.
proj = vtcapp.getobjectbyentryid("Projekt", "TemplateProject")
scripttext = vtcapp.evalocl("scripteintrag->select(bezeichnung='Projekt kopieren')->first.scripttext")
vtcapp.scriptexecute(scripttext, proj)
selectaddress()
selectphase()
selectproject()
selectobjectintree()

Starting with version 6.4.0.21. Allows you to call the different search and selection dialogs for addresses, projects, phases and the tree directly from Python.

The methods support the following optional keyword arguments:

  • selectaddress(string title, string classname, string filter)
    • title: Dialog Title (Default: Select addresses)
    • classname: Address class in which to search, e.g. Firma. (Default: address entry)
    • filter: Additional SQL filter condition (Default: empty), e.g. only on active objects
    The address search dialog uses the default search definition according to the system settings.
  • selectphase(string title, string filter)
    • title: Dialog Title (Default: Select phases)
    • filter: Additional SQL filter condition (Default: empty), e.g. only on active objects
  • selectproject(string title, string filter)
    • title: Dialog Title (Default: Select projects)
    • filter: Additional SQL filter condition (Default: empty), e.g. only on active objects
  • selectobjectintree(string title, list entrylist, string browsefilter, string selectfilter)
    • title: Dialog Title (Default: Select Objects)
    • entrylist: List of Vertec objects that are displayed as root elements in the dialog.
    • browsefilter: Comma-delimited filter for object types (e.g. Ordner, Expressionordner)
    • selectfilter: The selectfilter determines on which entries (classes and their subclasses) the dialog can be confirmed and thus “selected,” also comma-delimited.

Return value is the selected object.

adresse= vtcapp.selectaddress(title="Adressauswahl", classname="Kontakt", filter="vorname like '%S%'")

projekt = vtcapp.selectproject(title="Projektauswahl", filter="code like '%S%'")

phase= vtcapp.selectphase(title="Phasenauswahl", filter="code like '%S%'")

Kontakte = argobject.subordner
Kontaktordner = list(Kontakte)
Kontaktordner.append(argobject)
selected=vtcapp.selectobjectintree("Objekt wählen",Kontaktordner, "Ordner, Kontakt", selectfilter="Kontakt")
selectfromlist (caption: string, text: string, col1caption: string, col2caption: string, default: string, list: list of tuple): string
Creates a selection dialog as specified.
  • caption: title of the form
  • text: introductory text
  • col1caption: Column Heading 1
  • col2caption: Column title 2
  • default: Standard return value or pre-selected row *)
  • list: List of values to be shown for selection
The feature returns a string with the selected value. Only one value can be selected from the list.

*) To pre-select a row, the tuples of the list rows must consist of 3 items. The third item is the return value when the row is selected (this third column is invisible).

Only in this case does the default parameter have an effect: the row whose third column corresponds to the specified default is pre-selected.
$








vtc__000__999_66
sendfile(file: string, filename: string, [showsavedialog: boolean], [openfile: boolean]): boolean

From version 6.2. Send a file or string (as a file) to a client.

The method also works in Restrict Scripting mode.

  • file: Here you can pass a string as file content or a Python file object.
  • filename: Name of the file, if saved.
  • showsavedialog: Optional. Default = False. Desktop and cloud app. The transferred file should be saved or executed on the client depending on the client’s requirements and capabilities.
    A showsavedialog argument causes a save dialog to be shown. By default, the desktop is shown as the location.
    If showsavedialog=false, the file is saved in the client’s temp folder, overwriting an existing file. This makes sense in connection with openfile=true, then the file is saved in Temp and opened immediately.
As of Vertec 6.5.0.11, suppressing a dialog is only possible for the following file types (extensions). Whitelist:

.doc, .docx, .xls, .xlsx, .pdf, .csv, .txt, .zip, .png, .jpg, .jpeg, .bmp, .gif, .eml and from Vertec 6.5.0.15 .ics.
For all file types that are not on this whitelist, an error message will appear.

  • openfile: Optional. Desktop and cloud app. If true, the file will be opened after saving. Default is true.

The combination showsavedialog=false and openfile=false does not make sense, because the file is saved in the Temp directory and nothing else happens.

With the web app as a client, the file always appears as a download in the web browser. The arguments showsavedialog and openfile have no meaning.

Starting with version 6.3.0.8 the method has a return value and returns True or False:

  • True, if the file was saved,
  • False, if the file was not saved,
  • The web app always returns True because it cannot verify that the file has been saved. When using the web app, we recommend that you turn on automatic download in your browser.

Example of a simple project export:

projekte = argobject.evalocl("eintraege.list")
projektstr = ""
for projekt in projekte:
    projektstr += projekt.code + "\r\n"
vtcapp.sendfile(projektstr, 'projekte.txt', True, True)

Example of how to send a locally available image:

filename = r"C:\Arbeitsverzeichnis\python_editor.png"
# opening for [r]eading as [b]inary
with open(filename, 'rb') as afile:
    vtcapp.sendfile(afile, 'aFilenameHere.jpg', True, True)

Files should be explicitly closed after use. Otherwise, they will only be closed by the garbage collector or, in case of an error, even on the next exception. It is recommended to use open with with as in the example above.

sendmail(to, subject, body, [cc, bcc, fromSender, attachments])

Allows email to be sent from Vertec under the conditions described in the System Settings E-Mail . This method can be used with all apps.

  • to: String. Recipient addresses.
    • Using a semicolon ; multiple addresses can also be specified, with no space between the addresses and the semicolon.
  • subject: String. Subject of the email.
  • body:
    • String: The actual email text. Can be HTML or plaintext. HTML is recognized as such and then created as an Outlook HTML Mail.
    • Starting with version 6.5.0.21, a Word document can also be used (see example below).

Optional:

  • fromSender: String. if null or empty, the sender is removed from the system settings. Permissions etc. are not checked, it must be made sure that the user is authorized to send e-mails under this sender, otherwise this will not work on the client side.
  • cc: String. If filled as CC receiver.
  • bcc: String. If filled as BCC receiver.
  • attachment: [(File name, content)]: If filled in, the attachment will be attached to the email.

Examples:

  • The simplest case, body as a string:    
vtcapp.sendmail("dokumentation@vertec.com", "Dokumentation", "Dies ist der einfachste Fall")
  • Using Word documents as body:
    Note: Use spreadsheets in your Word documents and avoid tab stops, as they cannot be processed in the email.

1. The corresponding Word document must be created and read:

in_file = open("C:\<yourPath>\BeispielWordFürEmail.docx", "rb")
dataFileData = in_file.read()

2. Use the method to generate the email:    

vtcapp.sendmail('dokumentation@vertec.com', 'Test E-Mail from Word', dataFileData)
setpropertyvalue(name, value)

Sets a system setting. The corresponding name is specified in each system setting.

vtcapp.setpropertyvalue('Sperrdatum', vtcapp.incmonth(vtcapp.currentdate(), -1))
setresourceplanvalue
(user, project, phase, date, intervalType, value)

Only Vertec versions before 6.6. From Vertec version 6.6 you use the setresourceplanvalue Methods on User , Projects or Project Phases .

Sets a resource plan value.

  • intervalType: 0 = day, 1 = week, 2 = month
  • value: Value in minutes.
  • date: The period is filled with the value in which the date is. It is best to take the date at the beginning of the period, then there are no ambiguities.
bearbeiter = vtcapp.currentlogin()
projekt = argobject

vtcapp.setresourceplanvalue(bearbeiter, projekt, None, vtcapp.firstdayofmonth(vtcapp.currentdate()), 0, 240)
showcustomdialog(dialog definition, initial values)

Dialog function, with which dialogs can be defined in Python scripts and shown by the script. Available from version version 6.1.

For a detailed description, see the article about the Python dialogs.
showdetailform(obj: object)
Displays the detail view of the object in a new tab.
leistung = vtcapp.createobject("Offeneleistung")
vtcapp.showdetailform(leistung)
standardprocessbi()

Method for breaking Bi data for the business intelligence module.

Corresponds to the execution of the standard supplied planned task and triggers the calculation of all generators on all active measures.

Requires administrator rights.

For the calculation of individual generators, see the vtcapp.processbi() method above.

vtcapp.standardprocessbi()
strtominutes(string): integer
Translates a string into a minute value (integer), taking into account the up-to-date system setting show minutes.

Show minutes is hours:minutes:

print vtcapp.strtominutes('1:30')
>>> 90
print vtcapp.strtominutes('1.50')
>>> 110

Show minutes is hours.Decimal:

print vtcapp.strtominutes('1.50')
>>> 90
sqldateliteral(date: date): string
This method yields the correct date format for SQL queries, depending on the database server used, which is then converted into a    getwithsql statement can be built in.
aktivitaeten = vtcapp.getwithsql('Aktivitaet', 'datum = %s' % vtcapp.sqldateliteral(vtcapp.currentdate()), '')
for akt in aktivitaeten:
    print akt

>>>
Support, 30.05.2017, Support Frau Müller
Verkauf, 30.05.2017, Rechnung mit Leistungsliste (Word)
Verkauf, 30.05.2017, Rechnung mit Leistungsliste (Word)
Verkauf, 30.05.2017, Offerte (Word)
Verkauf, 30.05.2017, Offerte (Word)
Marketing, 30.05.2017, Informationen bezüglich KZU
>>>
sqlwhere(where: string): string
Creates a SQL WHERE clause, matching the up-to-date database server used, which is then placed in a    getwithsql Statement can be built in.
whereclause = vtcapp.sqlwhere("standardadresse like 'Dachsweg%'")
leistungen = vtcapp.sqlwherebetweendate('datum', vtcapp.firstdayofmonth(heute), heute)
print leistungen, whereclause

adressen = vtcapp.getwithsql("Adresseintrag", whereclause, "bold_id")
for adresse in adressen:
    print adresse

>>>
upper(standardadresse) starting with 'DACHSWEG'
Comtelsat AG
Comtelsat AG, Lanz André
Comtelsat AG, Huber Thomas
>>> 
sqlwherebetweendate(query:string, from: date, to: date): string

Creates a SQL between clause with a date interval that matches the currently used database server, which is then placed in a getwithsql Statement can be built in.

heute = vtcapp.currentdate()
whereclause = vtcapp.sqlwherebetweendate('datum', vtcapp.firstdayofmonth(heute), heute)
print whereclause

leistungen = vtcapp.getwithsql("Leistung", whereclause, "datum")
for leistung in leistungen:
    print leistung

>>>
datum between '01.05.2017' and '30.05.2017'
COMINSTALL, 09.05.2017, BER Besprechung mit Hr. Müller
COMINSTALL, 16.05.2017, TM Telefon mit Hr. Müller
>>> 
syncpayments()

Starting with version 6.4.0.22. Performs a global payment reconciliation.

If no debtor interface with payment reconciliation is installed, the method reports an error.

vtcapp.syncpayments()

For example, the method can be registered as a planned task .

SystemContext()

From version 6.6.

Activates Extended user rights within the script.

  • Must be with the with-Statement can be called.
  • Not allowed in the Python editor for security reasons.
with vtcapp.SystemContext():
    ...Code der vom Systemcontext profitiert.
translate(txt: string[, language:string]): string

Translates a GUI text into the up-to-date Vertec language.

Starting with version 6.5.0.20, an optional parameter for the target language of the translation can be used.

The up-to-date Vertec language is English:

>>> vtcapp.translate("Leistung")
Service

From version 6.5.0.20:

>>> vtcapp.translate('Offer', 'DD')
Angebot
updatedatabase()
Saves changes to the database.
vtcapp.updatedatabase()
validateobjects()

Validates new objects. If they do not violate any rules, they are no longer invalid.

vtcapp.validateobjects()
versiontointeger(versionstring): int
Converts a Vertec version string into a number that can be used to compare different versions.
Bsp: "5.5.0.67" wird in 550067 umgesetzt, 
"5.5" in 550000, 
"5" in 500000

Date Functions

The following date functions are available. They are all located in the vtcapp module.

feature Explanation Example From version
currentdate(): date
Returns the up-to-date date.
>>> vtcapp.currentdate()
2017-01-23
6.1.0.10
currentdatetime(): datetime
Returns the up-to-date date and the up-to-date time.
>>> vtcapp.currentdatetime()
2017-01-23 15:01:12.880000
6.1.0.10
datetostr(date): string
Converts a date to a string and returns it according to locale settings.

For example, in Australian English:

>>> print vtcapp.strtodate('13/06/17')
2017-06-13
>>> print vtcapp.datetostr(datum)
13/06/2017
6.1.0.14
datetostrgerman(date): string
Converts a date to a string and returns it in German date format.

It sometimes needs date values in German format at certain locations in scripts, regardless of current locale settings (see e.g. from/to arguments in groupPerformance Operators).
>>> vtcapp.datetostrgerman(argobject.evalocl('creationdatetime'))
13.10.2016
6.2
firstdayofmonth(date): date
Returns the date of the first day of the same month
>>> vtcapp.firstdayofmonth(vtcapp.currentdate())
2018-03-01
5.7
firstdayofyear(date): date
Returns the date of the first day of the same year
>>> vtcapp.firstdayofyear(vtcapp.currentdate())
2018-01-01
5.7
formatminutes(integer): string
Returns hour-minute display according to settings in Vertec
>>> vtcapp.formatminutes(argobject.minutenext)
1:00
5.7
incday(date, integer): date
Increments the day (+ or -) and returns the new date
>>> vtcapp.incday(vtcapp.currentdate(), 1)
2018-03-17
5.7
incminute(datetime, integer): datetime
Increments minutes (+ or -) and returns new date.

The date that is passed must be in the format Datetime, i.e. have a time part.

Adds 4 hours to the current time:
>>> vtcapp.incminute(vtcapp.currentdatetime(), 240)
2018-03-16 18:43:44.958000

5.7

incmonth(date, integer): date

Increments month (+ or -) and returns the new date

Note: If the date is at the end of the month and the respective months have different quantities of days, the last day of the month is taken.

Example: incmonth(-1) executed on 31.03.2021 results in 28.02.2021.

>>> vtcapp.incmonth(vtcapp.currentdate(), -1)
2018-02-16 
5.7
incyear(date, integer): date
Increments the year (+ or -) and returns the new date
>>> vtcapp.incyear(vtcapp.currentdate(), -1)
2017-03-16
5.7
lastdayofmonth(date): date
Returns the date of the last day of the same month
>>> vtcapp.lastdayofmonth(vtcapp.currentdate())
2018-03-31
5.7
lastdayofyear(date): date
Returns the date of the last day of the same year
>>> vtcapp.lastdayofyear(vtcapp.currentdate())
2018-12-31
5.7
ocldate(date): string
Returns OCL encodedate string based on a date value
>>> import datetime
>>> vtcapp.ocldate(datetime.date(2018,01,31))
encodedate(2018,1,31)
5.7
strtodate(string): datetime
Interprets a date string according to Windows locale settings (see notes on using strtodate below).
print vtcapp.strtodate('1.10.17')
>>> 2017-10-01 00:00:00
5.7
thismonday(date): date
Returns the date of the Monday in the same weeks
>>> vtcapp.thismonday(vtcapp.currentdate())
2018-03-12
5.7

Note on the use of strtodate

The use of strtodate is tricky because the string is interpreted according to the Windows locale. For example, the expression vtcapp.strtodate('01/31/2017) returns an error if it is not a German locale.

Therefore, you should always use the Python date function datetime.date(year, month, day) in the code (see example above). However, if you want the user to query a specific date via an input box, you can do this by presenting a date suggestion in the correct format, which the user can modify accordingly.

For this, the date is formatted according to local country settings (vtcapp.datetostr..):

# Frage den Benutzer nach dem Datum. Das Datum wird gemäss Windows-locale dargestellt.
res = vtcapp.inputbox('Vertec', 'Datum für die Berechnung', vtcapp.datetostr(vtcapp.currentdate()))
print vtcapp.strtodate(res)

The datetostr() method was introduced in Vertec version 6.1.0.14. In earlier Vertec versions, the date can be displayed in formatted with strftime according to local locale settings:

import datetime

# Frage den Benutzer nach dem Datum. Datum gemäss Windows-locale dargestellt.
res = vtcapp.inputbox('Vertec', 'Datum für die Berechnung', datetime.date.today().strftime('%x'))
print vtcapp.strtodate(res).date()

executereport() or executeserverwordreport()

When is which method used and how do the parameters need to be set?

  • Executereport and Executereport2 can be used with Office Reports and Legacy Word Reports and allow you to call and run reports based on a report object.
  • Executeserverwordreport can only be used with Vertec-generated word reports . This method is used to execute Vertec-generated Word reports without a report object.

The following parameters are the same for all methods:

rootObj The Vertec object on which the report runs.
optarg Optional address. If not used, use None.

 

executereport(rootObj, optarg, reportObj, [saveAs, showDialog, doPrint, showApp])
Reporting system ReportObj saveAs showDialog doPrint showApp Desktop Cloud (disambiguation) Web
Office-generated legacy reports (Word, Excel) Report object in Vertec

 

or

Path to the Office template on the filesystem.

  • None uses path from ReportObj. If no path is specified, the document is not saved.
  • Path, also with OCL variables
  • Filename (uses dock path of rootObj)

If an empty string is specified or the argument is omitted, no file is saved.

True or False

Default=False

True or False

Default=False

Deprecated in versions from 6.6.0.8 onwards.

True or False

 

In versions before 6.6.0.8 ignored if doPrint = True. In this case, the report will always be shown.

ignored if report is not saved. In this case, the report is always shown.

x x  
Vertec-generated legacy Word reports Report object in Vertec Dito Dito Not included Not included x x x
Office Reports (Word, Excel, PDF) Report object in Vertec Dito Dito Not included True or False

 

Ignored if report is not saved. In this case, the report is always shown.

x x x

 

executereport2(rootObj, optarg, reportObj, [saveAs, showDialog, doPrint, showApp])
Reporting system ReportObj saveAs showDialog doPrint showApp Desktop Cloud (disambiguation) Web
Office-generated legacy reports (Word, Excel)

Report object in Vertec

No trails.

  • None uses path from ReportObj. If no path is specified, the document is not saved.
  • Path, also with OCL variables
  • Filename (uses dock path of rootObj)

If an empty string is specified or the argument is omitted, no file is saved.

If no file is saved, no activity is created.

True or False

 

Default=False

True or False

Default=False

Deprecated in versions from 6.6.0.8 onward.

True or False

 

In versions before 6.6.0.8 ignored if doPrint = True. In this case, the report will always be shown.

ignored if report is not saved. In this case, the report is always shown.

x x  
Vertec-generated legacy Word reports Report object in Vertec Dito Dito Not included Not included x x x
Office Reports (Word, Excel, PDF) Report object in Vertec Dito Dito Not included True or False

 

Ignored if report is not saved. In this case, the report is always shown.

x x x

 

executeserverwordreport(rootObj, optarg, templatePath, [outputFormat, saveAs, showDialog, showApp])
Reporting system TemplatePath outputFormat saveAs showDialog showApp Desktop Cloud (disambiguation) Web
Vertec-generated Word reports Path to Template DOCX” or “PDF”.

 

Default: “DOCX

  • Filename (uses rootobj’s doc path)
  • Path, also with OCL variables.

If an empty string is specified or the argument is omitted, no file is saved.

True or False

 

Default=False

True or False

 

Default=True

x x x

italic: optional parameter

The module “vtcextensions”

There is a Vertec module called vtcextensions for handling extensions.

It is also available in Restricted Scripting mode from version 6.3 and includes the following methods:

Method / feature description Sample code
GetExtension(art:string) or
getextension(art:string): extension
Returns a reference to the extension of the specified type.
import vtcextensions

# Aufruf der DEBI-Extension
ext = vtcextensions.getextension("DEBI")
CreateVtcExtensionHost(extension:string): host

With this method, the host used by the extensions (e.g. __init__(self, host) can be replicated in the code for testing purposes.

When using the extensions via Vertec, this is done automatically.

import vtcextensions
host = vtcextensions.CreateVtcExtensionHost('FibuAbacus.AbacusDebiExtension')
ext = FibuAbacus.AbacusDebiExtension(host)

Example using an extension

# Buchungen
# Wir fragen den Benutzer, ob er in die Buchhaltung buchen will. Vielleicht will er auch einfach nur die Buchungen anschauen.
if vtcapp.msgbox("Die Buchungen wurden erstellt und als .txt Datei am üblichen Ort dokumentiert. Möchten Sie die Buchungen jetzt übertragen?",3, "Vertec") == 6:
   # Buchungen werden übertragen.
   ext = vtcextensions.getextension("DEBI")
   ext.StartLohnBuchung()
   for rec in reclist:
       ext.LohnBuchungsZeile(rec.Mandant, rec.Personalnummer, rec.Lohnartnummer, rec.Text, rec.GueltigVon, rec.GueltigBis, rec.Anzahl)
       # Buchungen werden hier abgesetzt. Vor der Buchung wird überprüft,
       # ob diese Zeile bereits vorhanden ist, wenn ja, überspringen.
   ext.EndLohnBuchung()

The module “ziputils”

As of version 6.3.0.2, there is a Vertec module called ziputils, which allows you to compress files. It generates ZIP files in Python.

It is also available in Resctict Scripting mode and includes the following methods:

Method / feature description Sample code
createzip(contentlist: tuples): bytestream From version 6.3.0.2. Compresses a list of tuples (filename,content) into a ZIP file and returns it as a byte stream. This can be easily saved/downloaded with a Filename.zip.
import ziputils

zip = ziputils.createzip([('file.txt', 'Hallo das ist ein Text')])
vtcapp.sendfile(zip, 'ziptest.zip', True)

Starting with version 6.5.0.14 the following 3 features are available:

  • readnames(zipcontent) returns a list of file names contained in the ZIP file. If the ZIP file has a folder structure, the names contain the paths separated by slashes (/).
  • readbyname(zipcontent, name) reads a file from the ZIP file based on its name.
  • readbyidx(zipcontent, idx) reads a file based on its index in the name list.

The module “vtcplanningcore”

As of version 6.6, there is the Python module vtcplanningcore for Resource Planning with the following methods:

Method / feature description
increment_interval_date(date, increment): date Feature for incrementing and decrementing period start data. Increments the specified date by the increment specified quantity of intervals. For decrementing, a negative quantity of intervals can be specified.
get_planning_level(): string Returns the planning level as a string.
Possible results: 'Projekt' or 'ProjektPhase'.
get_planning_interval_type(): string Returns the scheduling interval as a string.
Possible results: 'day', 'week' or 'month'.
show_bulk_planning_dialog(left_obj, right_obj)

Displays a dialog for efficiently setting multiple planning values for the specified objects.

The order in which the objects are provided does not play a role, but the caller must make sure that one of them is an object of type AbstractWorker is either a project editor or a Planning Editor , and the other is either a Projekt or a Projektphase, depending on the Planning Level set.

The ResourcePlanningProvider helper object

For the implementation of the resource planning lists, this module also includes a ResourcePlanningProvider class available, which allows the reading and setting of plan data and which can be used in a List Controller .

One ResourcePlanningProvider Object is created for a list of entries (users, projects or phases) and a time period. The provider then loads all planning data for these source objects and for the specified period. The planned values can then be retrieved or set.

A budgeted value in ResourcePlanningProvider always applies to 2 entries and a date, e.g. for the user “Christoph Keller,” the project “AZZ2” and the month starting with 01.08.2022.

The one entry (the Source entry, sourceEntry) must come from the list of entries specified at initialization. We call the other entry “opposite” (othersideEntry).

The following methods are available on a ResourcePlanningProvider object:

ResourcePlanningProvider(sourceEntries, start, end) Constructor, creates a planning provider and loads the planning data for the specified objects and period.
add_entry(obj) Adds a new object to the provider’s sourceEntries list.
add_otherside_entry(obj) Temporarily adds a new object to the list of otherside entries. This allows this object to be set_planned_minutes() budgeted values can be entered.
get_planned_minutes(date, sourceEntry, othersideEntry, subscriber): int Returns the scheduled time in minutes for the scheduled cell with interval date date and the two specified entries. If no plan data is available, None returned.
set_planned_minutes(date, sourceEntry, othersideEntry, value) Sets the scheduled time in minutes for the scheduled cell with interval date date and the specified entries.
Setting a None Value as value removes the plan data for this cell.
has_write_access(sourceEntry, othersideEntry, subscriber): boolean Checks whether the two objects and the date range have write permissions.
get_planned_minutes_aggregated (source_entry, otherside_entry, dateFrom, dateTo=None, subscriber=None): int Returns the aggregated scheduled time for the two specified entries in the specified period.
  • Both source_entry and otherside_entry can None be; in this case, all entries known to the up-to-date ResourcePlanningProvider are considered.
  • dateFrom is required, dateTo is optional. If no dateTo is specified, only the interval that matches dateFrom is considered.
Gives None return if no budgeted values with the specified criteria are found.
get_net_capacity_minutes(self, worker, dateFrom, dateTo=None, subscriber=None): int Net capacity in minutes per user.
  • worker : AbstractWorker, PlanningWorker, or project editor
  • dateFrom: Start date
  • dateTo: Optional, end date. If None, the end date of the interval of the dateFrom is used.
For example, on a project, users who are already overloaded can be highlighted by color in the list.
get_custom_net_capacity_minutes(self, worker, dateFrom, dateTo=None, subscriber=None): int

From Vertec 6.7.0.5. Net capacity in minutes per user based on system settings Adjusted Net Capacity (%) .

Gives None return if the system setting is empty or contains an invalid value.

get_gross_capacity_minutes(self, worker, dateFrom, dateTo=None, subscriber=None): int Gross capacity in minutes per user.
  • worker : AbstractWorker, PlanningWorker, or project editor
  • dateFrom: Start date
  • dateTo: Optional, end date. If None, the end date of the interval of the dateFrom is used.
For example, on a project, users who are already overloaded can be highlighted by color in the list.
get_remaining_capacity_minutes(worker, dateFrom, dateTo=None, subscriber=None): int Remaining free capacity in minutes for a given user and a given date range (net_capacity – planned_minutes).
  • worker : AbstractWorker, PlanningWorker or project editor (see 2.4)
  • dateFrom: Start date
  • dateTo: Optional, end date. If None, the end date of the interval of the dateFrom is used.
get_custom_remaining_capacity_minutes(self,worker, dateFrom, dateTo=None, subscriber=None): int

Starting with Vertec 6.7.0.5. Remaining free capacity in minutes for a given user and a given date range, taking into account the system setting Adjusted Net Capacity (%) .

Gives None return if the system setting is empty or contains an invalid value.

get_otherside_entries(subscriber): list of entries Returns the list of entries for which plan data already exists, based on the sourceEntries objects specified in the constructor.
generate_date_range(start, end) Returns a list of date values for scheduling intervals of start to end. Depends on the system-wide setting of the planning interval (months, weeks, days).
get_start_preceding_interval(): date Returns the date of the interval that precedes the start interval.
get_column_title_by_date(date): string Returns the appropriate column title when the date value is specified for a specific planning interval.

ResourcePlanningProviders are commonly used in list controllers and custom renderers for planning lists. The list controller instantiates a planning provider, which is then used to display and set the values in Plan cells.    

vtcplanningcore as Stub File

The vtcplanningcore module is also available as a Python Stub File. It is called vtcplanningcore.py and is stored like the other Stub Files in the subfolder PythonStubs in the Vertec installation directory.

The module “vtcplanning”

From version 6.6. there is the Python module vtcplanning, which includes standard implementations of list controllers for resource planning. List Controllers

These all have a initialize_with_period(start, end, interval) Method called by Vertec Kern and specifies the planning period to be displayed and the planning interval.

To ensure that a planning list that starts on a new interval (e.g. up-to-date month) is not completely empty, the list controllers also load planning data for an interval before the specified start date.

This means that if the planning period is August – October (planning interval “Month”) then row objects are also displayed which have planning data in July, but not in August-October.

Timetable

The Timetable are based on a single object and display one row for each scheduled opposite object. The columns correspond to the scheduling intervals.

Time tables can also be shown as read-only sum tables based on a list.

In the Python module vtcplanning, we provide the following list controller classes with:

list controller description
vtcplanning.SingleObjectTimeTableController

Used to plan on individual objects (checkmark Für einzelne Objekte anzeigen? is set).

The controller can handle the different classes (Project, ProjectPhase, AbstractWorker, Project Editor or PlanningWorker) itself, the same controller can always be specified.

vtcplanning.ReadonlySingleObjectTimeTableController Based on a single object, but read-only, not for scheduling. Used for timesheets on individual objects that cannot be scheduled.
vtcplanning.ReadonlyProjectsSingleObjectTimeTableController For read-only project time tables on individual objects. Used to show project totals if the planning level is phases.
vtcplanning.ReadonlyPhasesSingleObjectTimeTableController For read-only phase time tables on individual objects. Used to show phase totals if the planning type is Processor Phase Assignment .
vtcplanning.ReadonlyContainerTimeTableController For read-only timesheets on lists (checkbox Für Listen anzeigen? is set).
Used for Total Time Tables .
vtcplanning.ReadonlyOtherSideContainerTimeTableController For read-only timesheets on lists (checkbox Für Listen anzeigen? is set).
Used for Total Time Tables to show the totals of the opposite side on a list of objects (e.g. editor totals on a project list).
vtcplanning.ReadonlyPhasesContainerTimeTableController For read-only timesheets on lists (checkbox Für Listen anzeigen? is set) to show sums of phases on a list of projects or users if the planning level is project (in this case, the normal list controllers would not be shown on projects).

Pivot tables

Starting from a list of entries (AbstractWorker, project or phases), a resource planning Pivot Table can be displayed. The pivot table shows the entries as columns and the planned opposite entries as rows. This makes it possible to enter planned data for new opposite entries via the star row.

To implement pivot table views, the following list controller classes are available:

list controller description
vtcplanning.RegularPivotTableController

For pivot tables with the entries in the list as rows and the opposite side as columns. Used to schedule on a list (checkmark Für Listen anzeigen? is set).

The controller can handle the different classes (Project, ProjectPhase, AbstractWorker, Project Editor or PlanningWorker) itself, the same controller can always be specified.

vtcplanning.MirroredPivotTableController

For pivot tables with the entries in the list as columns and the opposite side as rows. Used to schedule on a list (checkmark Für Listen anzeigen? is set).

In this list, a star row can be shown to insert new objects to be planned. More information can be found here .

The controller can handle the different classes (Project, ProjectPhase, AbstractWorker, Project Editor or PlanningWorker) itself, the same controller can always be specified.

vtcplanning.ReadonlyRegularPivotTableController Used to show project-user pivot tables when the planning level Phasen is, with the entries of the list as rows and the opposite side as columns.
vtcplanning.ReadonlyMirroredPivotTableController Used to show project-user pivot tables when the planning level Phasen is, with the entries in the list as columns and the opposite side as rows.
vtcplanning.RegularSingleObjectPivotTableController Used to also plan on a single project in pivot tables. Displays a pivot table with the single entry as a row and the opposite side as a column.
vtcplanning.MirroredSingleObjectPivotTableController Used to also plan on a single project in pivot tables. Displays a pivot table with the single entry as a column and the opposite side as rows.

Available renderers

For this purpose, there are the following Custom Renderer for use in the resource planning tables. All of these renderers can be used in the list settings in two ways:

Dynamically
  • Expression: %col%
  • Checkbox : Ja

Shows the value in the cell that matches the row/column combination.

Static

Shows the summed value across all columns per row.

Custom renderer description
vtcplanning.PlannedMinutesRenderer

Renderer for the planning times. Allows you to enter the planned values in the individual cells.

vtcplanning.NetCapacityRenderer

Renderer to show net availability of users.

vtcplanning.CustomNetCapacityRenderer

Starting with Vertec 6.7.0.5. Shows the net availability of users, taking into account the system setting .

vtcplanning.GrossCapacityRenderer

Renderer to show the gross availability of users.

vtcplanning.RemainingCapacityRenderer

Renderer to show the remaining availability of users.

vtcplanning.CustomRemainingCapacityRenderer

Starting with Vertec 6.7.0.5. Shows the residual availability of users taking into account the system setting Adjusted Net Capacity (%) .

vtcplanning as Stub File

The vtcplanning module is also available as a Python Stub File. It is called vtcplanning.py and is stored like the other Stub Files in the subfolder PythonStubs in the Vertec installation directory.

The module “vtccom”

As of Vertec 6.7.0.7 there is the Python module vtccom, which implements the possibilities of COM forwarding.

This includes the feature vtccom.createobject(identifier) which provides a forwarding proxy for the COM server on the client.

For more information, see the article on Com forwarding .

The individual vertec data object

For individual objects, there are the following methods:

Method/Feature description Sample code
addtag(tagname)

Starting with version 6.1.0.10. Sets a tag on the object. For more information, see Tags on User Entries.

argobject.addtag('mytag')
checkright(right: string, membername: string): boolean

Checks whether the logged in user has the specified right on the specified member name.

Possible permissions are: 'read’, 'write’, 'create’, 'delete’, 'execute

Return value: 1 = True, 0 = False

obj = argobject
if obj.checkright('read', 'offeneleistung'):
  ...
delete()

Deletes the object in Vertec

obj.delete()
evalocl(OCL:string)

Evaluates an OCL expression on the object.

Before version 6.1.0.10 this was called eval() on the individual object. Then the method was adapted to the global method so that it has the same name everywhere. In versions 6.1.0.10 and later you should therefore always use evalocl().

projektcode = argobject.evalocl("code")
getattr(object, name[, default])

Returns the value of a member.

getattr(obj, “first name”)

is equivalent to obj.firstname. Sometimes you need getattr because you get a member as a parameter in a method, for example, and then query it like that.

If there is no member of this name on the object, the method returns the default, if one is specified. Otherwise, an AttributeError is returned.

getattr(obj, "vorname", "")
projekt = argobject
if hasattr(projekt, "offeneleistungen"):
    liste = getattr(projekt, "offeneleistungen")
    for leistung in liste:
        print leistung.text
getkeystring(key): string
getkeybool(key): boolean
getkeycurr(key): currency
getkeyint(key): integer
getkeydate(key): datetime

Starting with version 6.1.0.10. These methods are used to access the values stored as key values.

For details, see Key Values on User Entries.

>>> argobject.getkeydate('datum')
2017-02-03 00:00:00
getmemfootprint(): integer

From version 5.8. Returns as result the quantity of bytes occupied by the object in memory (memory footprint).

The value is determined as follows:

Instance of the object

+ Sum of instances of all members

+ Size of the value of each member (for strings, the length)

+ MemFootPrint of all owned linked objects (e.g. phases of the project).

It should be noted that this is an approximation, since the boundary of what has to be counted for an object cannot be drawn precisely.

The following script outputs the memory requirements of all projects in the system:

r = vtcapp.evalocl("projekt")
for projekt in r:
    print projekt.code+' '+str(projekt.getmemfootprint())
getmlvalue(membername:string, language:string): value

The so-called multilanguage attributes (MLStrings, multilingual attributes) can be queried using this method.

  • Membername: Name of the member
  • Language is the respective language code (DE, FR, IT, EN).

Multilanguage attributes are:

  • Servicetype.Text
  • Expense type.Text
  • Outlay type.Text
  • Custom field class.Description (designation of custom items)
  • GridColDef.Title (column title in list settings)

To set such an attribute, the method setmlvalue() can be used.

taetigkeit = argobject
print taetigkeit.getmlvalue("text", "FR")
>>>
Vacances
>>>

If the member is queried normally, the return value always corresponds to the up-to-date Vertec language:

print taetigkeit.text
>>>
Ferien/Urlaub
>>>
hasattr(object, name): boolean

Checks whether an object has a corresponding member.

obj = adresse
if hasattr(obj, "vorname"):
    print obj.vorname
hastag(tagname): boolean

From version 6.1.0.10. Checks whether an object has set a corresponding tag.

For more information, see Tags on user records.

obj = argobject
if obj.hastag('mytag'):
  ...
istypeof(classname:string)

or

IsTypeOf(classname:string): boolean

Checks whether the object is of type Classname.

True or False.

obj = argobject # das aktuelle Objekt ist eine Firma in Vertec
obj.IsTypeOf("Projekt")
>>> 0 # false

obj.istypeof("Firma")
>>> 1 # true
linkto(target, role)

Makes a link type from the object to the passed object (target) with the specified role.

For detailed information on this topic, see Operators and Methods for Links.

Objid

Returns the internal ID of the object.

>>> argobject.objid
3011
removetag(tagname)

Starting with version 6.1.0.10. Deletes the corresponding tag from this object.

For more information, see Tags on user records.

argobject.removetag('mytag')
setattr(object, name, value)

Describes the name attribute of the object object with the value value.

For example, you can loop through the custom fields of an object and use the found attribute names to describe the attributes.

This code creates a new object of the same type as the argobject and copies the contents of all custom fields to the new object.

source = argobject
target = vtcapp.createobject(source.evalocl('ocltype.asstring'))
zusatzfelder = source.zusatzfelder
for z in zusatzfelder:
    zName = z.metazusatzfeld.fieldname

Now you know the name of the custom field, but if you addressed it with target.zName, you would get an error message “target has no attribute zName”. So you use setattr:

setattr(target, zName, getattr(source, zName))
vtcapp.showdetailform(target)
setkeyvalue(key, value)

Starting with version 6.1.0.10. With this method, customer-specific values are stored as key values on user entries.

These values can later be accessed via the getkey methods and lists can be filtered efficiently.

argobject.setkeyvalue("datum", "2017-02-03")
setmemberoutofdate(membername:string)

If a value is to be read freshly from database, the field out of date must be set.

This method does the same as the Notif for a Modified message.

proj = argobject
proj.setmemberoutofdate('code')

ensures that the next time you access Project.code, this value is loaded freshly from the database.

setmlvalue(membername:string, value:string, language:string)

The so-called multilanguage attributes (MLStrings, multilingual attributes) can be set via this method.

  • Membername: Name of the member
  • Value: The value for the specified language
  • Language is the respective language code (DE, FR, IT, EN).

Multilanguage attributes are:

  • Servicetype.Text
  • Expense type.Text
  • Outlay type.Text
  • Custom field class.Description (designation of custom items)
  • GridColDef.Title (column title in list settings)

To query such an attribute, the getmlvalue() method can be used.

taetigkeit = argobject
taetigkeit.setmlvalue("text", "Vacanze", "IT")
unlink(target, role)

Removes the link from the object to the passed object (target) with the specified link role.

For detailed information on this topic, see Operators and Methods for Links.

unload(): None

Removes the object from the Vertec object store.

This method was introduced solely to control memory usage during data migrations. It should be used with caution, as subsequent access to the unloaded object may result in errors.

 

Classname of an object

Access to the classname works in Python only via OCL:

obj.evalocl('ocltype.asstring')

Methods on individual objects of type “project”

Method/Feature description Sample code
entrytypeslookup(typidx, phase=None): List of project entry types

Returns a list of project entry types for the project (and optionally a phase)

typeidx: 0: Services, 1: Expense types, 2: Outlay types.

proj = argobject
taetigkeitenliste = proj.entrytypeslookup(0, None)
phaseslookup(user, entrytype=None): List of project phases

Returns a list of project phases for the specified user (and optionally a project record type).

proj = argobject
bearbeiter= vtcapp.currentlogin()
phasenliste = proj.phaseslookup(bearbeiter, None)
assignment(user): boolean

Indicates whether the specified user is authorized to create services etc. on this project.

proj = argobject
bearbeiter= vtcapp.currentlogin()
if proj.projektbearbeiterisassigned(bearbeiter):
   ...

setresourceplanvalue(worker, date, value)

Starting with Vertec 6.6. Allows resource plan values to be set when the is set to project.

  • A or a project editor is passed as worker.
  • date: The period in which the date is located is filled with the value.
  • value: Value in minutes.
bearb = vtcapp.currentlogin()
projekt = argobject
projekt.setresourceplanvalue(bearb, vtcapp.strtodate('15.05.2023'), 180)

Methods on individual objects of type “AbstractWorker”

On Abstractworker , project editor, and Planningworker , there are the following methods:

Method/Feature description Sample code

setresourceplanvalue(project_or_phase, date, value)

As of Vertec 6.6. Allows setting of resource plan values.

  • project or phase: Depending on the Planning Level , a project or a project phase is specified here.
  • date: The period in which the date is located is filled with the value.
  • value: Value in minutes.
bearb = vtcapp.currentlogin()
projekt = argobject
bearb.setresourceplanvalue(projekt, vtcapp.strtodate('15.05.2023'), 180)

Methods on individual objects of type “Project user”

 On project users, there are the following methods:

Method/Feature description Sample code

setnotification(category, text, link)

Starting with Vertec 6.6. Adds a Notification to the user with a specified category, text and optional linked user entry.

If a notification with the same category and the same linked object already exists on the user, the text is updated.

  • category is a string indicating the category (type) of the notification. This is freely selectable.
  • text is any text that describes the notification and usually also contains information about the linked object.
  • link (optional): is a Vertec object (UserEntry). If specified, the notification is displayed with the corresponding icon and the object’s String Representation .
aktivitaet = argobject
zustaendig = aktivitaet.zustaendig
if zustaendig and not aktivitaet.erledigt:
    zustaendig.setnotification('pending_activity', aktivitaet.titel, aktivitaet)
deletenotification(category, link) Starting with Vertec 6.6. Deletes the Notification on the user with the corresponding category and linked object. If no corresponding notification is found, nothing happens. No error message appears.
aktivitaet = argobject
zustaendig = aktivitaet.zustaendig 
if zustaendig and aktivitaet.erledigt: 
    zustaendig.deletenotification('pending_activity', aktivitaet)

Methods on individual objects of type “Project phase”

On project phases there are the following methods:

Method/Feature description Sample code

setresourceplanvalue(worker, date, value)

Starting with Vertec 6.6. Allows resource plan values to be set when the Planning Level is set to phase.

  • worker: A Planning Editor or a project editor is passed as a worker.
  • date: The period in which the date is located is filled with the value.
  • value: Value in minutes.
bearb = vtcapp.currentlogin()
phase = argobject
phase.setresourceplanvalue(bearb, vtcapp.strtodate('15.05.2023'), 180)

Methods on individual objects of type “invoice”

Method/Feature description Sample code
reserve([raiseException])

From version 5.8. Post an invoice to the accounting system.

The raiseException argument is a Boolean (True/False), which specifies whether to report errors when posting or cancelling.

raiseException is optional, default is True.

If raiseException is False, errors when posting are ignored, the invoice is simply not posted.

rechnung = argobject
rechnung.buchen()
import payments()

From version 5.8. Imports the payments to the up-to-date invoice. Works only if the debtor interface supports payment reconciliation.

argobject.importzahlungen()
makeoffen([raiseException])

Starting with version 5.8. Sets a charged invoice back to open (Undo charging).

The raiseException argument is a Boolean (True/False), which specifies whether to report errors while charging or undo while charging.

raiseException is optional, default is True.

If raiseException is False, errors during charging are ignored, the invoice remains simply charged.

rechnung = argobject
rechnung.makeoffen(False)
makecalculated([raiseException])

From version 5.8. Charges an open invoice.

The raiseException argument is a Boolean (True/False), which specifies whether to report errors while charging or undo while charging.

raiseException is optional, default is True.

If raiseException is False, then charging errors are ignored, leaving the invoice open.

rechnung = argobject
rechnung.makeverrechnet(False)
cancel([raiseException])

From version 5.8. Cancels a posted invoice.

The raiseException argument is a Boolean (True/False), which specifies whether to report errors when posting or cancelling.

raiseException is optional, default is True.

If raiseException is False, errors in posting are ignored, the invoice is simply not canceled.
rechnung = argobject
rechnung.stornieren()

Methods on individual objects of type “project entry”

Services, expenses and outlays are summarized under the term project entry.

Method/Feature description Sample code
makeoff()

From version 5.8. Sets a billed service, expense or outlay to open.

This only works if the service, expense or outlay is not on an invoice, otherwise an error will be thrown.

argobject.makeoffen()
makecalculated()

Starting with version 5.8. Sets an open service, expense or outlay to charged.

This only works if the service, expense or outlay is not on an invoice, otherwise an error will be thrown.

argobject.makeverrechnet()

Methods on individual objects of type “service”

Method/Feature description Sample code
updateset()
From version 6.1.0.14. Hourly rate is recalculated (from tariff system).

Requires user right Projekt-Administrator or Super.

argobject.updatesatz()

Methods on individual objects of type “activity”

Method/Function description Sample code
setpath(path: string)

Starting with version 6.1.0.14. Sets the document path on the activity when the Document Storage to Dateisystem oder DMS has been discontinued.

argobject.setpfad('C:\\Dokumente\\text.txt')
setdocumentcontent(filename, documentcontent)

Starting with Vertec 6.7.0.15. Adds a document to the activity when the Document Storage to Intern has been discontinued.

  • filename: Name under which the file should be saved.
  • documentcontent: Document content as byte stream.

On the activity, the following happens:

  • DocumentFullName is set
  • DocumentData object is created and described with the content
  • DocumentSize is set to the length of the content array

After successful execution, the Document page is shown.

If a document has already been saved on the activity, an error is output.

Note: This method can also be used if document saving is not set to Internal, but the document will be saved internally.

(name, file) = vtcapp.requestfilefromclient("Dokument auswählen", r"C:", "Word|*.docx")
activity = vtcapp.createobject("Aktivitaet")
activity.setdocumentcontent(name, file)
vtcapp.showdetailform(activity)
setemailcontent(mimecontent)

Starting with Vertec 6.7.0.15. Adds an email to the activity.

  • mimecontent: Here the .eml file specified. If the email is a .msg file, it must first be converted to MIME format with vtcapp.msgtomime() .

On the activity, the following happens:

  • EmailSender is extracted and set
  • EmailRecipients is extracted and set
  • DocumentData object is created and described with the content
  • DocumentSize is set to the length of the content array
  • Setting EmailAttachmentNames
  • Text is described with body (plain text)
  • Title is described with subject

After successful execution, the E-mail page will be shown.

If a document has already been saved on the activity, an error is output.

(name, file) = vtcapp.requestfilefromclient("Email auswählen", r"C:", "Email|*.msg")
mimecontent = vtcapp.msgtomime(file) 
activity = vtcapp.createobject("Aktivitaet")
activity.setemailcontent(mimecontent)
vtcapp.showdetailform(activity)

Methods on individual objects of type “currency”

Method/Feature description Sample code
getkursto(currency: object, date: date): currency
Starting with version 6.1.0.14. Returns the conversion rate for the corresponding date.
chf.getkursto(eur, vtcapp.currentdate())

Vertec Lists

Starting with version 6.2.0.7, all Python methods that return lists of business objects directly return a Vertec list and no longer a Python list.

  • evalocl()
  • getwithsql()
  • getmemberwithsql()

resulting lists are vertec lists and no longer need to be created with vtcapp.createlist().

Example

Versions before 6.2.0.7: liste = vtcapp.createlist("Projekt", vtcapp.evalocl("projekt->select(code.sqllike('A%'))"))

Versions from 6.2.0.7: liste = vtcapp.evalocl("projekt->select(code.sqllike('A%'))")

Methods on vertec lists

Method/Feature description Sample code
append(Object)
A list can be populated via the append() method. Only individual objects can be passed, not entire lists with append().
mylist = vtcapp.createlist('Projekt')
mylist.append(argobject)
evalocl(OCL:string)
An OCL expression can be deposited on the Vertec list.
projektIds = argobject.evalocl("eintraege").idstring()
leistungen = vtcapp.createlist("OffeneLeistung", vtcapp.getwithsql("OffeneLeistung", "projekt IN (%s)" % projektIds, ""))
print leistungen.evalocl("wertext->sum")
extend(list: list)
Starting with version 6.2. The extend() method can be used to append another list to a Vertec list.

This checks whether the Vertec list is a derived list (e.g. Container.eintraege). Access is denied in this case.

projektIds = argobject.evalocl("eintraege").idstring()
leistungen = vtcapp.createlist("OffeneLeistung", vtcapp.getwithsql("OffeneLeistung", "projekt IN (%s)" % projektIds, ""))
leistungen.extend(vtcapp.createlist("VerrechneteLeistung", vtcapp.getwithsql("VerrechneteLeistung", "projekt IN (%s)" % projektIds, "")))
print leistungen.evalocl("wertext->sum")
idstring()

A common request in Python scripts is to formulate an SQL query with bold_id in (...) based on a list of Vertec objects.

To do this, the IDs of a list of objects must be converted to a comma-delimited string.

  • List.idstring() returns the IDs of the Vertec objects as a comma-delimited string.
  • If the list contains non-persistent objects, the method returns an error message.
>>> vtcapp.evalocl('Projektbearbeiter->allinstances').idstring()
300,676,7613,682,688,694
index(Object)
Starting with version 6.2.0.7. Returns the index of the object in the list.
If the object occurs more than once, the deepest index is returned. Introduced
for compatibility with Python lists (see below).
>>> liste = vtcapp.evalocl("projekt.code")
>>> print liste.index('COMINSTALL')
25
insert(index, object)
Starting with version 6.2.0.7. Adds an object to the list at the position index. Introduced
for compatibility with Python lists (see below).
>>> liste = [123, 'xyz', 'miau', 'abc']
>>> liste.insert(3, 2009)
>>> print liste
[123, 'xyz', 'miau', 2009, 'abc']
remove(object)
Removes the specified object from the list
projektIds = argobject.evalocl("eintraege").idstring()
leistungen = vtcapp.createlist("OffeneLeistung", vtcapp.getwithsql("OffeneLeistung", "projekt IN (%s)" % projektIds, ""))
fl = leistungen.evalocl("self->select(bearbeiter.asstring = 'Judith Feller')")
for leistung in fl:
    leistungen.remove(leistung)

The example above is to show the remove() method. This use case would be solved via reject:

projektIds = argobject.evalocl("eintraege").idstring()
leistungen = vtcapp.createlist("OffeneLeistung", vtcapp.getwithsql("OffeneLeistung", "projekt IN (%s)" % projektIds, ""))
leistungen = leistungen.evalocl("self->reject(bearbeiter.asstring = 'Judith Feller')")

Differences vertec and python lists

Vertec and Python lists differ in the following ways:

The + operator is not applicable to Vertec lists. Type code
projektIds = argobject.evalocl("eintraege").idstring()
leistungen = vtcapp.getwithsql("OffeneLeistung", "projekt IN (%s)" % projektIds, "") \
             + vtcapp.getwithsql("VerrechneteLeistung", "projekt IN (%s)" % projektIds, "")

does not work. An error appears: TypeError: can only concatenate list (not "BoldListAdapter") to list.

Instead, use extend() or +=:

leistungen = vtcapp.getwithsql("OffeneLeistung", "projekt IN (%s)" % projektIds, "")
leistungen.extend(vtcapp.getwithsql("VerrechneteLeistung", "projekt IN (%s)" % projektIds, ""))
or
leistungen = vtcapp.getwithsql("OffeneLeistung", "projekt IN (%s)" % projektIds, "")
leistungen += vtcapp.getwithsql("VerrechneteLeistung", "projekt IN (%s)" % projektIds, "")

Python lists can be created from Vertec lists by list(vertecliste).

Note that Vertec lists are “live”. That is, actions related to the logic of the list calculation may change, as shown in the following examples:

For remove() and delete(), the list is one shorter after each iteration. At the end, only half of the list is deleted. Therefore, to delete all objects in a list, it is best to convert them to a Python list:

for l in list(argobject.offeneleistungen):
    l.delete()

In the following case, it is a list of open services:

leistungen = phase.evalocl("offeneleistungen")
for l in leistungen:
    l.makeverrechnet()

If they are charged sequentially, they will automatically disappear from the list. The effect is the same as above: only half of the services will be charged. Instead, convert to a python list:

for l in list(phase.evalocl("offeneleistungen")):
    l.makeverrechnet()

'count’, 'pop’, 'reverse’ and 'sort’ are only available on Python lists. If you use these methods, you would have to rewrite them or use list(vertecliste) to revert the Vertec list to a Python list.