### Install PostgreSQL on Ubuntu
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Installs PostgreSQL and its contrib package on Ubuntu. Starts and enables the PostgreSQL service. Verifies the installation.
```bash
sudo apt update && sudo apt upgrade -y
```
```bash
sudo apt install postgresql postgresql-contrib -y
```
```bash
sudo systemctl start postgresql
```
```bash
sudo systemctl enable postgresql
```
```bash
psql --version
```
--------------------------------
### Run Docker Compose
Source: https://github.com/horilla/horilla-hr/blob/1.0/docker.md
Use this command to build and start the project services defined in the docker-compose.yml file. Ensure Docker and Docker Compose are installed.
```bash
docker compose up
```
--------------------------------
### Install Django using pip
Source: https://github.com/horilla/horilla-hr/wiki/Installation
Install the Django web framework using pip. This is a prerequisite for installing Horilla.
```bash
pip install Django
```
--------------------------------
### Rename Environment File
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Rename the example environment file to .env to start configuring your project settings.
```bash
mv .env.dist .env
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Install all necessary Python packages listed in the requirements.txt file.
```bash
pip install -r requirements.txt
```
--------------------------------
### Set Up Python Virtual Environment on Ubuntu
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Installs the python3-venv package, creates a virtual environment named 'horillavenv', activates it, and installs project dependencies from requirements.txt.
```bash
sudo apt-get install python3-venv
```
```bash
python3 -m venv horillavenv
```
```bash
source horillavenv/bin/activate
```
```bash
pip install -r requirements.txt
```
--------------------------------
### Install Django
Source: https://github.com/horilla/horilla-hr/wiki/Installation
Install the latest version of Django using Pip. This command installs the framework required for the Horilla application.
```bash
sudo pip3 install django
```
--------------------------------
### Run Windows Installer
Source: https://github.com/horilla/horilla-hr/wiki/Installation-using-Shell
Execute the Horilla installation script on Windows. Ensure you have downloaded the install.bat file and are in the correct directory.
```bash
horilla_install_windows.bat
```
--------------------------------
### Install Python 3 on Ubuntu
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Installs Python 3 on Ubuntu systems. Verify the installation using the version command.
```bash
sudo apt-get install python3
```
```bash
python3 --version
```
--------------------------------
### Run Development Server (Ubuntu/macOS)
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Start the Django development server on Ubuntu or macOS.
```bash
python3 manage.py runserver
```
--------------------------------
### Run Ubuntu/macOS Installer
Source: https://github.com/horilla/horilla-hr/wiki/Installation-using-Shell
Execute the Horilla installation script on Ubuntu or macOS after setting execute permissions. Use the correct script for your operating system.
```bash
./horilla_install_ubuntu.sh #for Ubuntu
OR
./horilla_install_macOS.sh #for macOS
```
--------------------------------
### Install Python on macOS
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Installs Python on macOS using Homebrew. Verifies the installation with the version command.
```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
```bash
brew install python
```
```bash
python3 --version
```
--------------------------------
### Set Up Python Virtual Environment on Windows
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Creates a virtual environment named 'horillavenv', activates it using Windows-specific paths, and installs project dependencies from requirements.txt.
```powershell
python -m venv horillavenv
```
```powershell
.\horillavenv\Scripts\activate
```
```powershell
pip install -r requirements.txt
```
--------------------------------
### Install Python 3 and Pip
Source: https://github.com/horilla/horilla-hr/wiki/Installation
Install Python 3 and its package installer, Pip, which are required for Django development.
```bash
sudo apt install python3 python3-pip
```
--------------------------------
### Install cx_Oracle Package
Source: https://github.com/horilla/horilla-hr/wiki/Database-Setup
Install the cx_Oracle package using pip to enable Django's interaction with Oracle databases.
```bash
pip install cx_Oracle
```
--------------------------------
### Install mysqlclient for MySQL
Source: https://github.com/horilla/horilla-hr/wiki/Database-Setup
Install the mysqlclient package using pip. This package allows Django to interact with MySQL databases.
```bash
pip install mysqlclient
```
--------------------------------
### Run Horilla Application
Source: https://github.com/horilla/horilla-hr/wiki/Installation
Start the Horilla application server. Access the application via your web browser at http://localhost:8000/.
```bash
python manage.py runserver
```
--------------------------------
### Verify Django Installation
Source: https://github.com/horilla/horilla-hr/wiki/Installation
Check if Django has been installed correctly by running this command in your command prompt. It should display the installed version number.
```bash
django-admin --version
```
--------------------------------
### Developer Guide: Adding Documentation
Source: https://github.com/horilla/horilla-hr/blob/1.0/horilla_api/README_API_DOCS.md
Instructions for developers on how to add documentation to new API endpoints using the `document_api` decorator.
```APIDOC
## For Developers: Adding Documentation to New Endpoints
### Using the `document_api` Decorator
```python
from horilla_api.docs import document_api
class MyAPIView(APIView):
@document_api(
operation_description="Description of what this endpoint does",
request_body=MyRequestSerializer,
responses={
200: MyResponseSerializer,
400: "Bad request error description"
},
tags=['Module Name']
)
def get(self, request):
# Your view logic here
pass
```
### Common Parameters
For paginated list views:
```python
@document_api(
operation_description="List all items with pagination",
responses={200: MySerializer(many=True)},
query_params='paginated'
)
```
```
--------------------------------
### Start Django Development Server
Source: https://github.com/horilla/horilla-hr/wiki/Installation-using-Shell
Run the Django development server for the Horilla application. This command should be executed from the Horilla project directory.
```python
python manage.py runserver
```
--------------------------------
### Navigate to Horilla Directory
Source: https://github.com/horilla/horilla-hr/wiki/Installation
Change your current directory to the cloned Horilla project directory. This is necessary before installing dependencies.
```bash
cd horilla
```
--------------------------------
### Ensure pip is Installed
Source: https://github.com/horilla/horilla-hr/wiki/Installation
Run this command in your command prompt to ensure pip is installed and updated if you have Python installed.
```bash
python -m ensurepip --default-pip
```
--------------------------------
### Install psycopg2 for PostgreSQL
Source: https://github.com/horilla/horilla-hr/wiki/Database-Setup
Install the psycopg2 package using pip. This package is a PostgreSQL database adapter for Python.
```bash
pip install psycopg2
```
--------------------------------
### Update and Upgrade Ubuntu System
Source: https://github.com/horilla/horilla-hr/wiki/Installation
Before installing new software, update your Ubuntu system's package list and upgrade existing packages.
```bash
sudo apt update
sudo apt upgrade
```
--------------------------------
### Set Execute Permissions for Ubuntu/macOS Installer
Source: https://github.com/horilla/horilla-hr/wiki/Installation-using-Shell
Grant execute permissions to the Horilla installation script before running it on Ubuntu or macOS. Use the appropriate script name for your OS.
```bash
chmod +x horilla_install_ubuntu.sh #for Ubuntu
OR
chmod +x horilla_install_macOS.sh #for macOS
```
--------------------------------
### Initialize UI Elements with jQuery
Source: https://github.com/horilla/horilla-hr/blob/1.0/pms/templates/feedback/feedback_detailed_view.html
Sets the class attribute for a close button on document ready. Used for initial UI setup.
```javascript
$(document).ready(function () { $("#close").attr( "class", "oh-activity-sidebar\_\_header-icon me-2 oh-activity-sidebar\_\_close md hydrated" ); });
```
--------------------------------
### Initialize UI Element Visibility
Source: https://github.com/horilla/horilla-hr/blob/1.0/attendance/templates/attendance/attendance_account/overtime_list.html
Hides specific UI elements related to instance selection and export when the function is called. This is likely an initial setup or reset function.
```javascript
function hiding() { $("#selectAllInstances").hide(); $("#unselectAllInstances").hide(); $("#exportAccounts").hide(); $("#selectedShow").hide(); }
```
--------------------------------
### Submit Payroll Form with Validation
Source: https://github.com/horilla/horilla-hr/blob/1.0/payroll/templates/payroll/payslip/view_payslips.html
Handles form submission for creating or generating payslips. It serializes form data and sends an AJAX GET request to validate the start date before submitting the form. Errors are displayed in an unordered list.
```javascript
$(document).ready(function () {
$(
`[action="/payroll/create-payslip"], [action="/payroll/generate-payslip"]`
).submit(function (e) {
e.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
type: "get",
url: "{% url 'validate-start-date' %}",
data: formData,
success: function (response) {
let ul = $(".errorlist");
response.errors.forEach(msg => {
const li = document.createElement("li");
li.textContent = msg;
ul.appendChild(li);
});
if (response.valid) {
form[0].submit();
}
},
});
});
});
```
--------------------------------
### Check Interview Conflicts on Date Selection
Source: https://github.com/horilla/horilla-hr/blob/1.0/leave/templates/leave/user_leave/user_request_update.html
Attaches a click event listener to a custom save button. When clicked, it prevents default form submission, retrieves start and end dates, and makes an AJAX GET request to check for interview conflicts.
```javascript
$(document).ready(function () { $("#buttonID").on("click", function () { event.preventDefault(); event.stopPropagation(); var startDate = $("#userLeaveForm \[name = start_date\]").val(); var endDate = $("#userLeaveForm \[name = end_date\]").val(); var employee = "{{request.user.employee_get.id}}"; $.ajax({ type: "GET", url: "{% url 'check-interview-conflicts' %}", data: { start_date: startDate, end_date: endDate, employee_id: employee, }, success: function (response) { var interviews = response.interviews; title = "Leave Request Alert."; var content =
{{request.user.employee_get}} has interview in the requested date.
Are you sure you want to proceed with the request?
; if (interviews.length != 0) { Swal.fire({ title: title, icon: "info", html: content, showCancelButton: true, confirmButtonColor: "#008000", cancelButtonColor: "#d33", confirmButtonText: "Confirm", }).then(function (result) { if (result.isConfirmed) { $("#userLeaveForm \[type=submit\]").click(); } }); } else { $("#userLeaveForm \[type=submit\]").click(); } }, }); }); });
```
--------------------------------
### Dynamic Installment Calculation
Source: https://github.com/horilla/horilla-hr/blob/1.0/asset/templates/request_allocation/asset_request_allocation_view.html
JavaScript code that calculates loan installments based on loan amount and number of installments. It also updates the installment amount when the installment amount changes. This script is triggered after HTMX swaps content.
```javascript
$(document).ready(function () {
$("#gp_request").on("change", function () {
$(".filterButton")[0].click();
});
$("#gp_allocation").on("change", function () {
$(".filterButton")[0].click();
});
$("#dynamicCreateModalTarget").on("htmx:afterSwap", function () {
$("[name='installment_amount']").on("change keyup", function () {
var loanAmount = $("[name='loan_amount']").val();
var installmentAmount = $(this).val();
var installments = loanAmount / installmentAmount;
$("[name='installments']").val(installments);
if (Math.round(installments) !== installments) {
installments = Math.round(installments);
$("[name='installments']").val(installments);
$("[name='installments']").trigger("change");
}
});
$("[name='loan_amount']").on("change keyup", function () {
var loanAmount = $("[name='loan_amount']").val();
if (loanAmount) {
$("[name='installments']").val(1);
} else {
$("[name='installments']").val("");
}
$("[name='installments']").change();
});
$("[name='installments']").on("change keyup", function () {
var loanAmount = $("[name='loan_amount']").val();
var installments = $(this).val();
var installmentAmount = loanAmount / installments;
$("[name='installment_amount']").val(installmentAmount);
});
});
});
```
--------------------------------
### Calculate Installment Amount
Source: https://github.com/horilla/horilla-hr/blob/1.0/payroll/templates/payroll/loan/nav.html
This JavaScript code calculates the installment amount for a loan when the number of installments changes. It requires the loan amount and the number of installments to be present in the form.
```javascript
$(document).ready(function () {
$("#objectCreateModalTarget").on("htmx:afterSwap", function () {
$("[name='installment_amount']").on("change", function () {
var loanAmount = $("[name='loan_amount']").val();
var installmentAmount = $(this).val();
var installments = loanAmount / installmentAmount;
$("[name='installments']").val(installments);
if (Math.round(installments) !== installments) {
installments = Math.round(installments);
$("[name='installments']").val(installments);
$("[name='installments']").trigger("change");
}
});
$("[name='installments']").on("change keyup", function () {
var loanAmount = $("[name='loan_amount']").val();
var installments = $(this).val();
var installmentAmount = loanAmount / installments;
$("[name='installment_amount']").val(installmentAmount);
});
});
});
```
--------------------------------
### Configure PostgreSQL on macOS
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Creates a database and user for Horilla on macOS using Homebrew. Sets the password for the new user.
```bash
createdb horilla_main
```
```bash
createuser horilla
```
```bash
psql -c "ALTER USER horilla WITH PASSWORD 'horilla';"
```
--------------------------------
### Initialize UI and Event Handlers
Source: https://github.com/horilla/horilla-hr/blob/1.0/recruitment/templates/candidate/candidate_list.html
Sets up the initial state of UI elements on document ready, including hiding/showing selection-related buttons and handling the 'select all' functionality. It also prepares messages based on the current language.
```javascript
$(document).ready(function () {
var excelMessages = {
ar: "هل ترغب في تنزيل ملف Excel؟",
de: "Möchten Sie die Excel-Datei herunterladen?",
es: "¿Desea descargar el archivo de Excel?",
en: "Do you want to download the excel file?",
fr: "Voulez-vous télécharger le fichier Excel?",
};
var ids = JSON.parse($("#selectedInstances").attr("data-ids") || "\[]");
var uniqueIds = makeListUnique1(ids);
var selectedCount = uniqueIds.length;
var message1 = rowMessages[languageCode];
$("#selectAllInstances").click(function () {
$("#selectedInstances").attr("data-clicked", 1);
var savedFilters = JSON.parse(localStorage.getItem("savedFilters"));
if (savedFilters && savedFilters["filterData"] !== null) {
var filter = savedFilters["filterData"]
$.ajax({
url: '{% url "candidate-select-filter" %}',
data: { page: "all", filter: JSON.stringify(filter) },
type: "GET",
dataType: "json",
success: function (response) {
var employeeIds = response.employee_ids;
var selectedCount = employee
```
--------------------------------
### Django Template Logic for Onboarding Overview
Source: https://github.com/horilla/horilla-hr/blob/1.0/onboarding/templates/onboarding/dashboard.html
Renders an overview of onboarding candidates, including counts and a chart. This template logic requires 'recruitment', 'candidates', 'hired', 'onboard_candidates', and 'job_positions' context variables.
```django
{% extends 'index.html' %} {% block content %} {% load static i18n %} {% load i18n %} .done-task{ background-color: #9acd322e !important; } .scheduled-task{ background-color: #00afff2e !important; } .ongoing-task{ background-color: #e6ff002e !important; } .stuck-task{ background-color: #ff45003b !important; } .todo-task{ background-color: #8d8d8d2e !important; }
{% trans "Back" %}
[
{% trans "Onboarding" %}
{{recruitment|length}}
]({%)
{% trans "Total Candidates" %}
{{candidates|length}}
{% trans "Candidates Start Onboarding" %}
{{hired|length}}
{% trans "Onboarding Stage Chart" %}
{% trans "Candidates on Onboard" %}
{% if onboard_candidates and job_positions %}
{% for job in job_positions %}* {{job|truncatechars:20}}
{% for cand in onboard_candidates %} {% if cand.job_position_id.job_position == job %}

{{cand}}
{% endif %} {% endfor %}
{% endfor %}
{% else %}

### {% trans "No candidates started onboarding." %}
{% endif %}
var recruitment = {{recruitment|safe}} $("#candidate_view").on("click",function(){ $("#back_button").removeClass("d-none") })
$("#hired_candidate").on("click",function(){ $("#back_button").removeClass("d-none") })
{% endblock content %}
```
--------------------------------
### Create and Activate Virtual Environment (macOS)
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Use this command to create a virtual environment for the project and then activate it. This isolates project dependencies.
```bash
python3 -m venv horillavenv
source horillavenv/bin/activate
```
--------------------------------
### Initialize Candidate Selection and Export
Source: https://github.com/horilla/horilla-hr/blob/1.0/onboarding/templates/onboarding/group_by.html
Sets up event handlers for selecting all, unselecting all, and exporting candidates. It also initializes UI elements and retrieves initial selected candidate IDs.
```javascript
$(document).ready(function () {
var excelMessages = {
ar: "هل ترغب في تنزيل ملف Excel؟",
de: "Möchten Sie die Excel-Datei herunterladen?",
es: "¿Desea descargar el archivo de Excel?",
en: "Do you want to download the excel file?",
fr: "Voulez-vous télécharger le fichier Excel?",
};
var ids = JSON.parse($("#selectedInstances").attr("data-ids") || "[]");
var uniqueIds = makeListUnique1(ids);
var selectedCount = uniqueIds.length;
var message1 = rowMessages[languageCode]
$("#selectAllInstances").click(function () {
$("#selectedInstances").attr("data-clicked", 1);
var savedFilters = JSON.parse(localStorage.getItem("savedFilters"));
if (savedFilters && savedFilters["filterData"] !== null) {
var filter = savedFilters["filterData"];
$.ajax({
url: '{% url "candidate-select-filter-onboarding" %}',
data: { page: "all", filter: JSON.stringify(filter) },
type: "GET",
dataType: "json",
success: function (response) {
var employeeIds = response.employee_ids;
var selectedCount = employeeIds.length;
var selectedCount = employeeIds.length;
var selectedCount = employeeIds.length;
for (var i = 0; i < employeeIds.length; i++) {
var empId = employeeIds[i]
$("#" + empId).prop("checked", true).change();
}
var previousIds = $("#selectedInstances").attr("data-ids")
$("#selectedInstances").attr("data-ids", JSON.stringify(Array.from(new Set([...employeeIds, ...JSON.parse(previousIds)]))));
tickCandidateCheckboxes();
},
error: function (xhr, status, error) {
console.error("Error:", error);
},
});
} else {
$.ajax({
url: '{% url "candidate-select-onboarding" %}',
data: { page: "all" },
type: "GET",
dataType: "json",
success: function (response) {
var employeeIds = response.employee_ids;
var selectedCount = employeeIds.length;
for (var i = 0; i < employeeIds.length; i++) {
var empId = employeeIds[i]
$("#" + empId).prop("checked", true);
}
$("#selectedInstances").attr(
"data-ids",
JSON.stringify(employeeIds)
);
tickCandidateCheckboxes();
},
error: function (xhr, status, error) {
console.error("Error:", error);
},
});
}
});
$("#unselectAllInstances").click(function () {
$("#selectedInstances").attr("data-ids", "[]");
tickCandidateCheckboxes()
$(".all-candidate-row").prop("checked", false).change()
});
$("#exportCandidates").click(function (e) {
var currentDate = new Date().toISOString().slice(0, 10);
var languageCode = null;
ids = []
ids.push($("#selectedInstances").attr("data-ids"));
ids = JSON.parse($("#selectedInstances").attr("data-ids"));
getCurrentLanguageCode(function (code) {
languageCode = code;
var confirmMessage = excelMessages[languageCode];
Swal.fire({
text: confirmMessage,
icon: "question",
showCancelButton: true,
confirmButtonColor: "#008000",
cancelButtonColor: "#d33",
confirmButtonText: "Confirm",
}).then(function (result) {
if (result.isConfirmed) {
$.ajax({
type: "GET",
url: "/recruitment/candidate-info-export",
data: {
ids: JSON.stringify(ids),
},
dataType: "binary",
xhrFields: {
responseType: "blob",
},
success: function (response) {
const file = new Blob([response], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
link.download = "Candidate_file_" + currentDate + ".xlsx";
document.body.appendChild(link);
link.click();
},
error: function (xhr, textStatus, errorThrown) {
console.error("Error downloading file:", errorThrown);
},
});
}
});
});
});
});
// toggle columns
// toggleColumns("candidate-toggle-table", "CandidateCells")
localStorageCandidateCells = localStorage.getItem("candidate_toggle_tab")
if (!localStorageCandidateCells) {
$("#CandidateCells").find("[type=checkbox]").prop("checked", true)
}
updateCount()
tickCandidateCheckboxes()
function isValidDateFormat(dateStr) {
if (!dateStr) return true; // Allow empty (clearing)
if (!/^\\d{4}-\\d{2}-\\d{2}/.test(dateStr)) return false;
}
```
--------------------------------
### Initialize UI Elements and Event Handlers
Source: https://github.com/horilla/horilla-hr/blob/1.0/pms/templates/okr/objective_creation.html
Sets up the initial state of UI elements and attaches event listeners when the document is ready. Hides the start date and assignee fields by default, and calls `addAssignees` to set initial visibility.
```javascript
$(document).ready(function(){ {% comment %} $('#id_assignees').next('span').hide() {% endcomment %} $('[id="id_start_date"]').parent().hide(); {% comment %} $('label[for="id_assignees"]').hide(); {% endcomment %} $('#id_assignees').closest('div.col-12').hide(); addAssignees() })
```
--------------------------------
### Initiate Build Process
Source: https://github.com/horilla/horilla-hr/blob/1.0/static/build/vendor/ionicons/@stencil/core/dev-server/connector.html
Initiates a build process, likely triggering a server-side build and returning a promise that resolves with the build results.
```javascript
$=function(e){return oe(se,"Build",e)}
```
--------------------------------
### Apply Django Migrations (Ubuntu/macOS)
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Run these commands on Ubuntu or macOS to create and apply database schema changes.
```bash
python3 manage.py makemigrations
python3 manage.py migrate
```
--------------------------------
### Set or Get Value (Deprecated)
Source: https://github.com/horilla/horilla-hr/blob/1.0/project/templates/time_sheet/form_project_time_sheet.html
Sets or gets the value of the Select2 instance. This method is deprecated and users should use the $element.val() method. Logs a warning if debug mode is enabled.
```javascript
if (null == e || 0 === e.length) return this.$element.val();
e = e[0]
Array.isArray(e) && (e = e.map(function(e) {
return e.toString()
})),
this.$element.val(e).trigger("input").trigger("change")
```
--------------------------------
### Configure PostgreSQL on Ubuntu
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Sets up a new role and database for Horilla within PostgreSQL on Ubuntu. Ensure to exit the postgres user session after configuration.
```bash
sudo su postgres
```
```bash
psql
```
```sql
CREATE ROLE horilla LOGIN PASSWORD 'horilla';
```
```sql
CREATE DATABASE horilla_main OWNER horilla;
```
```sql
\q
```
```bash
exit
```
--------------------------------
### Bulk Send Payslips
Source: https://github.com/horilla/horilla-hr/blob/1.0/payroll/templates/payroll/payslip/view_payslips.html
Initiates a bulk send for selected payslips using an AJAX GET request. It retrieves selected IDs, gets the current language code, and displays a processing message or a warning if no payslips are selected. It also resets checkboxes.
```javascript
$("#payslipBulkSend").click(function (e) {
e.preventDefault();
var languageCode = null;
getCurrentLanguageCode(function (code) {
languageCode = code;
var idsJson = $("#selectedPayslip").attr("data-ids");
var ids = JSON.parse(idsJson);
if (ids.length > 0) {
$.ajax({
type: "get",
url: `/payroll/send-slip`,
data: { id: ids },
traditional: true,
success: function (response) {
var mailProcessingMessage = mail_processing[languageCode];
$("#messages").html(
$(
`
` +
mailProcessingMessage +
`
`
)
);
$("#unselectAllPayslip").click();
$(".payslip-checkbox:checked").prop("checked", false).change();
},
});
} else {
var textMessage = no_rows_payslip_send[languageCode];
Swal.fire({
text: textMessage,
icon: "warning",
confirmButtonText: "Close",
});
$("#unselectAllPayslip").click();
$(".payslip-checkbox:checked").prop("checked", false).change();
}
});
});
```
--------------------------------
### Get Cookie Function
Source: https://github.com/horilla/horilla-hr/blob/1.0/project/templates/task_all/forms/create_project_stage_taskall.html
Retrieves the value of a specified cookie from the document's cookies.
```javascript
function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }
```
--------------------------------
### Initialize Candidate Selection JavaScript
Source: https://github.com/horilla/horilla-hr/blob/1.0/recruitment/templates/candidate/group_by.html
Sets up the initial state for candidate selection on document ready. It hides certain elements and prepares for potential selection actions based on stored IDs and language codes.
```javascript
$(document).ready(function () {
var excelMessages = {
ar: "هل ترغب في تنزيل ملف Excel؟",
de: "Möchten Sie die Excel-Datei herunterladen?",
es: "¿Desea descargar el archivo de Excel?",
en: "Do you want to download the excel file?",
fr: "Voulez-vous télécharger le fichier Excel?",
};
var ids = JSON.parse($("#selectedInstances").attr("data-ids") || "\[\]");
var uniqueIds = makeListUnique1(ids);
var selectedCount = uniqueIds.length;
var message1 = rowMessages[languageCode]
$("#selectAllInstances").click(function () {
$("#selectedInstances").attr("data-clicked", 1);
var savedFilters = JSON.parse(localStorage.getItem("savedFilters"));
if (savedFilters && savedFilters["filterData"] !== null) {
var filter = savedFilters["filterData"]
$.ajax({
url: '{% url "candidate-select-filter" %}',
data: { page: "all", filter: JSON.stringify(filter) },
type: "GET",
dataType: "json",
success: function (response) {
var employeeIds = response.employee_ids;
var selectedCount
```
--------------------------------
### Get Highlighted Select2 Results
Source: https://github.com/horilla/horilla-hr/blob/1.0/project/templates/time_sheet/form_task_time_sheet.html
Retrieves all currently highlighted result options within the Select2 dropdown.
```javascript
s.prototype.getHighlightedResults=function(){return this.$results.find(".select2-results__option--highlighted")}
```
--------------------------------
### Conditional Contract Details Inclusion
Source: https://github.com/horilla/horilla-hr/blob/1.0/employee/templates/tabs/personal_tab.html
Includes the 'contract-tab.html' template only if the 'payroll' app is installed and the user has necessary permissions or is the employee.
```html
{% if "payroll"|app_installed %} {% if perms.employee.view_employee or perms.payroll.view_contract or request.user == employee.employee_user_id %}*  {% trans "Contract details" %}
{% endif %} {% endif %}
{% if perms.employee.view_employee or perms.payroll.view_contract or request.user == employee.employee_user_id %} {% if "payroll"|app_installed %}
{% include "tabs/contract-tab.html" %}
{% endif %} {% endif %}
```
--------------------------------
### Initialize Backup Settings UI with jQuery
Source: https://github.com/horilla/horilla-hr/blob/1.0/horilla_backup/templates/backup/local_setup_form.html
Initializes the visibility of backup settings fields based on the current state of checkboxes. This script should be placed within a $(document).ready() block.
```javascript
$(document).ready(function() { $('#id_backup_path').parent().removeClass('col-md-6') $('.oh-payslip__header').append(
`
{% if show %} {% if active %} Stop {% else %} Start {% endif %} {% endif %}
`
)
if (!$('#id_interval').is(':checked')) { $('#id_seconds').parent().hide(); }
if (!$('#id_fixed').is(':checked')) { $('#id_hour').parent().hide(); $('#id_minute').parent().hide(); }
});
```
--------------------------------
### Initialize Candidate Table Columns
Source: https://github.com/horilla/horilla-hr/blob/1.0/onboarding/templates/onboarding/candidates.html
Initializes the visibility of candidate table columns based on local storage. If no preference is found, all columns are checked by default.
```javascript
localStorageCandidateCells = localStorage.getItem("candidate_toggle_tab")
if (!localStorageCandidateCells) {
$("#CandidateCells").find("[type=checkbox]").prop("checked", true)
}
updateCount()
tickCandidateCheckboxes()
```
--------------------------------
### Clone Horilla Repository
Source: https://github.com/horilla/horilla-hr/wiki/Installation
Clone the Horilla open-source web application repository from GitHub using Git. Ensure you have Git installed.
```bash
git clone https://github.com/horilla-opensource/horilla.git
```
--------------------------------
### Configure MySQL Database Settings
Source: https://github.com/horilla/horilla-hr/wiki/Database-Setup
In the project settings file (horilla/settings.py), add the following database settings for MySQL. Replace placeholders with your actual database credentials.
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
```
--------------------------------
### Configure PostgreSQL Database Settings
Source: https://github.com/horilla/horilla-hr/wiki/Database-Setup
In the project settings file (horilla/settings.py), add the following database settings for PostgreSQL. Replace placeholders with your actual database credentials.
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
```
--------------------------------
### Get CSRF Cookie
Source: https://github.com/horilla/horilla-hr/blob/1.0/onboarding/templates/onboarding/candidate_task.html
Retrieves the CSRF token from document cookies. This is essential for making authenticated POST requests in Django applications.
```javascript
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== "") {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === name + "=") {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
```
--------------------------------
### Clone Horilla Repository on Ubuntu
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Initializes a Git repository, adds the Horilla remote, and pulls the master branch on Ubuntu.
```bash
sudo git init
```
```bash
sudo git remote add horilla https://horilla-opensource@github.com/horilla-opensource/horilla.git
```
```bash
sudo git pull horilla master
```
--------------------------------
### Select2 Initialization and Event Handling
Source: https://github.com/horilla/horilla-hr/blob/1.0/project/templates/task_all/forms/create_project_stage_taskall.html
This section covers the initialization of Select2 components and the registration of various event listeners for data, selection, dropdown, and results components. It also details how to synchronize attributes and handle mutations.
```APIDOC
## Select2 Initialization and Event Handling
### Description
Initializes Select2 components and registers event listeners for data, selection, dropdown, and results. It also handles attribute synchronization and mutation observation.
### Methods
- `_registerDataEvents()`: Registers event listeners for data adapter events.
- `_registerSelectionEvents()`: Registers event listeners for selection events like 'toggle' and 'focus'.
- `_registerDropdownEvents()`: Registers event listeners for dropdown events.
- `_registerResultsEvents()`: Registers event listeners for results events.
- `_registerEvents()`: Registers core Select2 events like 'open', 'close', 'enable', 'disable', 'blur', 'query', 'query:append', and 'keypress'.
- `_syncAttributes()`: Synchronizes Select2's disabled state with the underlying element's disabled attribute.
- `_isChangeMutation(e)`: Determines if a mutation event signifies a change in the selection.
- `_syncSubtree(e)`: Synchronizes the selection data when subtree mutations occur.
### Event Handling
- **'open'**: Adds 'select2-container--open' class to the container.
- **'close'**: Removes 'select2-container--open' class from the container.
- **'enable'**: Removes 'select2-container--disabled' class from the container.
- **'disable'**: Adds 'select2-container--disabled' class to the container.
- **'blur'**: Removes 'select2-container--focus' class from the container.
- **'query'**: Triggers an 'open' event if the dropdown is not open and then queries data.
- **'query:append'**: Appends query results.
- **'keypress'**: Handles key presses for navigation and selection within the dropdown.
### Mutation Observer
- Observes the element for attribute changes, child list modifications, and subtree changes to synchronize Select2's state.
```
--------------------------------
### Get CSRF Cookie
Source: https://github.com/horilla/horilla-hr/blob/1.0/payroll/templates/payroll/payslip/generate_payslip_list.html
A utility function to retrieve the CSRF token from document cookies, necessary for making POST requests in Django applications.
```javascript
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== "") {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + "=")) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
```
--------------------------------
### Handle Build Log Events
Source: https://github.com/horilla/horilla-hr/blob/1.0/static/build/vendor/ionicons/@stencil/core/dev-server/connector.html
Listens for 'devserver:buildlog' events and calls the provided callback with the event details.
```javascript
b=function(e,t){e.addEventListener(k,(function(e){t(e.detail)}))}
```
--------------------------------
### Get CSRF Cookie
Source: https://github.com/horilla/horilla-hr/blob/1.0/onboarding/templates/onboarding/onboarding_view.html
Retrieves the CSRF token from document cookies. This function is essential for making authenticated POST requests in Django applications.
```javascript
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== "") {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + "=")) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
```
--------------------------------
### Install Ionicons Web Component
Source: https://github.com/horilla/horilla-hr/blob/1.0/static/images/ionicons/readme.md
Include this script tag near the end of your page to enable the Ionicons Web Component if not using Ionic Framework.
```html
```
--------------------------------
### Initialize Candidate Selection on Document Ready
Source: https://github.com/horilla/horilla-hr/blob/1.0/onboarding/templates/onboarding/candidates.html
Sets up initial state for candidate selection when the document is ready. It defines messages for different languages and initializes the selection count based on existing selected IDs.
```javascript
$(document).ready(function () {
var excelMessages = {
ar: "هل ترغب في تنزيل ملف Excel؟",
de: "Möchten Sie die Excel-Datei herunterladen?",
es: "¿Desea descargar el archivo de Excel?",
en: "Do you want to download the excel file?",
fr: "Voulez-vous télécharger le fichier Excel?",
};
var ids = JSON.parse($("#selectedInstances").attr("data-ids") || "\[\]");
var uniqueIds = makeListUnique1(ids);
var selectedCount = uniqueIds.length;
var message1 = rowMessages[languageCode]
});
```
--------------------------------
### Configure PostgreSQL on Windows
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Configures a new role and database for Horilla within PostgreSQL on Windows. Access PostgreSQL using the psql command.
```powershell
psql -U postgres
```
```sql
CREATE ROLE horilla LOGIN PASSWORD 'horilla';
```
```sql
CREATE DATABASE horilla_main OWNER horilla;
```
```sql
\q
```
--------------------------------
### Getting Select2 Data (Deprecated)
Source: https://github.com/horilla/horilla-hr/blob/1.0/project/templates/time_sheet/form_task_time_sheet.html
This method is deprecated for setting data. It retrieves the current data associated with the Select2 instance. Use $element.val() instead.
```javascript
o.prototype.data = function() {
this.options.get("debug") && 0 < arguments.length && window.console && console.warn && console.warn('Select2: Data can no longer be set using `select2("data")`. You should consider setting the value instead using `$element.val()`');
var t = [];
return this.dataAdapter.current(function(e) {
t = e
}), t
}
```
--------------------------------
### Get Field Label
Source: https://github.com/horilla/horilla-hr/blob/1.0/templates/filter_tags.html
Retrieves the human-readable label for a given field value, specifically handling 'field' type fields by looking up the option text.
```javascript
function fieldLabel(value, field) { if (field == "field") { return $(`option[value="${value}"]`).html(); } return value; }
```
--------------------------------
### Handle Project Selection and Stage Update (JavaScript)
Source: https://github.com/horilla/horilla-hr/blob/1.0/project/templates/task_all/forms/update_taskall.html
This code listens for changes in the project selection dropdown. If a new project is selected, it fetches project stages via AJAX and populates the stage dropdown. It also handles the 'create new project' option by triggering a modal.
```javascript
$(document).ready(function(){ {% comment %} // $(document).on("change", "#project_stage", function(e) { // task_id = $(this).val() // if (task_id === "create_new_stage") { // $.ajax({ // type: "GET", // url: '/project/create-stage-taskall', // data: { // project_id: project_id // }, // success: function (response) { // $("#ProjectStageModal").addClass("oh-modal--show"); // $("#ProjectStageFormTarget").html(response); // }, // }); // } // }); {% endcomment %} $(document).on("change", "#id_project", function() {
project_id = $(this).val()
if (project_id === 'create_new_project') {
$.ajax({
type: "GET",
url: '/project/create-project-time-sheet',
success: function (response) {
$("#ProjectModal").addClass("oh-modal--show");
$("#ProjectFormTarget").html(response);
},
});
}
if ($.isNumeric(project_id)) {
$.ajax({
type: "GET",
url: "/project/get-stages",
data: {'project_id':project_id},
beforeSend: function () {
$(".errorlist").remove();
},
success:function(response){
$('#project_stage').html("");
for (let i = 0; i < response.data.length; i++) {
const element = response.data[i]
$("#project_stage").append("");
}
$("#project_stage").append( "");
}
});
} else {
$("#project_stage").html("");
$("#project_stage").append( "")
}
});
$(document).on("change", "#project_stage", function(e) {
task_id = $(this).val()
if (task_id === "create_new_stage") {
$.ajax({
type: "GET",
url: '/project/create-stage-taskall',
data: { project_id: project_id },
success: function (response) {
$("#ProjectStageModal").addClass("oh-modal--show");
$("#ProjectStageFormTarget").html(response);
},
});
}
});
});
```
--------------------------------
### JavaScript for Removing Tags
Source: https://github.com/horilla/horilla-hr/blob/1.0/helpdesk/templates/helpdesk/ticket/forms/add_tag.html
Removes a tag from a ticket via an AJAX GET request and updates the UI by removing the tag's card element.
```javascript
function removeTag(element) {
var button = $(element);
var tagId = button.attr("id");
var ticketId = button.data("ticket_id");
tagCard = button.closest('.oh-helpdesk__tag');
$.ajax({
type:'GET',
url:'/helpdesk/remove-tag',
data:{'tag_id':tagId, 'ticket_id':ticketId},
success:function(response){
tagCard.remove()
$(".oh-alert-container").html(response.message)
}
})
}
```
--------------------------------
### Clone Horilla Repository on Windows
Source: https://github.com/horilla/horilla-hr/blob/1.0/README.md
Initializes a Git repository, adds the Horilla remote, and pulls the master branch on Windows.
```powershell
git init
```
```powershell
git remote add horilla https://horilla-opensource@github.com/horilla-opensource/horilla.git
```
```powershell
git pull horilla master
```
--------------------------------
### Render Instance Options
Source: https://github.com/horilla/horilla-hr/blob/1.0/horilla_views/templates/generic/group_by_table.html
Renders action options for a specific instance, checking accessibility before displaying. Supports both predefined options and dynamically generated ones.
```html
{% if not option_method %} {% for option in options %} {% if option.accessibility|accessibility:instance %} []("# "{{option.option|safe}}){% endif %} {% endfor %} {% else %} {{instance|getattribute:option_method|safe}} {% endif %}
```
--------------------------------
### Handle Project Stage Change
Source: https://github.com/horilla/horilla-hr/blob/1.0/project/templates/time_sheet/form_task_time_sheet.html
Listens for changes on the '#project_stage' element. If the selected value is 'create_new_stage', it triggers an AJAX GET request to fetch stage data.
```javascript
$(document).on("change", "#project_stage", function(e){
stage_id = $(this).val()
if (stage_id === "create_new_stage"){
$.ajax({
type: "GET",
url: '/project/create-stage-taskall',
data: {
project_id: {{project_id}}
},
success: function
```
--------------------------------
### Conditional App Rendering in Django Template
Source: https://github.com/horilla/horilla-hr/blob/1.0/templates/floating_button.html
Conditionally renders sections of the template based on whether specific Django applications are installed. This allows for dynamic UI elements.
```django
{% load static i18n %}
{% load horillafilters %}
{% if "helpdesk"|app_installed %}
_sell_
{% endif %} {% if "asset"|app_installed %}
_devices_
{% endif %} {% if "payroll"|app_installed %}
_paid_
{% endif %}
_work_
_history_
{% if "leave"|app_installed %}
calendar_add_on
{% endif %} {% if "attendance"|app_installed %}
person_add
{% endif %}
_{% trans "add" %}_
```
--------------------------------
### Initialize Pivot Table and Handle Model Selection
Source: https://github.com/horilla/horilla-hr/blob/1.0/report/templates/report/recruitment_report.html
Initializes the pivot table with 'candidate' data and sets up an event listener for model selection changes to reload the pivot data.
```javascript
sConfig, cols: [], aggregatorName: "Count", rendererName: "Table", renderers: $.extend($.pivotUtilities.renderers, plotlyRenderers), onRefresh: function (config) { const currentRenderer = config.rendererName; if (["Table", "Table Barchart", "Heatmap", "Row Heatmap", "Col Heatmap"].includes(currentRenderer)) { $("#export-btn").show(); } else { $("#export-btn").hide(); } } }); }); } // Initial load with all models loadPivotData("candidate"); // Model selection change event $("#model-select").on("change", function () { let selectedModel = $(this).val(); loadPivotData(selectedModel); // Reload pivot data with selected model });
```
--------------------------------
### Local Storage Active Menu State Management
Source: https://github.com/horilla/horilla-hr/blob/1.0/templates/sidebar.html
Provides functions to get and set the active menu item in local storage. It stores the ID of the active menu.
```javascript
function getActiveState(id) {
const activeMenu = JSON.parse(localStorage.getItem("activeMenu") || "{}");
return activeMenu === id;
}
function setActiveState(id) {
localStorage.setItem("activeMenu", id);
}
```
--------------------------------
### Handle Build Status Events
Source: https://github.com/horilla/horilla-hr/blob/1.0/static/build/vendor/ionicons/@stencil/core/dev-server/connector.html
Listens for 'devserver:buildstatus' events and calls the provided callback with the event details.
```javascript
w=function(e,t){e.addEventListener(C,(function(e){t(e.detail)}))}
```
--------------------------------
### Local Storage Menu State Management
Source: https://github.com/horilla/horilla-hr/blob/1.0/templates/sidebar.html
Provides functions to get and save the open state of menu items in local storage. It defaults to 'false' if no state is found.
```javascript
function getOpenState(id) {
const menuStates = JSON.parse(localStorage.getItem("menuStates") || "{}");
return menuStates[id] || false;
}
function saveOpenState(id, isOpen) {
const menuStates = JSON.parse(localStorage.getItem("menuStates") || "{}");
menuStates[id] = isOpen;
localStorage.setItem("menuStates", JSON.stringify(menuStates));
}
```
--------------------------------
### Get CSRF Token JavaScript Function
Source: https://github.com/horilla/horilla-hr/blob/1.0/attendance/templates/attendance/grace_time/grace_time_table.html
A utility function to retrieve the CSRF token from document cookies, necessary for making authenticated POST requests in Django applications.
```javascript
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
```