Skip to main content

library

The YetiForceClient is a custom library that contains all the functions that are used in the code.

The file that contains them is the client.py file, the other documents contained in the wrapper are external sources for the library itself.

Here are described all the functions of the client.py file:

def __init__():

This __init__ method initializes an instance of the YetiForceClient class, setting up the necessary configurations and performing an initial login to the YetiForce API.

Parameters

  1. base_url: The base URL of the YetiForce API endpoint (e.g., https://example.com/api).
  2. api_key: An instance of ApiKey used for authentication.
  3. x_api_key: An additional security key for accessing the API.
  4. api_user: An instance of AuthUser representing the user credentials for login.

Initialization Steps

  1. Set Attributes:

    • self.lastTokenRenewal: Tracks the last token renewal time, initialized to 0.
    • self.base_url: Stores the base URL for making API requests.
    • self.api_key: Stores the ApiKey instance.
    • self.x_api_key: Stores the extra security key.
    • self.user: Stores the user credentials.
  2. Set Headers:

    Header

    API headers are a section of the requests used to transfer metadata about the request and the desired response

    The self.headers dictionary contains:

    • Authorization: The complete authentication string from api_key.getCompleteAuth().
    • Content-Type: Ensures JSON data is sent.
    • x-api-key: Adds the additional security key.
    • x-session-info and x-session-uptime: Metadata for session tracking.
    JSON

    JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications.

  3. Perform Login:

    • self.login_data = self.database_user_login(): Logs in the user by calling the database_user_login() method, which presumably interacts with the YetiForce API to authenticate.
    • self.token = self.login_data.get("token"): Extracts the API token from the login response for future API requests.
    • self.loggedUser = self.login_data.get("name"): Extracts the logged-in user's name.
  4. Log Success Messages:

    • Logs a message indicating successful login with the username.
    • Logs a message that the YetiForceClient was initialized with the provided base_url.

Purpose

This method serves as the setup for the YetiForceClient, ensuring it is ready to make authenticated API calls to the YetiForce system by:

  • Setting required attributes.
  • Preparing HTTP headers for secure communication.
  • Authenticating with the API and storing necessary tokens and user details.

Example Code Usage

client = YetiForceClient(
base_url="https://api.example.com",
api_key=ApiKey("my-key-id", "my-key-secret"),
x_api_key="secure-x-api-key",
api_user=AuthUser("username", "password")
)

Upon initialization:

  • The client authenticates with the YetiForce API.
  • Tokens and user details are stored for subsequent API calls.

_requesttoyeti()

This function is designed to make HTTP requests to the YetiForce API. It is a versatile method to interact with the API, supporting various HTTP methods (GET, POST, etc.), with automatic token handling for authentication.

Parameters

  1. method: The HTTP method to be used for the request (e.g., GET, POST, PUT, DELETE).
  2. path: The specific API endpoint path (relative to the base URL).
  3. data: The data to be sent in the request body. This is usually required for methods like POST or PUT, but may be None for methods like GET.
  4. TokenNeeded: A boolean flag indicating whether an API token is required for the request. If True, the function will include the token in the request headers.
  5. additional_headers: Any additional headers that the caller wants to include in the request. These will be merged with the default headers.

Initialization steps

  1. Construct the Full URL:

    • The function constructs the full URL for the request by combining the base URL (self.base_url) with the specific API endpoint path (path).
    • The resulting URL will be in the format:
      https://<base_url>/webservice/WebserviceStandard/<path>
  2. Headers Setup:

    • The headers dictionary is copied from self.headers (which was set during initialization) to avoid modifying the original header data.
    • If the TokenNeeded flag is True, it checks if the token needs to be renewed (i.e., if it has been more than 3000 seconds since the last renewal). If so, it calls the _RenewToken() method to refresh the token.
    • The x-token header is set to the current API token (self.token), allowing authentication for the request.
  3. Additional Headers:

    • If any additional_headers are provided, they are merged into the headers dictionary, allowing the caller to add custom headers (such as for custom authentication or special configurations).
  4. Logging:

    • The function logs the HTTP request being made, including the method and URL, for debugging purposes.
  5. Sending the Request:

    • The request is sent using requests.request(), which is a flexible method for sending any type of HTTP request. The method, URL, headers, and body data (if provided) are passed to it.
  6. Return the Response:

    • The response from the API request is returned to the caller. This is typically a Response object from the requests library, which contains details like the status code, headers, and body content of the response.

Purpose

This method is a core function for interacting with the YetiForce API, providing a simple interface for making authenticated API requests with flexible options for headers and request methods. The _requesttoyeti method simplifies making authenticated requests to the YetiForce API, handling token management and flexible header setup while supporting different HTTP methods and endpoints.

Example Code Usage

client = YetiForceClient(
base_url="https://api.example.com",
api_key=ApiKey("my-key-id", "my-key-secret"),
x_api_key="secure-x-api-key",
api_user=AuthUser("username", "password")
)

# Example GET request
response = client._requesttoyeti(
method="GET",
path="users",
TokenNeeded=True
)

# Example POST request with data
data = {"name": "New User", "email": "user@example.com"}
response = client._requesttoyeti(
method="POST",
path="users",
data=data,
TokenNeeded=True
)

In the example:

  • The client sends a GET request to the users endpoint of the YetiForce API, including the necessary authentication token.
  • It then sends a POST request to create a new user with the provided data.

def CreateUsers():

Parameters

The CreateUsers function takes two parameters:

  1. userName: A string representing the username of the new user to be created.
  2. password: A string representing the password for the new user.

Initialization Steps

  1. Logging:

    • The function logs a debug message indicating that a user with the given userName is being created. This helps in tracking the process for debugging purposes.
  2. Create User Instance:

    • The function creates and returns an instance of the AuthUser class, passing the userName and password as arguments to the constructor of AuthUser. This instance represents the newly created user.

Purpose

The CreateUsers function is designed to create a new AuthUser instance by taking a userName and password as input parameters. It logs the action for debugging and returns the created user instance, allowing the application to interact with this user object further, for example, to authenticate or store in a database.

Example Code Usage

# Create a new user
new_user = CreateUsers("john_doe", "securepassword123")

# Access the newly created user's attributes
print(new_user.userName) # Output: john_doe
print(new_user.password) # Output: securepassword123

In the example above, the CreateUsers function is called with a username and password to create a new AuthUser instance. The new_user object can then be used to interact with the user data in the application.


def CreateApiKey():

Parameters

The CreateApiKey function takes two parameters:

  1. Name: A string representing the name associated with the API key. This can be a descriptive label used to identify the API key.
  2. Password: A string representing the password for the API key. This is used for authentication when using the API key.

Initialization Steps

  1. Logging:

    • The function logs a debug message indicating that an API key with the given Name is being created. This helps with tracking the action for debugging purposes.
  2. Create ApiKey Instance:

    • The function creates and returns an instance of the ApiKey class, passing the Name and Password as arguments to its constructor. This instance represents the newly created API key, containing the name and password for authentication.

Purpose

The CreateApiKey function is responsible for creating a new ApiKey instance with a provided name and password. It logs the action and returns the created instance, allowing the application to use this API key for subsequent interactions with services that require authentication.

Example Code Usage

# Create a new API key
api_key = CreateApiKey("myApiKey", "securepassword123")

# Access the newly created API key's attributes
print(api_key.Name) # Output: myApiKey
print(api_key.Password) # Output: securepassword123

In this example, the CreateApiKey function is called with a name and password to create a new ApiKey instance. The api_key object can then be used for authentication in API requests.


def database_user_login():

Parameters

The database_user_login function does not take any parameters directly. It uses the self.user attribute, which is presumably set during the initialization of the class that this method belongs to. This self.user attribute contains the user credentials (username and password) that are needed to log in to the YetiForce API.

Initialization Steps

  1. Logging:

    • The function logs a debug message indicating that it is attempting to log in with the specified username from self.user.
  2. Prepare Login Data:

    • The path variable is set to "Users/Login", which is the API endpoint used for user authentication.
    • The payload is created by calling self.user.toObject(), which converts the self.user object into a format suitable for the API request, likely a dictionary with the username and password.
  3. Make the API Request:

    • The function calls the _requesttoyeti method with the following parameters:
      • HTTP method: POST
      • Endpoint path: "Users/Login"
      • Data: payload (user credentials)
      • TokenNeeded: False (indicating that no token is required for the login request)
    • The response object contains the result of the API request.
  4. Handle Response:

    • If the response status code is 200, it indicates a successful login. The function logs the success and returns the result from the response JSON.
    • If the response status code is 401, it indicates authentication failure. The function logs the error and raises an AuthenticationError with a specific message depending on the error returned by the API (such as "Invalid username or password").
    • For any other response code, the function logs a critical error and raises a YetiForceError indicating a connection issue with the YetiForce API.

Purpose

The purpose of the database_user_login function is to authenticate a user against the YetiForce API. It sends the user's credentials to the YetiForce login endpoint, handles different response codes (successful login, authentication failure, and connection issues), and raises appropriate exceptions when necessary. This function is a key part of the authentication process, ensuring that only valid users can interact with the API.

Example Code Usage

# Assuming `self.user` is an instance of AuthUser with the credentials
try:
login_data = self.database_user_login()
print("Login successful, token:", login_data["token"])
except AuthenticationError as e:
print("Authentication failed:", e)
except YetiForceError as e:
print("Connection error:", e)

In this example, the database_user_login method is called to log the user in. If the login is successful, the token and other login data are returned and can be used for subsequent API requests. If authentication fails or if there is a connection issue, appropriate exceptions are raised and caught, providing meaningful error messages.


def _CheckTokenExsist():

Parameters

The _CheckTokenExsist function does not take any parameters directly. It uses the self.token attribute. This self.token attribute is expected to contain the authentication token needed for subsequent API requests.

Initialization Steps

  1. Logging:

    • The function logs an informational message: "Checking if token exists" to track when the token check is happening.
  2. Check Token:

    • The function checks if the self.token attribute is not set (i.e., if not self.token). If the token is None, empty, or evaluates to False, it indicates that the token does not exist or is invalid.
  3. Handle Missing Token:

    • If the token is missing, the function logs an error message: "Token not found".
    • It then raises a TokenError exception with the message "Token not found", indicating that the authentication token is required but was not found.

Purpose

The _CheckTokenExsist function is used to ensure that an authentication token exists before making further API requests. It performs a simple check to verify whether the self.token is present. If the token is missing, it raises an error, preventing any further actions that require authentication. This is crucial for maintaining secure and valid communication with the API.

Example Code Usage

try:
self._CheckTokenExsist() # Ensure the token exists
# Proceed with API requests that require authentication
except TokenError as e:
print("Token error:", e)

In this example, the function _CheckTokenExsist is called to verify that the authentication token is available. If the token is missing, the function raises a TokenError, which is caught and handled by printing an error message. If the token exists, the program can proceed with subsequent actions that require authentication.


def _getToken():

Parameters

The _getToken function does not take any parameters. It relies on the database_user_login method, which handles user authentication and returns login data, including the authentication token.

Initialization Steps

  1. Logging:

    • The function logs a warning message: "Retrieving new token" to indicate that a new token is being requested.
  2. Call to database_user_login:

    • The function calls self.database_user_login(), which logs the user into the YetiForce API and retrieves the login data (including the token) from the API.
  3. Extract Token:

    • It then accesses the token key in the returned login data dictionary (.get("token")) and returns the token as the result of the function.

Purpose

The purpose of the _getToken function is to retrieve a new authentication token from the YetiForce API. This is essential for ensuring that the application has a valid token to perform subsequent API requests. The function relies on the database_user_login method for the authentication process and extracts the token from the returned login data.

Example Code Usage

try:
token = self._getToken() # Retrieve a new token
print("New token:", token)
except AuthenticationError as e:
print("Authentication failed:", e)

In this example, the function _getToken is called to retrieve a new token. If successful, the token is printed. If the database_user_login method raises an error (e.g., if authentication fails), the exception is caught and an error message is printed. This ensures that the token retrieval process is handled properly before making further API requests.


Here's a more accurate documentation for the _RenewToken method:

def _RenewToken(self, forcedTOKEN=True, forcedurl=None):

Method Signature

def _RenewToken(self, forcedTOKEN=True, forcedurl=None)

Parameters

  • forcedTOKEN (bool, optional):
    • Default is True
    • When True, forces the method to retrieve a new token
  • forcedurl (str, optional):
    • Default is None
    • Allows specifying an alternative URL for token retrieval (if needed)

Functionality

The _RenewToken method is designed to ensure a valid authentication token is available for API interactions.

Key Behaviors

  1. Token Retrieval:

    • When forcedTOKEN is True, the method calls self._getToken() to obtain a new token
    • This guarantees a fresh token is available for API requests
  2. Timestamp Tracking:

    • Updates self.lastTokenRenewal with the current timestamp using time.time()
    • Helps track when the token was last renewed
  3. Logging:

    • Logs an informational message before token renewal
    • Logs a warning message after successful token renewal

Example Usage

# Standard token renewal
client._RenewToken() # Uses default parameters

# Force token renewal even if current token seems valid
client._RenewToken(forcedTOKEN=True)

# Potentially override token retrieval URL (uncommon)
client._RenewToken(forcedurl='https://custom-token-endpoint.com')

def get_all_users():

Parameters

The get_all_users function does not take any parameters. It relies on the self.token attribute (checked by the _CheckTokenExsist method) for authentication when making the API request.

Initialization Steps

  1. Logging:

    • The function logs an informational message: "Retrieving all users" to indicate that it is initiating the process of retrieving user data.
  2. Check Token Validity:

    • Before making the API request, the function calls self._CheckTokenExsist(), which verifies that a valid authentication token is available. If no valid token is found, this method raises an error.
  3. Define Request Path:

    • The path variable is constructed using the DefaultModules.ShortTerm module and the RecordsList endpoint, which is used to retrieve the list of users from the YetiForce API.
  4. Send API Request:

    • The function calls the _requesttoyeti method with the following parameters:
      • HTTP method: GET
      • Path: The constructed path for retrieving user data.
      • Additional headers:
        • "x-max-rows": "20000": Specifies the maximum number of rows to return (20,000 in this case).
        • 'x-fields': '["sid", "pin", "fullname"]': Defines the fields to be retrieved for each user (in this case, sid, pin, and fullname).
    • The _requesttoyeti method sends the API request and returns the response.
  5. Return Response Data:

    • The function returns the JSON data from the response, which contains the list of all users retrieved from the YetiForce API.

Purpose

The get_all_users function is designed to retrieve a list of all users from the YetiForce API. It performs the necessary checks to ensure that the authentication token is valid before making the request. It constructs the API path, sends the request with appropriate headers, and returns the JSON response containing user data. This function is useful for getting a comprehensive list of users and their associated data from the YetiForce system.

Example Code Usage

try:
users_data = self.get_all_users() # Retrieve all users from the YetiForce API
print("All users retrieved successfully:", users_data)
except TokenError as e:
print("Authentication error:", e)
except Exception as e:
print("Error retrieving users:", e)

In this example, the function get_all_users is called to fetch all users from the YetiForce API. The retrieved user data is printed out. If the authentication token is invalid or another error occurs during the request, the corresponding exception is caught and an error message is displayed.


def get_user_by_query():

Query

A query in database management is a request for data.

Parameters

The get_user_by_query function takes two parameters:

  1. sid: The unique identifier for the user (likely a system ID or similar).
  2. pin: The personal identification number (PIN) associated with the user.

Both parameters are used to search for a specific user in the YetiForce system by matching the sid and pin values.

Initialization Steps

  1. Logging:

    • The function logs the sid and pin parameters to track the query being executed.
  2. Check Token Validity:

    • Before proceeding with the request, the function calls self._CheckTokenExsist(), which checks if a valid authentication token is available. If no valid token is found, an error is raised.
  3. Validate sid and pin:

    • The function checks whether the sid or pin parameters are missing. If either of them is not provided, it logs an error and returns a response indicating that the sid or pin was not found.
  4. Set Request Headers:

    • The headers_to_add dictionary is created, containing:
      • x-condition: A JSON-encoded condition to filter records based on sid and pin. The operator "e" indicates an exact match.
      • x-fields: Specifies which fields to retrieve for the user (in this case: sid, pin, fullname, and assignedgroup).
  5. Send API Request:

    • The function calls self._requesttoyeti to send a GET request to the API with the specified path and additional headers.
  6. Handle API Response:

    • If the API returns a valid response with user data, the function checks the numberOfRecords field to determine if a user was found. If no records are found, it logs the event and returns an appropriate error message.
    • If records are found, the first user's details are retrieved, and the function checks if the user’s assigned group is valid for login using YetiForceClient.getRawAssignedGroupForLogin.
    • The function also checks if the user’s assigned group is within the acceptable date range using is_today_in_range.
    • If the user passes these checks, the function prepares a response with the user's details.
  7. Error Handling:

    • If no user is found, if the user is not in the valid range, or if any errors occur during the API request, the function logs the error and returns a failure response or raises an exception.

Purpose

The purpose of the get_user_by_query function is to retrieve a user’s data from the YetiForce API based on the provided sid and pin. The function performs several checks to ensure the validity of the query, including validating the token, ensuring that the sid and pin are provided, and confirming the user's assigned group and date range. It returns detailed information about the user if found, or an error message if any of the checks fail. This function is useful for fetching specific user data securely and reliably.

Example Code Usage

# Example: Retrieving a user by SID and PIN
sid = "12345"
pin = "67890"

try:
user_info = self.get_user_by_query(sid, pin) # Retrieve user information by SID and PIN
if user_info["code"] == "200":
print("User found:", user_info["data"])
else:
print("Error:", user_info["data"]) # Error message (e.g., user not found or invalid range)
except APIError as e:
print("Error calling the API:", e)

In this example, the function get_user_by_query is called with a specific sid and pin. If a user is found, their information is printed. If no user is found, or if any error occurs (e.g., invalid token or date range), an appropriate error message is displayed. The APIError exception is raised if there is an issue with the API call itself.


def try_login():

Parameters

The try_login function takes two parameters:

  1. sid: The unique identifier for the user (likely a system ID or similar).
  2. pin: The personal identification number (PIN) associated with the user.

These parameters are passed to the get_user_by_query function to search for the user in the system.

Initialization Steps

  1. Call get_user_by_query:

    • The function calls get_user_by_query(sid, pin) to check if a user with the given sid and pin exists in the system.
  2. Evaluate Query Response:

    • The function checks the response (qury) from get_user_by_query. Specifically, it looks at the "code" field to determine if the user was found.
  3. Return Appropriate Response:

    • If the "code" returned from get_user_by_query is "200", indicating that the user exists, it returns a dictionary with:
      • code: 200 to indicate a successful login.
      • data: A success message ("User exists").
    • If the "code" is anything other than "200", it returns a dictionary with:
      • code: The code returned from get_user_by_query (indicating an error or failure).
      • data: The error message returned from get_user_by_query.

Purpose

The purpose of the try_login function is to attempt to log a user in by validating the provided sid and pin. It leverages the get_user_by_query function to check the user's credentials, and based on the result, it returns a response indicating whether the user exists or if there was an error (e.g., user not found, invalid credentials). This function serves as a higher-level utility for logging in users and handling login-related errors.

Example Code Usage

# Example: Attempting to log in a user with SID and PIN
sid = "12345"
pin = "67890"

login_result = self.try_login(sid, pin)

if login_result["code"] == 200:
print("Login successful:", login_result["data"])
else:
print("Login failed:", login_result["data"])

In this example, the try_login function is called with a specific sid and pin. If the login is successful (i.e., the user exists), it prints a success message. If the login fails (e.g., user not found or invalid credentials), it prints an error message based on the response data.


Parameters:

  1. sid: A session ID used to identify the current user or session.
  2. pin: A personal identification number (PIN) associated with the user.
  3. moduleName: The name of the module from which related fields are being fetched.
  4. relatedModuleName: The name of the related module that contains the relevant data.
  5. additional_headers (optional): Additional headers to be included in the request, useful for authentication or passing extra information.

Initialization Steps:

  1. Initialize a returner dictionary: This dictionary is used to store the function’s output. It starts with a code "1" (indicating some failure) and data set to "null".

  2. Get user record: The function calls get_user_by_query(sid, pin) to fetch user details. If the status code is not "200", the function returns the error code and message from the record.

  3. Check for a valid record ID: The function checks if the recordId is present in the response. If not, it logs an error and returns an error code "401" with the message "Record ID not found".

  4. Construct URL for related records: The path is dynamically generated to retrieve the related fields, using the provided moduleName, relatedModuleName, and the recordId.

  5. Make an API request: The function sends a GET request to the generated path with any additional headers.

  6. Process the response: If the response contains related records, they are returned; otherwise, an error is logged indicating no related fields were found.

Purpose:

This function is designed to fetch related fields of a record from a specific module in a database or API, given a user's session ID and personal PIN. It handles errors such as missing user records or related fields and provides structured feedback through the returner dictionary. It is useful in systems where users need to retrieve related data from different modules based on a specific record.

Example Code Usage:


# Initialize parameters
sid = "user_session_123"
pin = "user_pin_123"
moduleName = "Users"
relatedModuleName = "Contacts"
additional_headers = {"Authorization": "Bearer token123"}

# Call the function to get related fields
result = self.get_related_fields(sid, pin, moduleName, relatedModuleName, additional_headers)

# Check the returned result
if result["code"] == "200":
print("Related fields retrieved successfully:")
print(result["data"])
else:
print(f"Error: {result['data']}")

In this example, the function attempts to retrieve related contact information for a user in the "Users" module. If successful, it prints the related records; if not, it shows an error message.


def _create_entry():

Parameters:

  1. module: The name of the module where the new entry will be created (e.g., "Users," "Products").
  2. data: A dictionary containing the information that needs to be created in the module.
  3. additional_headers (optional): Extra headers to be included in the request, such as for authentication or content type specification.

Initialization Steps:

  1. Log the module name: The function logs an informational message to indicate that a new entry is being created in the specified module.

  2. Check Token Existence: The function calls _CheckTokenExsist() to ensure that the necessary authentication token is available for the request. This step likely handles token validation or renewal.

  3. Construct URL for request: The URL path is dynamically generated using the provided module name, specifically targeting the Record endpoint for creating new entries.

  4. Make POST request: A POST request is made to the generated path with the provided data, optional additional_headers, and a flag indicating that a token is needed for the request.

Purpose:

This function is used to create a new record in a specified module. It sends a POST request to an API endpoint designed for creating records, with the provided data. It handles authentication and sends the data as part of the request. The function returns the JSON response containing the details of the newly created entry, which might include success or error messages depending on the outcome.

Example Code Usage:

# Initialize parameters
module = "Users"
data = {
"name": "John Doe",
"email": "john.doe@example.com",
"age": 30
}
additional_headers = {"Authorization": "Bearer token123"}

# Call the function to create a new user entry
response = self._create_entry(module, data, additional_headers)

# Check the returned response
if response.get("status") == "success":
print("User created successfully:", response["data"])
else:
print(f"Error creating user: {response.get('message')}")

In this example, the function attempts to create a new user in the "Users" module with the provided data. The result is checked for success, and the newly created user's information is printed if successful, or an error message is shown otherwise.


def _edit_entry():

Parameters:

  • module: This specifies the module where the entry is located, which is a string representing the name of the module (e.g., "users", "products").
  • data: This is the data to be updated for the specified entry. It could be a dictionary containing the new values for the entry fields.
  • record_id: This is the unique identifier (ID) of the entry to be edited. It helps locate the specific record in the module.
  • additional_headers: This is an optional parameter that allows adding extra headers to the HTTP request. It defaults to None if no extra headers are needed.

Initialization Steps:

  1. Logging: The function logs an info message to indicate that an entry in the given module is being edited.
  2. Token Check: The function calls self._CheckTokenExsist() to ensure a valid token exists before proceeding with the request.
  3. Path Setup: The URL path for the API request is constructed using the module and record_id to target the correct record.
  4. HTTP Request: The function sends an HTTP PUT request to the API endpoint using the constructed path and provided data. It also includes any additional headers if provided.

Purpose:

This function is used to edit or update an existing entry in a specified module. It performs the update by making an API request with the given data and record ID. The purpose is to allow modifications to a record within the specified module on the server, typically as part of a web service or API interaction.

Example Code Usage:

module = "users"
data = {
"name": "John Doe",
"email": "johndoe@example.com"
}
record_id = 12345
additional_headers = {"Authorization": "Bearer some-token"}

response = api_instance._edit_entry(module, data, record_id, additional_headers)

print(response) # This will print the JSON response containing the edited entry.

In this example, the function is used to update the user's name and email in the "users" module, targeting the record with ID 12345. It sends the updated data along with an authorization token in the headers.


def getRawFamily():

Parameters:

  • response: This parameter is expected to be a dictionary containing the response data, typically from an API or web service. The function specifically looks for a key named 'data' in the dictionary, which should contain family-related information.

Initialization Steps:

  1. Logging: The function logs a debug message to indicate the process of retrieving the raw family from the given response.
  2. Date Setup: The function gets the current date formatted as DD/MM/YYYY using datetime.now().strftime('%d/%m/%Y') and stores it in the today variable.
  3. Variable Initialization: It initializes raw_family to None, which will be updated if the correct family is found.
  4. Try-Except Block: The function is wrapped in a try-except block to handle potential errors (such as missing or malformed data) gracefully.

Purpose:

The function is designed to extract the "raw" family data from the response dictionary, specifically looking for a family that is available based on the current date. It checks whether the available date range (from 'available_from' to 'available_to') encompasses the current date, and if so, it retrieves the "raw" family information within the 'host_family' key. The function returns this "raw" family data or None if no such data is found or an error occurs.

Example Code Usage:

response = {
'data': {
'family_1': {
'available_from': '01/12/2024',
'available_to': '15/12/2024',
'host_family': {'raw': 'Family_A'}
},
'family_2': {
'available_from': '20/12/2024',
'available_to': '25/12/2024',
'host_family': {'raw': 'Family_B'}
}
}
}

raw_family = getRawFamily(response)
print(raw_family) # This would print 'Family_A' if the current date is between 01/12/2024 and 15/12/2024.

In this example, the function checks the availability of families in the response, and since family_1 is available during the current date, it returns 'Family_A'.


def getRawAssignedGroup():

Parameters

  • response (dict): The function takes a dictionary response as input. It expects the dictionary to contain a key 'data' and within that, another key 'assignedgroup'. The function will look for the 'raw' key inside 'assignedgroup' to return its value.

Initialization Steps

  • assigned_group_raw (None): The function initializes a variable assigned_group_raw to None. This will hold the value of the 'raw' key if it exists in the response, or remain None if not found.

Purpose

The purpose of the function is to check if the provided response contains the necessary nested keys ('data', 'assignedgroup', and 'raw'). If these keys are present, it returns the value of raw inside 'assignedgroup'. If any of these keys are missing, it will return None.

Example Code Usage

response = {
'data': {
'assignedgroup': {
'raw': 'group_data_value'
}
}
}

# Call the function with the response dictionary
result = getRawAssignedGroup(response)

print(result) # Output: 'group_data_value'

In this example, the function successfully retrieves the value 'group_data_value' from the raw key inside the 'assignedgroup' object within the data field.

Another Example (Missing Data)

response = {
'data': {
'assignedgroup': {}
}
}

result = getRawAssignedGroup(response)

print(result) # Output: None

In this case, the 'raw' key is missing, so the function will return None.


def getRawAssignedGroupForLogin():

Parameters

  • response (dict): The function accepts a dictionary response, which is expected to contain several nested keys. Specifically, the function looks for the 'result' key, which should contain a dictionary with a 'records' key. Each record within 'records' should have an 'assignedgroup' key, from which it extracts the 'raw' value.

Initialization Steps

  • first_record (dict): The function attempts to retrieve the first record in the response['result']['records'] dictionary using next(iter(response['result']['records'].values())). This gets the first item in the 'records' dictionary, assuming it's not empty.
  • assigned_group_raw (None): The function initializes assigned_group_raw to None. This will hold the 'raw' value from the 'assignedgroup' field if it exists, or remain None if any error occurs (e.g., missing keys or invalid data types).

Purpose

The purpose of this function is to extract the 'raw' value from the 'assignedgroup' key for the first record in the response data. The function ensures that even if the 'assignedgroup' or its 'raw' key is missing, or if the response structure is not as expected, it gracefully handles the situation by returning None. This makes the function resilient to variations in the input structure.

Example Code Usage

response = {
'status': 1,
'result': {
'headers': {
'sid': 'SID',
'pin': 'PIN',
'fullname': 'Full Name',
'assignedgroup': 'Assigned Group'
},
'records': {
'81463': {
'recordLabel': 'Michele Parenti',
'sid': '200000',
'pin': '0000',
'fullname': 'Michele Parenti',
'assignedgroup': {
'value': 'Cumacini',
'raw': 78839,
'referenceModule': 'ClosedGroups',
'state': 'Active',
'isPermitted': True
}
}
},
'permissions': {
'81463': {
'isEditable': True,
'moveToTrash': True
}
},
'numberOfRecords': 1,
'isMorePages': False
}
}

# Call the function with the response dictionary
result = getRawAssignedGroupForLogin(response)

print(result) # Output: 78839

In this example, the function successfully retrieves the value 78839 from the 'raw' key inside the 'assignedgroup' field for the first record in 'records'.

Another Example (Missing Data)

response = {
'status': 1,
'result': {
'records': {}
}
}

result = getRawAssignedGroupForLogin(response)

print(result) # Output: None

In this case, the 'records' dictionary is empty, so the function will return None as there is no 'assignedgroup' field to extract the 'raw' value from.


def create_feedback_family():

Parameters

  • sid (str): The SID (Student ID or unique identifier) of the user for whom the feedback is being created.
  • pin (str): The PIN associated with the user for authentication and lookup.
  • feedbackBody (str): The main feedback content that the user is submitting.
  • additional_headers (dict, optional): Any additional headers that should be included in the request when creating the feedback. This is an optional parameter.
  • genralScore (int, optional): The general score for the feedback, if applicable. This is an optional parameter.
  • foodScore (int, optional): The food-related score for the feedback, if applicable. This is an optional parameter.
  • cleaningScore (int, optional): The cleaning-related score for the feedback, if applicable. This is an optional parameter.
  • content (str, optional): Any extra content or remarks related to the feedback. This is an optional parameter.

Initialization Steps

  • record (dict): The function first retrieves the user record using self.get_user_by_query(sid, pin), which returns the user's details based on the provided sid and pin.
  • recordid (str): The recordid is extracted from the user record. If no recordid is found, an error is logged, and the function returns a failure response.
  • family (dict): The function retrieves the related family fields using self.get_related_fields(sid, pin, DefaultModules.ShortTerm, DefaultModules.Hostfamilies), which pulls in the family data associated with the user.
  • raw_fam_id (str): The raw family ID is obtained from the YetiForceClient.getRawFamily(family) function. If the family ID is missing, an error is logged, and the function returns a failure response.
  • raw_assigned_group (str): The raw assigned group for the user is fetched from YetiForceClient.getRawAssignedGroup(record). Similarly, if the assigned group is missing, an error is logged, and the function returns a failure response.

Purpose

The purpose of this function is to create a new feedback entry or update an existing one for a user in the host family feedback module. It ensures that necessary information, such as the user record, family ID, and assigned group, are valid before creating the feedback. Additionally, it supports scoring (general, food, cleaning) and allows extra content or headers to be added. Based on whether the user already has feedback, the function either creates a new feedback entry or edits an existing one.

Example Code Usage

# Example feedback creation
sid = "200000"
pin = "0000"
feedbackBody = "The family was very welcoming and supportive."
genralScore = 8
foodScore = 7
cleaningScore = 9
content = "The food was good, but could use more variety."

response = create_feedback_family(sid, pin, feedbackBody, genralScore=genralScore, foodScore=foodScore, cleaningScore=cleaningScore, content=content)

print(response)

Another Example (No Scores)

# Example feedback creation without scores
sid = "200001"
pin = "1234"
feedbackBody = "The family was friendly and the experience was great."

response = create_feedback_family(sid, pin, feedbackBody)

print(response)

In this example, the feedback is created without scores for food, general, or cleaning, and only the text of the feedback is provided.

Key Functional Flow:

  1. Record Retrieval: It first retrieves the user record using the sid and pin.
  2. Family and Group Validation: It checks if both the family ID and the assigned group are present.
  3. Feedback Construction: It constructs the feedback dictionary, including optional score parameters if provided.
  4. Feedback Creation or Edit: It checks if feedback already exists for the user. If it does, the feedback is edited; otherwise, a new entry is created.

Return Value

  • The function returns a JSON response containing the newly created or edited feedback entry. This could include success or failure data, depending on the outcome.

def create_job_placement_feedback():

Parameters

  • sid (str): The SID (Student ID or unique identifier) of the user submitting the feedback.
  • pin (str): The PIN associated with the user for authentication and data retrieval.
  • feedbackBody (str): The main content of the feedback provided by the user about their job placement experience.
  • overallResult (str, optional): The overall result of the job placement (e.g., positive, negative). This is an optional parameter.
  • typeOftasks (str, optional): Describes the type of tasks the user was involved with during their job placement. This is an optional parameter.
  • haveYouLearned (str, optional): Indicates whether the user has learned something new during the placement. This is an optional parameter.
  • expirianceSatis (str, optional): The user's satisfaction level with the overall experience. This is an optional parameter.
  • overallExperience (str, optional): A description of the user's overall experience during the job placement. This is an optional parameter.
  • comments (str, optional): Any additional comments the user wants to add about their job placement. This is an optional parameter.
  • whynottell (str, optional): A reason provided by the user if they are withholding feedback or certain details. This is an optional parameter.
  • additional_headers (dict, optional): Additional headers to be included with the feedback request. This is an optional parameter.
  • problemsawareness (str, optional): Describes the user's awareness of any problems or challenges faced during the job placement. This is an optional parameter.

Initialization Steps

  • record (dict): The function starts by retrieving the user record using self.get_user_by_query(sid, pin), which returns the user's details, including their recordId.
  • raw_assigned_group (str): The function retrieves the raw assigned group ID using YetiForceClient.getRawAssignedGroup(record), which helps in identifying the user's group.
  • raw_job_placement_id (str): It fetches the job placement ID using YetiForceClient.getCompanyrawidFromInternPlace(job_placement), which is based on the user's job placement record.
  • Validation: The function checks for the presence of the recordId, raw_assigned_group, and raw_job_placement_id. If any of these are missing, it logs an error and returns a failure response with the appropriate error message.

Purpose

The purpose of this function is to facilitate the creation or updating of a job placement feedback entry. It collects various pieces of feedback from the user, such as overall satisfaction, tasks performed, learning outcomes, and comments. It ensures that all necessary information, like the user's record ID, assigned group, and job placement ID, is valid before proceeding with creating the feedback. The function also supports both creating new feedback entries and editing existing ones, depending on whether the user has already submitted feedback for the job placement.

Example Code Usage

# Example job placement feedback creation
sid = "200000"
pin = "0000"
feedbackBody = "The job placement was challenging but very rewarding."
overallResult = "Positive"
typeOftasks = "Software development"
haveYouLearned = "Yes, I learned new programming skills."
expirianceSatis = "Very satisfied"
overallExperience = "Great learning experience with hands-on projects."
comments = "Would love to work with this company again."
whynottell = "N/A"
additional_headers = {"Authorization": "Bearer token"}
problemsawareness = "None"

response = create_job_placement_feedback(sid, pin, feedbackBody, overallResult=overallResult, typeOftasks=typeOftasks,
haveYouLearned=haveYouLearned, expirianceSatis=expirianceSatis,
overallExperience=overallExperience, comments=comments, whynottell=whynottell,
additional_headers=additional_headers, problemsawareness=problemsawareness)

print(response)

Another Example (Without Optional Parameters)

# Example job placement feedback creation with only required parameters
sid = "200001"
pin = "1234"
feedbackBody = "The placement was good, and I gained valuable experience."

response = create_job_placement_feedback(sid, pin, feedbackBody)

print(response)

In this case, the function creates a job placement feedback entry with just the required parameters, without including optional ones like comments, typeOftasks, or problemsawareness.

Key Functional Flow:

  1. User and Job Placement Validation: It retrieves the user record and validates the presence of necessary fields, including the recordId, assigned group, and job placement ID.
  2. Feedback Construction: The function constructs a feedback dictionary containing all the feedback-related fields, including any optional parameters if provided.
  3. Feedback Creation or Edit: It checks if the user has already submitted feedback for the job placement. If so, it edits the existing feedback; otherwise, it creates a new feedback entry.
  4. API Interaction: The function interacts with the backend API to create or edit the feedback entry and logs the response.

Return Value

  • The function returns a JSON response containing either the newly created or edited job placement feedback entry. This response includes success or failure data, depending on the outcome of the creation or edit operation.

def create_erasmus_feedback():

Parameters

  • sid (str): The SID (Student ID or unique identifier) of the user providing the feedback.
  • pin (str): The PIN associated with the user for authentication and data retrieval.
  • feedbackBody (str): The main content of the feedback about the user's Erasmus visit.
  • visitunderstanding (str): The user's understanding of the Erasmus visit.
  • professionalism (str): The professionalism demonstrated during the Erasmus visit.
  • visittopic (str): The topic or subject of the Erasmus visit.
  • visitinterest (str): The level of interest the user had in the Erasmus visit.
  • adequacy (str): The adequacy of the Erasmus visit or related activities.
  • overallexperience (str): The user's overall experience during the Erasmus visit.
  • suggestionworkshop (str, optional): Suggestions related to the workshop during the Erasmus visit (optional).
  • suggestionpremises (str, optional): Suggestions for the premises or facilities during the Erasmus visit (optional).

Initialization Steps

  • user (dict): The function retrieves the user record using self.get_user_by_query(sid, pin), which returns the user's details, including their recordId.
  • recordid (str): The recordId is extracted from the user record. If no recordId is found, the function logs an error and returns a failure response.
  • groupraw (str): The function retrieves the raw assigned group ID using YetiForceClient.getRawAssignedGroup(user), which helps identify the user's assigned group.
  • Validation: The function checks whether the recordId and groupraw are present. If either is missing, it logs an error and returns a failure response with an appropriate error message.

Purpose

The purpose of this function is to manage the creation or updating of Erasmus feedback for a user. It collects various pieces of feedback regarding the Erasmus visit, such as understanding, professionalism, topics, interest, experience, and suggestions. The function ensures that the necessary information is available before proceeding to either create a new feedback entry or update an existing one. It interacts with the backend system to store or modify the feedback.

Example Code Usage

# Example Erasmus feedback creation
sid = "200000"
pin = "0000"
feedbackBody = "The Erasmus visit was highly educational, and the workshop was well-organized."
visitunderstanding = "Clear understanding of the visit."
professionalism = "The visit was conducted professionally."
visittopic = "The topic covered was related to international collaboration."
visitinterest = "I was very interested in the topic."
adequacy = "The visit was adequately planned."
overallexperience = "Overall, it was a great experience with valuable insights."
suggestionworkshop = "More interactive activities in future workshops."
suggestionpremises = "Improvement in premises accessibility would be helpful."

response = create_erasmus_feedback(sid, pin, feedbackBody, visitunderstanding=visitunderstanding,
professionalism=professionalism, visittopic=visittopic,
visitinterest=visitinterest, adequacy=adequacy,
overallexperience=overallexperience,
suggestionworkshop=suggestionworkshop,
suggestionpremises=suggestionpremises)

print(response)

Another Example (Without Optional Parameters)

# Example Erasmus feedback creation without optional parameters
sid = "200001"
pin = "1234"
feedbackBody = "The Erasmus visit was informative and helpful."

response = create_erasmus_feedback(sid, pin, feedbackBody, visitunderstanding="Good understanding",
professionalism="Professional", visittopic="Cultural exchange",
visitinterest="Very interested", adequacy="Adequate",
overallexperience="Great overall experience")

print(response)

Key Functional Flow:

  1. User and Group Validation: The function retrieves the user’s record and validates the presence of both recordId and groupraw.
  2. Feedback Construction: The function constructs a feedback dictionary with all relevant fields, including any optional parameters such as suggestions for workshops or premises.
  3. Feedback Creation or Edit: It checks if feedback has already been submitted for the user. If feedback exists, it updates the existing entry; otherwise, it creates a new feedback entry.
  4. API Interaction: The function interacts with the backend API to create or edit the feedback entry and logs the response.

Return Value

  • The function returns a JSON response containing either the newly created or updated Erasmus feedback entry. The response includes data about the success or failure of the feedback creation or update operation.

create_hybrid_feedback():

Parameters

  • sid (str): The SID (Student ID or unique identifier) of the user providing the feedback.
  • pin (str): The PIN associated with the user for authentication and data retrieval.
  • feedbackbody (str): The main content of the feedback regarding the hybrid experience, summarizing the user's thoughts and opinions.
  • overallexperience2 (str): The user's overall experience with the hybrid program or event.
  • learning_experience (str): The user's learning experience during the hybrid program or event.
  • like_visits (str): The user's opinion about the visits related to the hybrid program.
  • overallexperience (str): The user's overall opinion about the hybrid program or event.
  • typeactivities (str): The type of activities involved in the hybrid program or event (e.g., workshops, discussions, etc.).
  • satisfied (str): The user's level of satisfaction with the hybrid program or event.
  • comments (str, optional): Any additional comments the user might have about their experience (optional).

Initialization Steps

  • user (dict): The function first retrieves the user’s record using self.get_user_by_query(sid, pin) to obtain the recordId and other relevant details.
  • recordid (str): The recordId is extracted from the user record. If no recordId is found, the function returns a failure response with a message indicating that the Record ID was not found.
  • groupid (str): The function retrieves the raw assigned group ID using YetiForceClient.getRawAssignedGroup(user) to identify the group to which the user belongs. If the groupid is not found, the function logs an error and returns a failure response.

Purpose

The primary purpose of this function is to gather feedback from users regarding their experience with a hybrid program. The feedback includes both qualitative data (comments, learning experience) and quantitative data (satisfaction levels, type of activities). After collecting this data, the function constructs a feedback entry and submits it to the system. The function also checks for the existence of required data (e.g., recordId, groupid) to ensure the feedback can be properly recorded. If any required data is missing, it returns an error response.

Example Code Usage

# Example hybrid feedback creation
sid = "200000"
pin = "0000"
feedbackbody = "The hybrid program was engaging and informative, especially the interactive workshops."
overallexperience2 = "Excellent"
learning_experience = "I learned a lot about new technologies and practical applications."
like_visits = "The site visits were very informative and well organized."
overallexperience = "Overall, I had a positive experience and would recommend it."
typeactivities = "Workshops, Site visits, Group discussions"
satisfied = "Very satisfied"
comments = "I look forward to similar future programs."

response = create_hybrid_feedback(sid, pin, feedbackbody, overallexperience2=overallexperience2,
learning_experience=learning_experience, like_visits=like_visits,
overallexperience=overallexperience, typeactivities=typeactivities,
satisfied=satisfied, comments=comments)

print(response)

Another Example (Without Optional Parameters)

# Example hybrid feedback creation without comments
sid = "200001"
pin = "1234"
feedbackbody = "The hybrid event was very interactive and provided a great mix of learning and practical activities."
overallexperience2 = "Good"
learning_experience = "I learned a lot about project management and team collaboration."
like_visits = "The industry visits were insightful."
overallexperience = "The overall experience was good and enriching."
typeactivities = "Team projects, Presentations, Case studies"
satisfied = "Satisfied"

response = create_hybrid_feedback(sid, pin, feedbackbody, overallexperience2=overallexperience2,
learning_experience=learning_experience, like_visits=like_visits,
overallexperience=overallexperience, typeactivities=typeactivities,
satisfied=satisfied)

print(response)

Key Functional Flow:

  1. User Validation: The function retrieves the user’s record and checks if the recordId is present. If it is missing, an error response is returned.
  2. Group Validation: The function retrieves the groupid (raw assigned group) for the user to associate the feedback with the correct group. If the group is not found, an error response is returned.
  3. Feedback Construction: The function constructs a feedback dictionary containing the provided feedback details (e.g., overall experience, learning experience, type of activities).
  4. Feedback Submission: The feedback dictionary is submitted to the backend system using _create_entry, which stores the feedback in the appropriate module.

Return Value

  • The function returns a JSON response that contains the result of the feedback submission. If the feedback is successfully created, it will return a success message; otherwise, it will return an error response indicating which piece of information was missing or invalid.

def getCompanyrawidFromInternPlace():

Parameters

  • data (dict): A dictionary that contains the data structure representing internship placement details. This data is expected to include nested keys where the company ID can be found under 'assigned_partner' -> 'raw'.

Initialization Steps

  • first_key (str): The function retrieves the first key from the dictionary located under the 'data' key. It uses next(iter(data['data'])) to access the first item in the dictionary.
  • raw_company_id (str or None): The function attempts to retrieve the raw company ID from the nested structure of the assigned_partner key. If there is an issue (e.g., the expected key or data is missing), it handles the TypeError and sets raw_company_id to None.

Purpose

The primary purpose of this function is to extract and return the raw company ID from an internship placement record. The company ID is essential for further processing or for linking the internship placement to the appropriate company in a database or system. The function ensures that if the data structure is not as expected, it doesn't raise an error but returns None instead.

Example Code Usage

# Example data structure representing internship placement details
data = {
'data': {
'internship1': {
'assigned_partner': {
'raw': 12345
}
}
}
}

# Call the function to get the company raw ID
company_raw_id = getCompanyrawidFromInternPlace(data)
print(company_raw_id) # Output: 12345

Example with Missing Data

# Example data structure where the raw company ID is missing or malformed
data = {
'data': {
'internship1': {
'assigned_partner': {}
}
}
}

# Call the function to get the company raw ID
company_raw_id = getCompanyrawidFromInternPlace(data)
print(company_raw_id) # Output: None

Key Functional Flow:

  1. Accessing the Data: The function accesses the first key in the 'data' dictionary, which represents an individual internship placement.
  2. Extracting the Company ID: It attempts to extract the raw company ID from the assigned_partner field.
  3. Error Handling: If the data structure is not as expected (e.g., if the assigned_partner key is missing or malformed), it catches the TypeError and returns None.

Return Value

  • Success: The function returns the raw company ID (a numeric or string value).
  • Failure: If the data structure is invalid or the company ID cannot be found, it returns None.

def get_group_from_group_record_id():

Parameters

  • grid (str): The group record ID. This ID is used to identify a specific group in the system and is passed to the function in order to retrieve its details.

Initialization Steps

  • Logging: The function logs the action of retrieving the group associated with the given group record ID using logging.info.
  • Token Check: It calls self._CheckTokenExsist() to ensure that a valid authentication token exists before making the request.
  • Path Construction: The function constructs the API request path using the group record ID (grid). The path is dynamically created using the format string f"{DefaultModules.Groups}/Record/{grid}", where DefaultModules.Groups is likely a predefined constant representing the groups module in the system.
  • API Request: The function sends a GET request to the specified path using self._requesttoyeti("GET", path). This method likely interacts with the backend API to fetch the group data.

Purpose

The function's purpose is to fetch and return the group details (likely including the group name) corresponding to a specific group record ID (grid). This is useful when trying to identify or display the group associated with a given record ID in the system.

Example Code Usage

# Example usage of get_group_from_group_record_id
grid = "12345" # Group record ID

group_info = get_group_from_group_record_id(grid)

# Print the JSON response returned by the function
print(group_info)

Key Functional Flow:

  1. Logging: Logs the process of retrieving group information based on the provided group record ID.
  2. Token Validation: Ensures that a valid authentication token exists by calling self._CheckTokenExsist().
  3. API Request: Constructs the request path using the grid and sends a GET request to the server to retrieve the group information.
  4. Response: The response from the API is expected to be in JSON format, and the function returns this JSON data.

Return Value

The function returns the response from the API as a JSON object. This JSON response likely contains information about the group, such as the group name and possibly other details associated with the group. If the request fails, an error response or an empty result may be returned depending on the implementation of _requesttoyeti.

Example Response:

{
"group_name": "Engineering Group",
"group_id": "12345",
"description": "This is a group for engineering students."
}

This output shows the expected group information based on the provided grid (group record ID).


def checkIfUserHasAlreadyMadeFeedback():

Parameters

  • response (dict): This is the response from an API or data source, expected to contain feedback records in the 'data' field. The format of the response is typically a dictionary with a 'data' key, which contains a collection of records (e.g., feedback entries) indexed by record IDs.

Initialization Steps

  • Initial Print Statement: The function first prints the response parameter for debugging or logging purposes, which helps to see the structure of the data.
  • Check for Empty Data: The function checks if the 'data' field in the response is empty or not. If no data is found (i.e., 'data' is None or empty), it returns False.
  • Check for "No related fields" Message: If the 'data' key contains a specific message like "No related fields found", the function also returns False, indicating that no feedback records were found.
  • Initialize last_record_id: A variable last_record_id is initialized to None to hold the last record ID found during the iteration over the records.

Purpose

The purpose of the function is to check if a user has already made feedback by processing the response data. It does this by looking for existing records in the 'data' field. If records are found, it returns the last record ID (indicating that feedback exists); otherwise, it returns False to indicate no feedback has been made.

Example Code Usage

# Example response where feedback records exist
response = {
'code': '200',
'data': {
'108946': {},
'108947': {},
'108950': {},
'108951': {}
}
}

# Check if the user has already made feedback
last_record_id = checkIfUserHasAlreadyMadeFeedback(response)
print(last_record_id) # Output: 108951 (the last feedback record ID)

# Example response where no feedback records exist
response_empty = {
'code': '200',
'data': {}
}

# Check if the user has already made feedback
last_record_id_empty = checkIfUserHasAlreadyMadeFeedback(response_empty)
print(last_record_id_empty) # Output: False (no feedback records found)

Key Functional Flow:

  1. Check for Data Existence: The function first checks if the 'data' field in the response exists and contains feedback records. If not, it returns False.
  2. Check for Specific Message: If the response contains the message "No related fields found", it returns False, indicating no feedback was made.
  3. Iterate through Feedback Records: If records exist in the 'data' field, the function iterates through the records, updating the last_record_id with the most recent feedback record ID.
  4. Return Last Record ID: Once the iteration completes, the function returns the last_record_id, which is the ID of the most recent feedback record found in the response.

Return Value

  • Success: The function returns the last feedback record ID (a string or number representing the last entry).
  • Failure: If no records are found or if the response contains a "No related fields found" message, the function returns False.

Example Response:

{
"code": "200",
"data": {
"108946": {},
"108947": {},
"108950": {},
"108951": {}
}
}

def check_families_feedbacks():

Parameters

  • sid (str): The student's identification number, used to identify the user whose feedback status needs to be checked.
  • pin (str): The student's personal identification number, which is used in combination with sid to fetch specific records for the user.

Initialization Steps

  • Logging: The function begins by logging the action of checking whether the user has made feedback. This is done for tracking purposes and debugging.
  • Token Validation: It calls self._CheckTokenExsist() to ensure that the necessary authentication token is available for making a valid request.
  • Fetching Related Fields: The function then calls self.get_related_fields() to fetch the relevant data associated with the user’s host family feedback, using sid, pin, and the DefaultModules.ShortTerm and DefaultModules.HostfamiliesFeedBack modules. The request also includes an optional "x-fields": '[""]' parameter, which likely filters or specifies certain fields in the response.
  • Feedback Check: The function delegates the actual feedback check to the YetiForceClient.checkIfUserHasAlreadyMadeFeedback() function by passing the fetched response data.

Purpose

The primary purpose of this function is to determine whether a user has already submitted feedback for their host family in a short-term program. It does so by making a request to fetch related fields and then checking the response for existing feedback records. If feedback is found, it returns the last feedback record ID; otherwise, it returns False.

Example Code Usage

# Example SID and PIN of a user
sid = "123456"
pin = "7890"

# Call the function to check if the user has already made feedback
last_record_id = check_families_feedbacks(sid, pin)

# Print the result
if last_record_id:
print(f"User has already made feedback with record ID: {last_record_id}")
else:
print("User has not made any feedback yet.")

Key Functional Flow:

  1. Logging: The function logs that it is checking for existing feedback for the given user.
  2. Token Validation: Ensures that a valid authentication token exists before proceeding with the API request.
  3. Fetch Related Data: It retrieves relevant data related to the user’s host family feedback using the provided sid and pin.
  4. Check Feedback: The function then delegates the task of checking whether feedback exists to checkIfUserHasAlreadyMadeFeedback(), passing the response obtained in the previous step.

Return Value

  • Success: If feedback records are found, the function returns the last record ID associated with the user's feedback.
  • Failure: If no feedback records exist, it returns False.

Example Response:

{
"code": "200",
"data": {
"108946": {},
"108947": {},
"108950": {},
"108951": {}
}
}

check_job_placement_feedback():

Parameters

  • sid (str): The student identification number, used to uniquely identify the user whose feedback status is being checked.
  • pin (str): The personal identification number of the student, used in combination with sid to query the user’s specific data.

Initialization Steps

  • Logging: The function begins by logging the action of checking whether the user has made feedback. This helps with tracking and debugging.
  • Token Validation: It calls self._CheckTokenExsist() to ensure that the necessary authentication token is present and valid before making the request.
  • Fetching Related Fields: The function calls self.get_related_fields() to retrieve the relevant data for the user’s job placement feedback, using sid, pin, and the DefaultModules.ShortTerm and DefaultModules.PlacementFeedBack modules. The request includes an optional "x-fields": '[""]' parameter, which might be used to filter specific fields in the response data.
  • Feedback Check: The function then passes the fetched response to YetiForceClient.checkIfUserHasAlreadyMadeFeedback() to check if feedback has been submitted already.

Purpose

The primary purpose of this function is to determine whether a user has already submitted feedback for their job placement. It retrieves the relevant feedback data associated with the user and delegates the actual feedback check to another function, which checks if any feedback exists. If feedback is found, it returns the last record ID; otherwise, it returns False.

Example Code Usage

# Example SID and PIN of a user
sid = "654321"
pin = "4321"

# Call the function to check if the user has already made feedback for job placement
last_record_id = check_job_placement_feedback(sid, pin)

# Print the result
if last_record_id:
print(f"User has already made feedback with record ID: {last_record_id}")
else:
print("User has not made any job placement feedback yet.")

Key Functional Flow:

  1. Logging: Logs that it is checking if the user has made feedback for their job placement.
  2. Token Validation: Ensures that the request is authenticated by validating the token before proceeding with fetching the data.
  3. Fetch Related Data: Retrieves the relevant data for the user’s job placement feedback using sid and pin through the get_related_fields() function, with the DefaultModules.ShortTerm and DefaultModules.PlacementFeedBack modules.
  4. Check Feedback: The function then delegates the task of checking for existing feedback to checkIfUserHasAlreadyMadeFeedback(), passing the response data it received.

Return Value

  • Success: If feedback records are found, the function returns the last record ID associated with the feedback.
  • Failure: If no feedback records exist or if the response indicates that no related fields are present, the function returns False.

Example Response:

{
"code": "200",
"data": {
"109001": {},
"109002": {},
"109003": {}
}
}

check_erasmus_feedback():

Parameters

  • sid (str): The student identification number. This is used to identify the specific user whose feedback status is being checked.
  • pin (str): The personal identification number of the user. It is used in combination with sid to retrieve the correct user data.

Initialization Steps

  1. Logging: The function starts by logging an informational message indicating that it is checking if the user has already made feedback. This log helps with tracking and debugging.
  2. Token Validation: It calls self._CheckTokenExsist() to ensure the necessary authentication token is available before proceeding with any requests.
  3. Fetching Related Fields: The function calls self.get_related_fields() to fetch data related to the Erasmus feedback using the sid, pin, and the DefaultModules.ShortTerm and DefaultModules.ErasmusFeedBack modules. It also includes a parameter "x-fields": '[""]', which likely filters or specifies certain fields to retrieve in the response.
  4. Feedback Check: After retrieving the data, the function passes the response to YetiForceClient.checkIfUserHasAlreadyMadeFeedback() to check whether feedback has been previously submitted for the Erasmus program.

Purpose

The main purpose of this function is to verify whether a user has already submitted feedback for their Erasmus program. It does this by fetching the relevant user data and passing it to a helper function that checks for existing feedback records. If feedback is found, it returns the last record ID; otherwise, it returns False.

Example Code Usage

# Example SID and PIN for the user
sid = "987654"
pin = "1234"

# Call the function to check if the user has already provided Erasmus feedback
last_record_id = check_erasmus_feedback(sid, pin)

# Print the result
if last_record_id:
print("User has already made Erasmus feedback with record ID: {last_record_id}")
else:
print("User has not made any Erasmus feedback yet.")

Key Functional Flow:

  1. Logging: Logs the action of checking for Erasmus feedback for the given user.
  2. Token Validation: Ensures that the necessary authentication token is available to make the request.
  3. Fetch Related Data: Retrieves the relevant data for Erasmus feedback using the sid and pin of the user, fetching information from the ShortTerm and ErasmusFeedBack modules.
  4. Check Feedback: The function delegates the task of checking whether feedback exists to checkIfUserHasAlreadyMadeFeedback(), passing the fetched response data.

Return Value

  • Success: If the user has already made feedback, the function returns the last feedback record ID.
  • Failure: If no feedback records are found, it returns False.

Example Response:

{
"code": "200",
"data": {
"120001": {},
"120002": {},
"120003": {}
}
}

check_hybrid_feedback():

Parameters

  • sid (str): The student identification number, used to uniquely identify the user whose feedback status is being checked.
  • pin (str): The personal identification number associated with the user, used alongside sid to query the user's feedback data.

Initialization Steps

  1. Logging: The function starts by logging an informational message indicating that it is checking whether the user has already provided feedback. This log helps track the execution and debug any potential issues.
  2. Token Validation: The function calls self._CheckTokenExsist(), which ensures that an authentication token is available before making any requests to the API or server. This step is crucial to prevent unauthorized access.
  3. Fetching Related Fields: The function uses self.get_related_fields() to fetch data related to the hybrid feedback using the provided sid and pin. It specifies the DefaultModules.ShortTerm and DefaultModules.HybridFeedBack modules, which are likely related to short-term programs and hybrid feedback data. The request also includes an optional parameter "x-fields": '[""]', which may be used to filter or specify which fields to retrieve from the server.

Purpose

The purpose of this function is to determine whether a user has already submitted feedback for a hybrid program. It does this by querying the relevant feedback data associated with the user and then passing the response data to an external function (likely checkIfUserHasAlreadyMadeFeedback) to check if feedback already exists. If feedback is found, it returns the last record ID; otherwise, it returns False.

Example Code Usage

# Example SID and PIN for the user
sid = "123456"
pin = "7890"

# Call the function to check if the user has already provided hybrid feedback
last_record_id = check_hybrid_feedback(sid, pin)

# Print the result
if last_record_id:
print(f"User has already made hybrid feedback with record ID: {last_record_id}")
else:
print("User has not made any hybrid feedback yet.")

Key Functional Flow:

  1. Logging: Logs the action of checking if the user has already submitted feedback for a hybrid program.
  2. Token Validation: Ensures that the necessary authentication token exists and is valid before making the API request.
  3. Fetch Related Data: Retrieves feedback data related to the user’s hybrid program participation by querying the ShortTerm and HybridFeedBack modules, using sid and pin to filter the data.
  4. Feedback Check: After retrieving the data, the function likely passes it to another method (not shown in the code snippet) to check if any feedback exists for the user.

Return Value

  • Success: If the user has already provided feedback, the function returns the last record ID associated with that feedback.
  • Failure: If no feedback records are found, the function returns False.

Example Response:

{
"code": "200",
"data": {
"130001": {},
"130002": {},
"130003": {}
}
}

In this case, if feedback records exist, the function will return the last record ID (130003). If no feedback is found or if the response indicates "No related fields found", the function will return False.