Skip to content

niceSmartCRM API Documentation

crm_cmd

Created on 2024-01-12

@author: wf

CrmCmd

Bases: WebserverCmd

Command line for Customer Relationship Management

Source code in crm/crm_cmd.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class CrmCmd(WebserverCmd):
    """
    Command line for Customer Relationship Management
    """

    def getArgParser(self, description: str, version_msg) -> ArgumentParser:
        """
        override the default argparser call
        """
        parser = super().getArgParser(description, version_msg)
        parser.add_argument(
            "-v",
            "--verbose",
            action="store_true",
            help="show verbose output [default: %(default)s]",
        )
        parser.add_argument(
            "-rp",
            "--root_path",
            default=CRM.root_path(),
            help="path to example dcm definition files [default: %(default)s]",
        )
        return parser

getArgParser(description, version_msg)

override the default argparser call

Source code in crm/crm_cmd.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def getArgParser(self, description: str, version_msg) -> ArgumentParser:
    """
    override the default argparser call
    """
    parser = super().getArgParser(description, version_msg)
    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="show verbose output [default: %(default)s]",
    )
    parser.add_argument(
        "-rp",
        "--root_path",
        default=CRM.root_path(),
        help="path to example dcm definition files [default: %(default)s]",
    )
    return parser

main(argv=None)

main call

Source code in crm/crm_cmd.py
40
41
42
43
44
45
46
47
48
49
def main(argv: list = None):
    """
    main call
    """
    cmd = CrmCmd(
        config=CrmWebServer.get_config(),
        webserver_cls=CrmWebServer,
    )
    exit_code = cmd.cmd_main(argv)
    return exit_code

crm_core

Created on 2024-01-12

@author: wf

Organizations

Bases: EntityManager

get organizations

Source code in crm/crm_core.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class Organizations(EntityManager):
    """
    get organizations
    """

    def __init__(self):
        super().__init__(entity_name="Organisation")

    def from_smartcrm(self, smartcrm_org_lod: List[Dict]) -> List[Dict]:
        """
        Convert a list of organizations from the smartcrm_org_lod format to a list of dictionaries
        with appropriate field names and types.

        Args:
            smartcrm_org_lod (List[Dict]): List of organizations in smartcrm_org_lod format.

        Returns:
            List[Dict]: A list of dictionaries with converted field names and types.
        """
        org_list = []
        for org in smartcrm_org_lod:
            converted_org = {
                "kind": org.get("art"),
                "industry": org.get("Branche"),
                "created_at": self._convert_to_datetime(org.get("createdAt")),
                "data_origin": org.get("DatenHerkunft"),
                "created_by": org.get("ErstelltVon"),
                "country": org.get("Land"),
                "last_modified": self._convert_to_datetime(org.get("lastModified")),
                "logo": org.get("logo", ""),
                "employee_count": self._convert_to_int(org.get("Mitarbeiterzahl")),
                "organization_number": org.get("OrganisationNummer"),
                "city": org.get("Ort"),
                "postal_code": org.get("PLZ"),
                "po_box": org.get("Postfach"),
                "sales_estimate": self._convert_to_int(org.get("salesEstimate")),
                "sales_rank": self._convert_to_int(org.get("salesRank")),
                "location_name": org.get("Standort"),
                "phone": org.get("Telefon"),
                "revenue": self._convert_to_int(org.get("Umsatz")),
                "revenue_probability": self._convert_to_int(
                    org.get("UmsatzWahrscheinlichkeit")
                ),
                "revenue_potential": self._convert_to_int(org.get("Umsatzpotential")),
                "country_dialing_code": org.get("VorwahlLand"),
                "city_dialing_code": org.get("VorwahlOrt"),
                "website": org.get("Web"),
                "importance": org.get("Wichtigkeit"),
            }
            org_list.append(converted_org)
        return org_list

from_smartcrm(smartcrm_org_lod)

Convert a list of organizations from the smartcrm_org_lod format to a list of dictionaries with appropriate field names and types.

Parameters:

Name Type Description Default
smartcrm_org_lod List[Dict]

List of organizations in smartcrm_org_lod format.

required

Returns:

Type Description
List[Dict]

List[Dict]: A list of dictionaries with converted field names and types.

Source code in crm/crm_core.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def from_smartcrm(self, smartcrm_org_lod: List[Dict]) -> List[Dict]:
    """
    Convert a list of organizations from the smartcrm_org_lod format to a list of dictionaries
    with appropriate field names and types.

    Args:
        smartcrm_org_lod (List[Dict]): List of organizations in smartcrm_org_lod format.

    Returns:
        List[Dict]: A list of dictionaries with converted field names and types.
    """
    org_list = []
    for org in smartcrm_org_lod:
        converted_org = {
            "kind": org.get("art"),
            "industry": org.get("Branche"),
            "created_at": self._convert_to_datetime(org.get("createdAt")),
            "data_origin": org.get("DatenHerkunft"),
            "created_by": org.get("ErstelltVon"),
            "country": org.get("Land"),
            "last_modified": self._convert_to_datetime(org.get("lastModified")),
            "logo": org.get("logo", ""),
            "employee_count": self._convert_to_int(org.get("Mitarbeiterzahl")),
            "organization_number": org.get("OrganisationNummer"),
            "city": org.get("Ort"),
            "postal_code": org.get("PLZ"),
            "po_box": org.get("Postfach"),
            "sales_estimate": self._convert_to_int(org.get("salesEstimate")),
            "sales_rank": self._convert_to_int(org.get("salesRank")),
            "location_name": org.get("Standort"),
            "phone": org.get("Telefon"),
            "revenue": self._convert_to_int(org.get("Umsatz")),
            "revenue_probability": self._convert_to_int(
                org.get("UmsatzWahrscheinlichkeit")
            ),
            "revenue_potential": self._convert_to_int(org.get("Umsatzpotential")),
            "country_dialing_code": org.get("VorwahlLand"),
            "city_dialing_code": org.get("VorwahlOrt"),
            "website": org.get("Web"),
            "importance": org.get("Wichtigkeit"),
        }
        org_list.append(converted_org)
    return org_list

db

Created on 2024-01-13

@author: wf

DB

Database wrapper for managing direct database connections and executing queries using PyMySQL.

Attributes:

Name Type Description
config Dict[str, Any]

Database configuration details.

connection Connection

PyMySQL connection instance.

Source code in crm/db.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class DB:
    """
    Database wrapper for managing direct database connections and executing queries using PyMySQL.

    Attributes:
        config (Dict[str, Any]): Database configuration details.
        connection (pymysql.connections.Connection): PyMySQL connection instance.
    """

    def __init__(self, config_path: str = None):
        """
        Initializes the database connection using provided configuration.

        Args:
            config_path (str, optional): Path to the configuration YAML file.
                                         Defaults to '~/.smartcrm/db_config.yaml'.
        """
        if config_path is None:
            config_path = f"{Path.home()}/.smartcrm/db_config.yaml"
        self.config = self.load_config(config_path)
        self.connection = self.create_connection()

    def load_config(self, path: str) -> Dict[str, Any]:
        """
        Loads the database configuration from a YAML file.

        Args:
            path (str): The file path of the YAML configuration file.

        Returns:
            Dict[str, Any]: A dictionary containing database configuration.
        """
        with open(path, "r") as file:
            return yaml.safe_load(file)["database"]

    def create_connection(self) -> pymysql.connections.Connection:
        """
        Creates a PyMySQL connection using the loaded configuration.

        Returns:
            pymysql.connections.Connection: PyMySQL connection instance.
        """
        config = {
            "host": self.config["host"],
            "user": self.config["user"],
            "password": self.config["password"],
            "db": self.config["name"],
            "charset": "utf8mb4",
            "cursorclass": pymysql.cursors.DictCursor,
        }
        return pymysql.connect(**config)

    def execute_query(self, query: str) -> List[Dict[str, Any]]:
        """
        Executes a SQL query and returns the results.

        Args:
            query (str): The SQL query to execute.

        Returns:
            List[Dict[str, Any]]: The result of the SQL query execution.
        """
        with self.connection.cursor() as cursor:
            cursor.execute(query)
            return cursor.fetchall()

    def close(self):
        """
        Closes the database connection.
        """
        if self.connection:
            self.connection.close()

__init__(config_path=None)

Initializes the database connection using provided configuration.

Parameters:

Name Type Description Default
config_path str

Path to the configuration YAML file. Defaults to '~/.smartcrm/db_config.yaml'.

None
Source code in crm/db.py
23
24
25
26
27
28
29
30
31
32
33
34
def __init__(self, config_path: str = None):
    """
    Initializes the database connection using provided configuration.

    Args:
        config_path (str, optional): Path to the configuration YAML file.
                                     Defaults to '~/.smartcrm/db_config.yaml'.
    """
    if config_path is None:
        config_path = f"{Path.home()}/.smartcrm/db_config.yaml"
    self.config = self.load_config(config_path)
    self.connection = self.create_connection()

close()

Closes the database connection.

Source code in crm/db.py
80
81
82
83
84
85
def close(self):
    """
    Closes the database connection.
    """
    if self.connection:
        self.connection.close()

create_connection()

Creates a PyMySQL connection using the loaded configuration.

Returns:

Type Description
Connection

pymysql.connections.Connection: PyMySQL connection instance.

Source code in crm/db.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def create_connection(self) -> pymysql.connections.Connection:
    """
    Creates a PyMySQL connection using the loaded configuration.

    Returns:
        pymysql.connections.Connection: PyMySQL connection instance.
    """
    config = {
        "host": self.config["host"],
        "user": self.config["user"],
        "password": self.config["password"],
        "db": self.config["name"],
        "charset": "utf8mb4",
        "cursorclass": pymysql.cursors.DictCursor,
    }
    return pymysql.connect(**config)

execute_query(query)

Executes a SQL query and returns the results.

Parameters:

Name Type Description Default
query str

The SQL query to execute.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: The result of the SQL query execution.

Source code in crm/db.py
66
67
68
69
70
71
72
73
74
75
76
77
78
def execute_query(self, query: str) -> List[Dict[str, Any]]:
    """
    Executes a SQL query and returns the results.

    Args:
        query (str): The SQL query to execute.

    Returns:
        List[Dict[str, Any]]: The result of the SQL query execution.
    """
    with self.connection.cursor() as cursor:
        cursor.execute(query)
        return cursor.fetchall()

load_config(path)

Loads the database configuration from a YAML file.

Parameters:

Name Type Description Default
path str

The file path of the YAML configuration file.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary containing database configuration.

Source code in crm/db.py
36
37
38
39
40
41
42
43
44
45
46
47
def load_config(self, path: str) -> Dict[str, Any]:
    """
    Loads the database configuration from a YAML file.

    Args:
        path (str): The file path of the YAML configuration file.

    Returns:
        Dict[str, Any]: A dictionary containing database configuration.
    """
    with open(path, "r") as file:
        return yaml.safe_load(file)["database"]

em

Created on 2024-01-13

@author: wf

CRM

CRM

Source code in crm/em.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class CRM:
    """
    CRM
    """

    def __init__(self):
        pass

    @classmethod
    def root_path(cls) -> str:
        """
        Get the root path dynamically based on the home directory.
        """
        home = str(Path.home())
        # Append the relative path to the home directory
        root_path = f"{home}/.smartcrm"
        return root_path

root_path() classmethod

Get the root path dynamically based on the home directory.

Source code in crm/em.py
22
23
24
25
26
27
28
29
30
@classmethod
def root_path(cls) -> str:
    """
    Get the root path dynamically based on the home directory.
    """
    home = str(Path.home())
    # Append the relative path to the home directory
    root_path = f"{home}/.smartcrm"
    return root_path

EntityManager

Generic Entity Manager

Source code in crm/em.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class EntityManager:
    """
    Generic Entity Manager
    """

    def __init__(self, entity_name: str, plural_name: str = None):
        self.entity_name = entity_name
        self.plural_name = plural_name if plural_name else f"{entity_name.lower()}s"
        # Handling first letter uppercase for JSON keys
        self.manager_name = (
            self.entity_name[0].upper() + self.entity_name[1:] + "Manager"
        )

    def _convert_to_datetime(self, date_value: Any) -> datetime:
        """
        Convert a value to a datetime object.

        Args:
            date_str (Any): Date value to convert.

        Returns:
            datetime: A datetime object.
        """
        if date_value is None:
            return None
        if isinstance(date_value, str):
            date_str = date_value
            parsed_date = datetime.fromisoformat(date_str) if date_str else None
        else:
            parsed_date = date_value
        return parsed_date

    def _convert_to_int(self, num_str: str) -> int:
        """
        Convert a string to an integer.

        Args:
            num_str (str): Numeric string to convert.

        Returns:
            int: An integer value.
        """
        if num_str is None:
            return None
        try:
            return int(num_str)
        except ValueError:
            return 0

    def from_db(self, db: DB) -> List[Dict]:
        """
        Fetch entities from the database.

        Args:
            db (DB): Database object to execute queries.

        Returns:
            List[Dict]: A list of entity dictionaries.
        """
        query = f"SELECT * FROM {self.entity_name}"
        smartcrm_lod = db.execute_query(query)
        lod = self.from_smartcrm(smartcrm_lod)
        return lod

    def from_json_file(self, json_path: str = None):
        """
        read my lod from the given json_path
        """
        if json_path is None:
            json_path = f"{CRM.root_path()}/{self.entity_name}.json"

        with open(json_path, "r") as json_file:
            smartcrm_data = json.load(json_file)
        # get the list of dicts
        smartcrm_lod = smartcrm_data[self.manager_name][self.plural_name][
            self.entity_name
        ]
        lod = self.from_smartcrm(smartcrm_lod)
        return lod

from_db(db)

Fetch entities from the database.

Parameters:

Name Type Description Default
db DB

Database object to execute queries.

required

Returns:

Type Description
List[Dict]

List[Dict]: A list of entity dictionaries.

Source code in crm/em.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def from_db(self, db: DB) -> List[Dict]:
    """
    Fetch entities from the database.

    Args:
        db (DB): Database object to execute queries.

    Returns:
        List[Dict]: A list of entity dictionaries.
    """
    query = f"SELECT * FROM {self.entity_name}"
    smartcrm_lod = db.execute_query(query)
    lod = self.from_smartcrm(smartcrm_lod)
    return lod

from_json_file(json_path=None)

read my lod from the given json_path

Source code in crm/em.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def from_json_file(self, json_path: str = None):
    """
    read my lod from the given json_path
    """
    if json_path is None:
        json_path = f"{CRM.root_path()}/{self.entity_name}.json"

    with open(json_path, "r") as json_file:
        smartcrm_data = json.load(json_file)
    # get the list of dicts
    smartcrm_lod = smartcrm_data[self.manager_name][self.plural_name][
        self.entity_name
    ]
    lod = self.from_smartcrm(smartcrm_lod)
    return lod

smart_crm

Created on 2024-01-13

@author: wf

version

Created on 2023-11-06

@author: wf

Version dataclass

Version handling for niceSmartCRM

Source code in crm/version.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@dataclass
class Version:
    """
    Version handling for niceSmartCRM
    """

    name = "niceSmartCRM"
    version = crm.__version__
    date = "2024-01-12"
    updated = "2024-01-12"
    description = "nicegui based Customer Relationship Management"

    authors = "Wolfgang Fahl"

    doc_url = "https://wiki.bitplan.com/index.php/niceSmartCRM"
    chat_url = "https://github.com/BITPlan/niceSmartCRM/discussions"
    cm_url = "https://github.com/BITPlan/niceSmartCRM"

    license = f"""Copyright 2024 contributors. All rights reserved.

  Licensed under the Apache License 2.0
  http://www.apache.org/licenses/LICENSE-2.0

  Distributed on an "AS IS" basis without warranties
  or conditions of any kind, either express or implied."""

    longDescription = f"""{name} version {version}
{description}

  Created by {authors} on {date} last updated {updated}"""

xmi

Created on 2024-01-14

@author: wf

Class dataclass

Bases: ModelElement

Source code in crm/xmi.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
@dataclass_json
@dataclass
class Class(ModelElement):
    is_abstract: Optional[str] = None
    attributes: Dict[str, Attribute] = field(default_factory=dict)
    operations: Dict[str, Operation] = field(default_factory=dict)
    roles: Dict[str, Role] = field(default_factory=dict)

    @classmethod
    def from_xmi_dict(cls, parent: ModelElement, node: Dict) -> "Class":
        class_ = super().from_xmi_dict(parent, node)
        class_.attributes={}
        class_.operations={}
        class_.roles={}
        class_.is_abstract = node.get("@isAbstract")
        # Process attributes
        for attr_list in node.get("attributes", {}).values():
            for attr in attr_list:
                attribute = Attribute.from_xmi_dict(class_, attr)
                class_.attributes[attribute.name] = attribute

        # Process operations
        for op_list in node.get('operations', {}).values():
            if isinstance(op_list,dict):
                op_list=[op_list]
            for op in op_list:
                operation = Operation.from_xmi_dict(class_, op)
                class_.operations[operation.name] = operation

        for role_list in node.get('roles', {}).values():
            if isinstance(role_list,dict):
                role_list=[role_list]
            for role_node in role_list:
                role=Role.from_xmi_dict(class_, role_node)
                class_.roles[role.name] = role
        return class_

    def add_to_lookup(self, lookup: Dict):
        super().add_to_lookup(lookup)  # Add the class itself
        for attribute in self.attributes.values():  # Add all attributes
            attribute.add_to_lookup(lookup)
        for operation in self.operations.values():  # Add all operations
            operation.add_to_lookup(lookup)
        for role in self.roles.values():  # Add all roles
            role.add_to_lookup(lookup)

    def as_plantuml(self, indentation:str ="")->str:
        """
        Generate PlantUML representation for this Class and its contents.

        Args:
            indentation (str): Indentation for the PlantUML code.

        Returns:
            str: The PlantUML representation for this Class and its contents.
        """
        plantuml = f"{indentation}class {self.short_name} {{\n"

        # Add attributes
        for _attr_name, attr in self.attributes.items():
            attr_type=attr.type
            if "enum" in attr_type:
                attr_type="enum"
            # [[{{{attr.documentation}}} {attr.short_name} ]]
            plantuml += f"{indentation}  {attr.short_name}: {attr_type}\n"

        # Add operations
        for _op_name, op in self.operations.items():
            operation_plantuml = op.as_plantuml(indentation + "  ")
            plantuml += f"{operation_plantuml}\n"

        plantuml += f"{indentation}}}\n"
        plantuml += f"""note top of {self.short_name}
{self.multi_line_doc(40)}
end note
"""
        return plantuml

as_plantuml(indentation='')

Generate PlantUML representation for this Class and its contents.

Parameters:

Name Type Description Default
indentation str

Indentation for the PlantUML code.

''

Returns:

Name Type Description
str str

The PlantUML representation for this Class and its contents.

Source code in crm/xmi.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
    def as_plantuml(self, indentation:str ="")->str:
        """
        Generate PlantUML representation for this Class and its contents.

        Args:
            indentation (str): Indentation for the PlantUML code.

        Returns:
            str: The PlantUML representation for this Class and its contents.
        """
        plantuml = f"{indentation}class {self.short_name} {{\n"

        # Add attributes
        for _attr_name, attr in self.attributes.items():
            attr_type=attr.type
            if "enum" in attr_type:
                attr_type="enum"
            # [[{{{attr.documentation}}} {attr.short_name} ]]
            plantuml += f"{indentation}  {attr.short_name}: {attr_type}\n"

        # Add operations
        for _op_name, op in self.operations.items():
            operation_plantuml = op.as_plantuml(indentation + "  ")
            plantuml += f"{operation_plantuml}\n"

        plantuml += f"{indentation}}}\n"
        plantuml += f"""note top of {self.short_name}
{self.multi_line_doc(40)}
end note
"""
        return plantuml

Model dataclass

Bases: Package

Model with option to read from XMI files which have been converted to JSON

Source code in crm/xmi.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
@dataclass_json
@dataclass
class Model(Package):
    """
    Model with option to read from
    XMI files which have been converted to JSON
    """

    @classmethod
    def raw_read_xmi_json(cls, file_path: str) -> Dict:
        """
        read the XMI file which has been converted to JSON with xq

        Args:
            file_path (str): the file_path to read from
        """
        with open(file_path, "r") as file:
            data = json.load(file)
        return data

    @classmethod
    def from_xmi_json(cls, file_path:str) -> "Model":
        """
        read the XMI file which has been converted to JSON with xq

        Args:
            file_path (str): the file_path to read from

        Returns:
            Model: the Model instance
        """
        data = cls.raw_read_xmi_json(file_path)
        model = cls.from_xmi_dict(None, data)
        model.create_lookup()
        return model

    def create_lookup(self):
        """
        create the lookup dict
        """
        self.lookup={}
        self.add_to_lookup(self.lookup)

    def as_plantuml(self, indentation=""):
        plant_uml=super().as_plantuml(indentation)
        for _model_id,element in self.lookup.items():

            if isinstance(element,Role):
                l_multi=""
                r_multi=""
                multi=element.multiplicity
                if multi:
                    multi_parts=multi.split("..")
                    if len(multi_parts)==2:
                        l_multi,r_multi=multi_parts
                        r_multi=f'"{r_multi}"'
                    else:
                        l_multi=multi_parts[0]
                    l_multi=f'"{l_multi}"'

                relation_plantuml = f"{element.parent.short_name} {l_multi} -- {r_multi} {element.type} : {element.short_name}"
                plant_uml += f"{indentation} {relation_plantuml}\n"
        return plant_uml

    def to_plant_uml(self) -> str:
        """
        Generate a PlantUML representation of the model.

        Returns:
            str: The PlantUML string.
        """
        skinparams="""
' BITPlan Corporate identity skin params
' Copyright (c) 2015-2024 BITPlan GmbH
' see http://wiki.bitplan.com/PlantUmlSkinParams#BITPlanCI
' skinparams generated by com.bitplan.restmodelmanager
skinparam note {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam component {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam package {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam usecase {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam activity {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam classAttribute {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam interface {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam class {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam object {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
hide circle
' end of skinparams '"""
        plant_uml = "@startuml\n"
        plant_uml += f"{skinparams}\n"
        plant_uml += self.as_plantuml("")
        plant_uml += "@enduml"
        return plant_uml

create_lookup()

create the lookup dict

Source code in crm/xmi.py
398
399
400
401
402
403
def create_lookup(self):
    """
    create the lookup dict
    """
    self.lookup={}
    self.add_to_lookup(self.lookup)

from_xmi_json(file_path) classmethod

read the XMI file which has been converted to JSON with xq

Parameters:

Name Type Description Default
file_path str

the file_path to read from

required

Returns:

Name Type Description
Model Model

the Model instance

Source code in crm/xmi.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
@classmethod
def from_xmi_json(cls, file_path:str) -> "Model":
    """
    read the XMI file which has been converted to JSON with xq

    Args:
        file_path (str): the file_path to read from

    Returns:
        Model: the Model instance
    """
    data = cls.raw_read_xmi_json(file_path)
    model = cls.from_xmi_dict(None, data)
    model.create_lookup()
    return model

raw_read_xmi_json(file_path) classmethod

read the XMI file which has been converted to JSON with xq

Parameters:

Name Type Description Default
file_path str

the file_path to read from

required
Source code in crm/xmi.py
370
371
372
373
374
375
376
377
378
379
380
@classmethod
def raw_read_xmi_json(cls, file_path: str) -> Dict:
    """
    read the XMI file which has been converted to JSON with xq

    Args:
        file_path (str): the file_path to read from
    """
    with open(file_path, "r") as file:
        data = json.load(file)
    return data

to_plant_uml()

Generate a PlantUML representation of the model.

Returns:

Name Type Description
str str

The PlantUML string.

Source code in crm/xmi.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
    def to_plant_uml(self) -> str:
        """
        Generate a PlantUML representation of the model.

        Returns:
            str: The PlantUML string.
        """
        skinparams="""
' BITPlan Corporate identity skin params
' Copyright (c) 2015-2024 BITPlan GmbH
' see http://wiki.bitplan.com/PlantUmlSkinParams#BITPlanCI
' skinparams generated by com.bitplan.restmodelmanager
skinparam note {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam component {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam package {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam usecase {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam activity {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam classAttribute {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam interface {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam class {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
skinparam object {
  BackGroundColor #FFFFFF
  FontSize 12
  ArrowColor #FF8000
  BorderColor #FF8000
  FontColor black
  FontName Technical
}
hide circle
' end of skinparams '"""
        plant_uml = "@startuml\n"
        plant_uml += f"{skinparams}\n"
        plant_uml += self.as_plantuml("")
        plant_uml += "@enduml"
        return plant_uml

ModelElement dataclass

Base model element class

Source code in crm/xmi.py
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@dataclass_json
@dataclass
class ModelElement:
    """
    Base model element class
    """
    name: str
    id: str
    stereotype: str
    visibility: str
    documentation: str
    tagged_values: Dict[str, TaggedValue] = field(default_factory=dict)

    @property
    def short_name(self) -> str:
        """
        for name: Logical View::com::bitplan::smartCRM::Organisation::Name
        return "Name"
        """
        short_name=ModelElement.as_short_name(self.name)
        return short_name

    def multi_line_doc(self, limit: int) -> str:
        """
        Returns the documentation as a multiline string with a limited length per line.
        Lines are broken at whitespace.

        :param limit: The maximum length of each line.
        :return: Multiline string.
        """
        text='\n'.join(textwrap.wrap(self.documentation, width=limit))
        return text

    def add_to_lookup(self,lookup:Dict):
        lookup[self.id]=self

    @classmethod
    def as_short_name(cls,name:str)->str:
        if name is None:
            return None
        short_name=name.split("::")[-1]
        return short_name

    @classmethod
    def from_xmi_dict(cls, parent: "ModelElement", node: Dict) -> "ModelElement":
        """
        Create a ModelElement instance from a dictionary.

        Args:
            parent (ModelElement): the parent ModelElement or None for the Model itself
            node (Dict): A dictionary representing a ModelElement.

        Returns:
            ModelElement: An instance of ModelElement.
        """
        element = cls(
            name=node.get("@name"),
            id=node.get("@id"),
            stereotype=node.get("@stereotype"),
            visibility=node.get("@visibility"),
            documentation=node.get("Documentation"),
        )
        element.parent=parent

        for tv_list in node.get("taggedValues", {}).values():
            for tv in tv_list:
                tagged_value = TaggedValue.from_xmi_dict(tv)
                element.tagged_values[tagged_value.name] = tagged_value

        return element

    def as_plantuml(self, _indentation=""):
        return ""

short_name: str property

for name: Logical View::com::bitplan::smartCRM::Organisation::Name return "Name"

from_xmi_dict(parent, node) classmethod

Create a ModelElement instance from a dictionary.

Parameters:

Name Type Description Default
parent ModelElement

the parent ModelElement or None for the Model itself

required
node Dict

A dictionary representing a ModelElement.

required

Returns:

Name Type Description
ModelElement ModelElement

An instance of ModelElement.

Source code in crm/xmi.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@classmethod
def from_xmi_dict(cls, parent: "ModelElement", node: Dict) -> "ModelElement":
    """
    Create a ModelElement instance from a dictionary.

    Args:
        parent (ModelElement): the parent ModelElement or None for the Model itself
        node (Dict): A dictionary representing a ModelElement.

    Returns:
        ModelElement: An instance of ModelElement.
    """
    element = cls(
        name=node.get("@name"),
        id=node.get("@id"),
        stereotype=node.get("@stereotype"),
        visibility=node.get("@visibility"),
        documentation=node.get("Documentation"),
    )
    element.parent=parent

    for tv_list in node.get("taggedValues", {}).values():
        for tv in tv_list:
            tagged_value = TaggedValue.from_xmi_dict(tv)
            element.tagged_values[tagged_value.name] = tagged_value

    return element

multi_line_doc(limit)

Returns the documentation as a multiline string with a limited length per line. Lines are broken at whitespace.

:param limit: The maximum length of each line. :return: Multiline string.

Source code in crm/xmi.py
57
58
59
60
61
62
63
64
65
66
def multi_line_doc(self, limit: int) -> str:
    """
    Returns the documentation as a multiline string with a limited length per line.
    Lines are broken at whitespace.

    :param limit: The maximum length of each line.
    :return: Multiline string.
    """
    text='\n'.join(textwrap.wrap(self.documentation, width=limit))
    return text

Operation dataclass

Bases: ModelElement

Source code in crm/xmi.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
@dataclass_json
@dataclass
class Operation(ModelElement):
    is_static: Optional[str] = None
    is_abstract: Optional[str] = None
    parameters: Dict[str, 'Parameter'] = field(default_factory=dict)

    @classmethod
    def from_xmi_dict(cls, parent: ModelElement, node: Dict) -> 'Operation':
        operation = super().from_xmi_dict(parent, node)
        operation.parameters={}
        operation.is_static = node.get('@isStatic')
        operation.is_abstract = node.get('@isAbstract')

        # Process parameters
        for param_list in node.get('parameters', {}).values():
            # return parameter
            if isinstance(param_list,dict):
                param_list=[param_list]
            for param in param_list:
                parameter = Parameter.from_xmi_dict(operation, param)
                operation.parameters[parameter.name] = parameter

        return operation

    def as_plantuml(self, indentation="")->str:
        """
        Generate PlantUML representation for this Operation.

        Args:
            indentation (str): Indentation for the PlantUML code.

        Returns:
            str: The PlantUML representation for this Operation.
        """
        plantuml = f"{indentation}{self.short_name}("

        # Add parameters
        params = []
        return_type=None
        for param_name, param in self.parameters.items():
            type_short=ModelElement.as_short_name(param.type)
            if not param_name.endswith("::return") and not param_name=="return":
                param_str = f"{param.short_name}: {type_short}"
                params.append(param_str)
            else:
                return_type=type_short

        # Handle return type
        if return_type:
            params.append(f"return: {return_type}")
        plantuml += ", ".join(params)
        plantuml += ")"
        return plantuml

as_plantuml(indentation='')

Generate PlantUML representation for this Operation.

Parameters:

Name Type Description Default
indentation str

Indentation for the PlantUML code.

''

Returns:

Name Type Description
str str

The PlantUML representation for this Operation.

Source code in crm/xmi.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def as_plantuml(self, indentation="")->str:
    """
    Generate PlantUML representation for this Operation.

    Args:
        indentation (str): Indentation for the PlantUML code.

    Returns:
        str: The PlantUML representation for this Operation.
    """
    plantuml = f"{indentation}{self.short_name}("

    # Add parameters
    params = []
    return_type=None
    for param_name, param in self.parameters.items():
        type_short=ModelElement.as_short_name(param.type)
        if not param_name.endswith("::return") and not param_name=="return":
            param_str = f"{param.short_name}: {type_short}"
            params.append(param_str)
        else:
            return_type=type_short

    # Handle return type
    if return_type:
        params.append(f"return: {return_type}")
    plantuml += ", ".join(params)
    plantuml += ")"
    return plantuml

Package dataclass

Bases: ModelElement

Source code in crm/xmi.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
@dataclass_json
@dataclass
class Package(ModelElement):
    packages: Dict[str, "Package"] = field(default_factory=dict)
    classes: Dict[str, "Class"] = field(default_factory=dict)

    @classmethod
    def from_xmi_dict(cls, parent: ModelElement, node: Dict) -> "Package":
        """
        Create a Package instance from a dictionary.

        Args:
            node (Dict): A dictionary representing a Package, with keys for package attributes.

        Returns:
            Package: An instance of Package.
        """
        # top level package handling
        if "Package" in node:
            pnode = node["Package"]
        else:
            pnode = node

        package = super().from_xmi_dict(parent, pnode)
        package.classes={}
        package.packages={}
        package.packages_by_name={}
        # Process classes
        for cl_list in pnode.get("classes", {}).values():
            for cl in cl_list:
                class_ = Class.from_xmi_dict(package, cl)
                package.classes[class_.name] = class_

        # Process sub-packages
        for sp in pnode.get("packages", {}).values():
            sub_package = Package.from_xmi_dict(package, sp)
            package.packages[sub_package.id] = sub_package
            package.packages_by_name[sub_package.name] = sub_package
        return package

    def add_to_lookup(self, lookup: Dict):
        super().add_to_lookup(lookup)  # Add the package itself
        for sub_package in self.packages.values():  # Add all sub-packages
            sub_package.add_to_lookup(lookup)
        for class_ in self.classes.values():  # Add all classes
            class_.add_to_lookup(lookup)

    def as_plantuml(self, indentation="")->str:
        """
        Generate PlantUML representation for this Package and its contents.

        Args:
            indentation (str): Indentation for the PlantUML code.

        Returns:
            str: The PlantUML representation for this Package and its contents.
        """
        plantuml = f"{indentation}package {self.short_name} {{\n"

        # Add classes within the package
        for _class_name, class_obj in self.classes.items():
            class_plantuml = class_obj.as_plantuml(indentation + "  ")
            plantuml += f"{class_plantuml}\n"

        # Add sub-packages within the package
        for _sub_package_name, sub_package_obj in self.packages.items():
            sub_package_plantuml = sub_package_obj.as_plantuml(indentation + "  ")
            plantuml += f"{sub_package_plantuml}\n"

        plantuml += f"{indentation}}}\n"
        plantuml+=f"""note top of {self.short_name}
{self.documentation}
end note
"""
        return plantuml

as_plantuml(indentation='')

Generate PlantUML representation for this Package and its contents.

Parameters:

Name Type Description Default
indentation str

Indentation for the PlantUML code.

''

Returns:

Name Type Description
str str

The PlantUML representation for this Package and its contents.

Source code in crm/xmi.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
    def as_plantuml(self, indentation="")->str:
        """
        Generate PlantUML representation for this Package and its contents.

        Args:
            indentation (str): Indentation for the PlantUML code.

        Returns:
            str: The PlantUML representation for this Package and its contents.
        """
        plantuml = f"{indentation}package {self.short_name} {{\n"

        # Add classes within the package
        for _class_name, class_obj in self.classes.items():
            class_plantuml = class_obj.as_plantuml(indentation + "  ")
            plantuml += f"{class_plantuml}\n"

        # Add sub-packages within the package
        for _sub_package_name, sub_package_obj in self.packages.items():
            sub_package_plantuml = sub_package_obj.as_plantuml(indentation + "  ")
            plantuml += f"{sub_package_plantuml}\n"

        plantuml += f"{indentation}}}\n"
        plantuml+=f"""note top of {self.short_name}
{self.documentation}
end note
"""
        return plantuml

from_xmi_dict(parent, node) classmethod

Create a Package instance from a dictionary.

Parameters:

Name Type Description Default
node Dict

A dictionary representing a Package, with keys for package attributes.

required

Returns:

Name Type Description
Package Package

An instance of Package.

Source code in crm/xmi.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
@classmethod
def from_xmi_dict(cls, parent: ModelElement, node: Dict) -> "Package":
    """
    Create a Package instance from a dictionary.

    Args:
        node (Dict): A dictionary representing a Package, with keys for package attributes.

    Returns:
        Package: An instance of Package.
    """
    # top level package handling
    if "Package" in node:
        pnode = node["Package"]
    else:
        pnode = node

    package = super().from_xmi_dict(parent, pnode)
    package.classes={}
    package.packages={}
    package.packages_by_name={}
    # Process classes
    for cl_list in pnode.get("classes", {}).values():
        for cl in cl_list:
            class_ = Class.from_xmi_dict(package, cl)
            package.classes[class_.name] = class_

    # Process sub-packages
    for sp in pnode.get("packages", {}).values():
        sub_package = Package.from_xmi_dict(package, sp)
        package.packages[sub_package.id] = sub_package
        package.packages_by_name[sub_package.name] = sub_package
    return package

TaggedValue dataclass

Source code in crm/xmi.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@dataclass_json
@dataclass
class TaggedValue:
    name: str
    value: Optional[str] = field(
        default=None
    )

    @classmethod
    def from_xmi_dict(cls, node: Dict) -> "TaggedValue":
        """
        Create a TaggedValue instance from a dictionary.

        Args:
            node (Dict): A dictionary representing a TaggedValue, with keys '@name' and 'Value'.

        Returns:
            TaggedValue: An instance of TaggedValue.
        """
        name = node.get("@name")
        value = node.get("Value")
        return cls(name=name, value=value)

from_xmi_dict(node) classmethod

Create a TaggedValue instance from a dictionary.

Parameters:

Name Type Description Default
node Dict

A dictionary representing a TaggedValue, with keys '@name' and 'Value'.

required

Returns:

Name Type Description
TaggedValue TaggedValue

An instance of TaggedValue.

Source code in crm/xmi.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@classmethod
def from_xmi_dict(cls, node: Dict) -> "TaggedValue":
    """
    Create a TaggedValue instance from a dictionary.

    Args:
        node (Dict): A dictionary representing a TaggedValue, with keys '@name' and 'Value'.

    Returns:
        TaggedValue: An instance of TaggedValue.
    """
    name = node.get("@name")
    value = node.get("Value")
    return cls(name=name, value=value)