i am creating one project and i want to design one schema of postgres sql give me postgres SQL DDL file
these are project requirements don't miss anything
Users Guide
Created: October, 3, 2024
Types of Users
The overall application will have a few types of users:
Internal Employee
Payroll Employee
Ghost Employee
Client
Vendor
Support Engineer
It is important to note, all users can convert or take on additional responsibilities of another user type. For example, say Client A may get a job placement at Apple and have been there for 2 years. If Client B is joining Apple, we may reach out to Client A to provide support to Client B, thus making Client A a Support Engineer as well.
Depending on the profile type, they will have access to different dashboards.
A new user will come into the platform as a single user type, admin/super admin or anyone with proper privileges can modify and add or remove user types from the profile thus granting or removing access to additional areas of the platform.
Internal Employee
Internal employees are employees who are working directly at Hypinx Consulting performing essential business tasks. These employees are on bi-weekly payroll and can have access/privileges based on feature flags (e.g. being able to create placements, being able to record payments, and so on).
Internal employees may be users such as placement coordinators, assistants, in-house software engineers.
Payroll Employee
Payroll employees are essentially employees who just want to have payroll run on their name for various reasons - to maintain visa status, to show on paper income for other reasons, whatever the case may be. They are employees of Hypinx Consulting but in terms of business operations and contributions serve no real purpose.
The most common type of payroll employee is actually a client who may be on student visa or any other temporary work status.
These employees will follow the same payroll cycle as internal employees, they will send us payment and we will route it right back to them. The business will have a net zero gain on these transactions.
Ghost Employee
Ghost employees are somewhat similar to payroll employees in terms of contributions to business operations. These are usually employees who cannot find a job under their own identity due to visa status constraints, so instead we will get a job under a client and then delegate all the work to the ghost employee.
The client themselves will not be participating in anything, they will only receive a cut every month for having the job under their name.
The ghost employee will be an employee of Hypinx Consulting, we will be their legal employer and payroll will be run through our company to the ghost employee following the payroll cycle set. The ghost employee will perform all the tasks/work for the client’s placement.
Ghost employees may eventually end up getting a job under their own name in the future and they can also continue to choose to do the ghost employee work, this makes them 2 user types: client and ghost employee.
Client
Clients are the most common types of users, these are users who are searching for a job under their own identity, looking to perform the job duties themselves. We serve these users the most and charge commission on placements made for these clients.
Vendor
Vendors are usually foreign entities who provide access to resources (mostly engineers) who are willing to support users with active jobs that are struggling or need expertise in to complete work.
Assistant
Vendors handle paying their support employees, they can choose to refer support engineers and that will go to approval to admin/super admin, once approved their user would be generated in our system and they would be tagged to the vendor who referred them.
Vendors themselves may choose to provide resources and act as a support employee also. By default they will only be onboarded as a vendor, but if they choose to provide support themselves we can add an additional tag as a support engineer to the vendor profile.
Support Engineer
Support engineers are users who provide job duty support to anyone who is actively working. Support engineers can be individuals, come through a vendor, or be existing clients/employees who are willing to provide support.
Onboarding of Users
In general, admin+ should be able to onboard any type of user. There should be a functionality to add a new user to the system where we can specify the user type. Depending on the user type selected, we have different fields to fill out.
Once we fill out the fields, we would have an option to send credentials to the email id specified or to keep the user stale and send the activation details at a later time. The user profile details would be generated in the system but the activation flag would stay as false (e.g. functionalities like reset password would fail if the account is not activated).
Employee Onboarding
Internal Employee
When we select an “Internal Employee” as the user type, we need to fill out the following fields:
First Name
Last Name
Employee Type: Superadmin, Admin, Employee
Phone
Email
Referrer (Optional) - can select any other user with Internal Employee if they were referred by someone
Reports To - specify another user with Internal Employee type as the person they report to
Base Salary (Annual)
Start Date (a future date in which the employee would be joining)
Note - When we go on the employee profile, we can set a specific job title at a later point. This field is not mandatory during the onboarding process, but somewhere we will maintain a list of the positions available and we can assign a role later (e.g. Coordinator, Assistant, Coordinator Manager, etc.)
Payroll Employee
Payroll employee will be the same as Internal Employee
Ghost Employee
Ghost employees will be similar to Internal Employees, except the base salary will be disabled and set to 0 by default. This is because ghost employees will essentially get paid only when they are assigned to a ghost placement, here we will specify the salary and depending on the number of ghost placements active, the salary will be changing.
Client
For clients we have the following:
First Name
Last Name
Phone
Email
Referrer (Optional) - can be anyone with Internal Employee or Client role
Vendor
For vendors we will have the following:
First Name
Last Name
Phone
Email
Referrer (Optional)
Reports To
For “Referrer” and “Reports to”, the selectable users should be any users with an Internal Employee role.
Support Engineer
Support engineers will have the following:
First Name
Last Name
Phone
Email
Referrer (Optional)
Reports To
For support engineers, the “Referrer” field, this can be any user in the system. For the “Reports To” field, this can be anyone tagged with a vendor role.
We can have scenarios where a support engineer comes in through a vendor, or we can hire people directly to provide support people hence we have flexibility and we should be able to tag anyone with a vendor role as the person they report to.
Placements
Overview
The job placements view should give a few capabilities to staff members and clients. For staff members we will by default want to display all placements which have currently been registered (super admin, admin, staff, etc.). We will want to offer filtering options by assigned staff member, client information, employer, and status. We should also have a subsection labeled “My Placements” or similar which the staff member will click which by default shows only placements they are marked as the owner of.
From the client’s view they will only be able to see placements for themselves and have filtering options by staff member, employer, and status.
By default, super admin and admin should be able to create/view/modify placements. Not all staff members can access the placements section - this will be a feature flag and we can enable privileges such as viewing placements, creating, and editing (editing their own placements and/or being able to edit all placements, even those created by other staff).
Placements
Creating a Placement
Placements can only be created by staff members who have the create placement privilege enabled. In order to create a placement they can navigate to the page and click a button. We should be routed to a page where we can pre-fill some information. The only mandatory field for creating should be selecting a client the placement is for, this will link the placement to the client’s portfolio.
There are two types of placements which can be created:
Regular (Default)
Ghost
Regular placements are for clients who are searching for a job themselves. Ghost placements are for clients who want a job under their name but expect another person to do the work. The other person is a Ghost employee (Hypinx employee).
Regular Placement
Selecting Regular placement we will need the following mandatory fields when creating the placement and the following steps needed to transition from one stage to the next.
Position Related:
Employer (Select from drop down or add new one)
Job Title (Select from drop down or add new one) - Job titles will be selectable based on employer selected
Work Locations: (Can select multiple from drop down, drop down menu is can vary based on which employer is selected since corporate offices can be in different cities/states for different companies)
Commission Related: all fields here can be left empty but must be defined before going from Offer to Background Check stage
Monthly Commission Amount (total)
Monthly Commission Amount Start Date
Monthly Commission Amount End Date (auto calculates based on 360 months (or we can override and define our own timeframe at this time) from start date)
Monthly Commission Amount (per month) - auto calculates based on total divided by total months specified (by default is 360 months)
Clearance Amount (total)
Clearance Amount Deposit
Clearance Amount Deposit Due Date
Lump Sum Amount (total)
Lump Sum Amount Due Date
Remaining Balance (Auto calculated: clearance amount - deposit - lump sum)
Remaining Balance Payment Plan (number of months to split over)
Remaining Balance Payment Start Date
Remaining Balance Payment End Date
Compensation Related: all fields here can be left empty but must be defined before going from Offer to Background Check stage
Base Salary
Sign On Bonus
Relocation Bonus
Annual Bonus
RSU’s - composed of amount (in USD) and vesting period (in years) - 2 fields necessary for this section
Ghost Placement
Selecting ghost placement we will have the following fields when creating the placement
Client
Ghost Employee (Optional)
code
Position Related:
Employer (Select from drop down or add new one)
Job Title (Select from drop down or add new one) - same as above
Work Locations: (Can select multiple from drop down, drop down menu is can vary based on which employer is selected since corporate offices can be in different cities/states for different companies)
code
Ghost Employee Salary
Annual Salary
Employment Type: 1099, W2, Cash
code
Cut to Client:
Monthly Salary: this is a fixed amount which will be received to the client per month for having the job under their name
Compensation Related: all fields here can be left empty but must be defined before
going from Offer to Background Check stage
Base Salary
Sign On Bonus
Relocation Bonus
Annual Bonus
RSU’s - composed of amount (in USD) and vesting period (in years) - 2 fields necessary for this section
Placement Lifecycle
Some fields on the placement which can be pre-filled would be: employer (must be selected from a dropdown), job title, a resume (uploaded by staff member), placement nickname (in the overall view if a nickname is specified the placement would have this nickname showing, otherwise we can use a default format of: client_name-employer-placementNumber where placementNumber is the incremental count of all previous placements for this specific client/employer combo.). The only mandatory field when creating a placement is to select the client.
Example - I have client Mark Smith whom we created 2 placements for at Apple. Both previous placements resulted in failure. If we make a new placement at Apple and do not specify a nickname, the default name would be “Mark_Smith-Apple-3”
Note - Super admin should have access to disable nickname feature for all staff, if this feature is disabled then the name disabled in the dashboard should follow the default naming format.
Each job placement will have the following statuses to select from as the placement moves forward in the life cycle:
Pre-Screen (default upon creation)
Awaiting Documents
Awaiting Agreement Forms
Pre-Submission
Submitted
Interviewing
Offer
Background Check
Onboarding
Active
Resigned
Terminated
Removed From Consideration
Failed
From Pre-Screen to Active stages, we can only move forward on stage at a time. Each movement there may be mandatory things required before being able to move forward which is mentioned below. Only from Pre-Screen to Active, from these stages we can go to “Failed” or “Removed from Consideration” at any time.
Example: Pre-Screen → Awaiting Documents → Awaiting Agreement Forms is allowed. But Pre-Screen → Awaiting Agreement Forms is NOT allowed.
Pre-Screen → Awaiting Agreement Forms → Failed is allowed.
Mandatory Requirements Between Stages (Regular Placement)
Moving between stages will have one or more mandatory tasks which need to be marked as complete before we can move forward.
Pre-Screen → Awaiting Documents
Checkbox to confirm if pre-screen phone call and/or meeting is completed
Checkbox to confirm if client has sent acknowledgement response to follow up email
Awaiting Documents → Awaiting Agreement Forms
A popup with a checklist of all documents required (set by superadmin). Each checkbox will have the most recent version of the document next to it which can be viewable in another page. Once the document is verified, the member can check the box to mark as valid
If multiple versions exist of the document, we display the latest one and give an option to view all documents which will open a new tab and a hyperlink to each document which can be viewable in the browser
Once all checkboxes are marked as complete we can mark the entire task as complete and then move to the next stage
If a document is not present, there should be an option to automatically send an email notifying the client of all the unchecked documents missing and request them to upload into the portal. The staff member should be able to enter a custom note as well for each document.
Example - Driver’s license is present but is expired, hence the updated license is needed. Staff member should be able to specify this as a comment
By sending an email, this should create a task on the client’s portfolio, after the client has completed the upload, they can mark it as resolved thus triggering an email notification to all the people following this placement.
Awaiting Agreement Forms → Pre-Submission
Staff member must upload a copy of the signed agreement forms
Commission charges must be updated into the job placement
Pre-Submission → Submitted
Client resume must be present on the job placement (can be uploaded upon creation) or must be uploaded at this time
Submitted → Interviewing
No mandatory tasks
Interviewing → Offer
No mandatory tasks
Offer → Background Check
Offer Letter (final) must be uploaded at this time
Additional documents related to the job offer if applicable can be uploaded (optional)
We must fill out payment term details: base salary, monthly commission, clearance amount (deposit, lump sum, start/end date of installments which will automatically calculate based on the remaining balance)
Background Check → Onboarding
Background check results file (if results are not given there should be an option to mark as no document to upload which will automatically complete this task)
Screenshot of fingerprinting appointment confirmation (optional)
Screenshot of drug screen appointment confirmation (optional)
Onboarding → Active
Confirmation of sending “pre-onboarding” email to client
Confirmation of reviewing the email with the client
Confirmation of forwarded necessary emails/document to the client and reviewing them on call
Confirmation of google doc being updated prior to joining
The following steps are only allowed from one direction:
Active → Resigned
Must specify a resignation date
Must specify penalty amount if applicable
Must upload a separation letter (can be marked with a no document to upload which automatically completes the task)
Active → Terminated
Must specify a termination date
Must upload a separation letter (can be marked with a no document to upload which automatically completes the task)
We can move from any of these stages to “Removed From Consideration” and “Failed” at any time. When moving to these stages we must specify a reason. There can be a penalty associated with “Failed” if the client reaches the offer stage within the specified contract terms but refuses to accept the offer or backs out.
Mandatory Requirements Between Stages (Ghost Placement)
Moving between stages will have one or more mandatory tasks which need to be marked as complete before we can move forward.
Pre-Screen → Awaiting Documents
Checkbox to confirm if pre-screen phone call and/or meeting is completed
Checkbox to confirm if client has sent acknowledgement response to follow up email
Awaiting Documents → Awaiting Agreement Forms
A popup with a checklist of all documents required (set by superadmin). Each checkbox will have the most recent version of the document next to it which can be viewable in another page. Once the document is verified, the member can check the box to mark as valid
If multiple versions exist of the document, we display the latest one and give an option to view all documents which will open a new tab and a hyperlink to each document which can be viewable in the browser
Once all checkboxes are marked as complete we can mark the entire task as complete and then move to the next stage
If a document is not present, there should be an option to automatically send an email notifying the client of all the unchecked documents missing and request them to upload into the portal. The staff member should be able to enter a custom note as well for each document.
Example - Driver’s license is present but is expired, hence the updated license is needed. Staff member should be able to specify this as a comment
By sending an email, this should create a task on the client’s portfolio, after the client has completed the upload, they can mark it as resolved thus triggering an email notification to all the people following this placement.
Awaiting Agreement Forms → Pre-Submission
Staff member must upload signed employment agreement forms for the Ghost employee
Staff member must upload signed agreement forms with client (optional)
Pre-Submission → Submitted
No mandatory tasks
Submitted → Interviewing
No mandatory tasks
Interviewing → Offer
Client resume must be present on the job placement (can be uploaded upon creation) or must be uploaded at this time
Offer → Background Check
Offer Letter (final) must be uploaded at this time
Additional documents related to the job offer if applicable can be uploaded (optional)
Cut to Client must be filled in on the placement form
Ghost employee must be selected and their salary must be filled in
Compensation details must be filled in
Background Check → Onboarding
Background check results file (if results are not given there should be an option to mark as no document to upload which will automatically complete this task)
Screenshot of fingerprinting appointment confirmation (optional)
Screenshot of drug screen appointment confirmation (optional)
Onboarding → Active
Confirmation of sending “pre-onboarding” email to client (Ghost version)
Confirmation of reviewing the email with the client
Confirmation of forwarded necessary emails/document to the client and reviewing them on call
Confirmation of google doc being updated prior to joining
The following steps are only allowed from one direction:
Active → Resigned
Must specify a resignation date
Must specify penalty amount if applicable
Must upload a separation letter (can be marked with a no document to upload which automatically completes the task)
Active → Terminated
Must specify a termination date
Must upload a separation letter (can be marked with a no document to upload which automatically completes the task)
We can move from any of these stages to “Removed From Consideration” and “Failed” at any time. When moving to these stages we must specify a reason. There can be a penalty associated with “Failed” if the client reaches the offer stage within the specified contract terms but refuses to accept the offer or backs out.
Penalty Placements
Placements which were closed and contain a penalty should be flagged (maybe with a penalty checkbox on the dashboard and individual placement itself). Placements with penalties should have a way to record payments towards the penalty amount.
Example - Mark Smith refuses to take the offer and we penalize with 5,000.Placementisnowat“Failed”statusandapenaltyof5,000 exists. 10 days from now Mark makes a payment of 1,000.Werecordthe1,000 payment on the job placement itself (this should also update with the incoming revenue as a whole) and now the penalty balance shows $4,000 outstanding.
When adding a penalty to the placement, we should be able to specify a due date for the entire amount, if we do not specify then we allow by default 1 year to make the penalty payment.
Following Placements
Staff users should be able to “follow” a placement, whenever there is meaningful activity we should also notify followers of the placement of the activity.
We should be able to filter the overall dashboard by placements we follow and have a subsection to manage placements are we following (e.g. If we follow 100 placements then with the click of one button we should be able to unfollow everything, or we can view all the placements and when we edit the following ones, we simply uncheck the ones we have no interest in anymore).
Adding Existing/Old Placements
Left to fill
Financial Inflows and Outflows Overview
Created: June 18th, 2024
Last Modified: June 30th, 2024
Overview
Hypinx Consulting earns revenue in 4 different ways.
Commission from job placements for clients
Running payroll for student visa holders and H1B
Assigning eligible Hypinx Consulting employee as a proxy employee for a client
Internal Hypinx Consulting employee - does actual work for the company
More information about the revenue sources is defined below.
Commission From Job Placements For Clients
When placing clients on a job, there is a fixed monthly rate which is charged to the client. This amount is fixed and recurring over 30 years of their job placement. Once a job placement is complete, the monthly commission starts from day one of the placement - we should have the ability to specify a start date on the job placement after the recruitment process is completed.
The second portion to the commission is optional but it is called a clearance package. This is a one time fee which is charged and once it is paid off it is complete.
The one time fee can come with the following components: deposit (charged prior to joining), a lump-sum amount which is paid towards the balance, and remaining balance which is split over 12 monthly installments. We should be able to specify the start month/year when the installments will begin and an end-date as well. Note - the installments may begin sometime in the future and not necessarily the first day of joining. The lump sum payment is usually defined prior to joining and a tentative charge date is also specified, therefore calculating the remaining balance is doable.
Sample placement: Assume a client has successfully gotten a placement. The client’s start date is July 15th, 2024. The commission package which we are charging him is 3,000/monthformonthlycommissionand45,000 for clearance cost.
Clearance package is broken down as follows:
4,500deposit18,900 lump sum charged on 26th, 2024
Remaining balance: 45,000 - 4,500 - 18,900 = 21,600 split over 12 months starting from August 2024 to July 2025, equal installments of $1,800/month
Since the client has joined mid-month, the month of July we prorate the monthly charge to be 1,645.Thisiscalculatedusingthefollowingformula:Numberofactiv3,000
Charge = (number of active days/total days) * monthly rate = (17/31) * (3000) = 1645
We should have an option to specify if the same month the client starts, will we bill them the same month or postpone that bill to the following month.
In this situation we would postpone it to the following month. So the commission for June would be 0 but for July would include the cost of June and July. July’s commission is therefore calculated as follows:
1,645−proratedforJune3,000 - monthly for July
18,900−lumpsumpaymentdefinedTotal=23,545
For August it would be as follows:
3,000−monthlyforAugust1,800 - clearance installment 1 of 12
Total = $4,800
Additional Features:
We should have the option to specify a % discount on the monthly commission for some duration (a start and end date). For most clients if they are existing members, we reduce the monthly commission by 25% for the first 365 days they are active. So if we apply a 25% discount to the example client, from July 15th, 2024 to July 14th, 2025, they would have a monthly rate of 2,250insteadof3,000. This discount ONLY applies to monthly, there is no discount to the clearance costs.
Refund a partial or full payment - in some scenarios if the client is let go from the role or resigns, we must refund back a portion of the payment. We should have the ability to enter an amount on a specific payment, if we do not want to specify a specific payment we should have the ability to note this on the entire job placement itself
Postpone or rollover a payment - In some scenarios due to financial situations, if a client is unable to make a payment we may roll the payment over to a later month. We must have the ability to track the payment and any gaps rolling over may create
Example - A client has the 25% discount active and they are on the last month. We decide to roll over the payment of 2,250,forthenextmonththepaymentcalculatedshouldbe3,000. So their total balance should include month 12 + month 13 for a total of $5,250.
Penalties
Clients can incur penalties in various different forms:
Failure to pay - if a client stops paying this can incur a breach of contract which results in penalties and potentially lead to a civil lawsuit if unresolved. The payment balance should continue to be calculated and tracked until a resolution is made (client pays the amount, client is sued in court and funds are retrieved, or until we drop the penalty amount).
Example - We had one client who stopped paying in August 2023. Payment was 825amonthandwetrackeduntilMay2024,thetotalamountwas8,250 + 350latefees(35 per month). But the client was not aware they were terminated on April 29th, 2024. In this scenario we did not charge any interest, only a flat late fee. Therefore when we update the placement to termination and specify the date of April 29th, 2024 - the penalty amount should be recalculated to include from August 1, 2023 to April 29th, 2024.
This would be (825 * 8 months) + ((29/30) * 825) = 7,397.50+315 (35. If client payment is recorded on July 11th, for the month of August they will have their normal payment + $35 late fee from July.
Late fees should have the option to be waived or dropped entirely.
Note - It’s possible a client made the payment before the due date and we just did not get a chance to record the payment. Now it’s past the due date, on their balance it would now show a late fee. But when we record the payment, say on July 14th, we can mark that the payment was made on July 7th which is before the due date and now the late fee would be dropped.
Early Resignation - Each job placement is subject to a minimum term, usually to 1 year. For every placement, once we change the stage to “Active” or something similar, we have to specify what is the start date and what is the “minimum commitment date” which represents till when does the client need to work to not incur penalties. If the client is fired or laid off then we do not charge penalties, only under voluntary resignation.
Likewise, when a job placement ends and we switch the stage to “inactive” we should specify a clause (e.g. termination, lay off, voluntary resignation) and then we manually include a penalty if they incurred one.
All payments and penalties are subject to interest, for every job placement we should be able to specify an annual interest amount for any outstanding balance which has not been paid. For every day past the due date, interest is automatically calculated based on the pending balance.
Running payroll for student visa holders and H1B
These clients will fall under the “Hypinx Employee” category and will be classified as “Payroll Employee”.
For payroll employees, they will be sending money to the business and in return we will generate payroll based on some salary discussed. The business will have a net zero revenue from these employees but we still have to track how much money has entered and exited.
For example - Let’s say we have a client called Dhruv who is running a salary of 60,000annually.Sincewepaybi−weeklyforallemployees,every2weekswewillrunapayrollof2307.69. Dhruv will need to have sent this amount or higher before we are able to run the salary.
Assuming payroll falls on July 15th, July 30th, August 15th, and August 30th (these are just dummy payroll dates), Dhruv sends over 5,000June30th.His“account”hasabalanceof5,000. When July 15th comes around we run a payroll of 2307.69.Hisaccountnowhasremainingfundsof2,692.31. On July 30th we run another payroll of 2307.69sohisfinalbalanceisnow384.62. There is not enough funds to run another payroll. So 5 days prior to the next payroll, we want to start sending notifications to Dhruv mentioning his balance is 384.62andheneedstosendatleastanother1,923.07 in order to run a payroll of $2307.69 by August 15th.
Now Dhruv will send over say 3,000sohisbalanceisat3,384.62. On August 15th we ran the next payroll of 2307.69,hisbalancenowremainsat1,076.93.
Everytime the client sends funds we need to manually update onto this payroll employee profile and everytime payroll is run we also need to update that. Every incoming funds from the client will increase the running balance and every payroll run will decrease the running balance. The running balance is simply how much money the client has sent which has still not been sent back via payroll.
All the payroll we run is essentially tax deductible hence the need to track it. The client can send funds in multiple forms - cash, zelle, payment to others, etc, hence there is no automatic way to track it and needs manual intervention. Payroll is always ran through a payment processor called Bill.com, so the eventual goal for recording payroll will be to integrate an API to track it.
Assigning eligible Hypinx Consulting employee as a proxy employee for a client
These employees are essentially internal salaried employees (see next section), however they are conducting “proxy” work for a client. These employees need to be tagged to a client portfolio to indicate whose name the job is under. We can have a one to many relationship here as one proxy employee can work multiple jobs under the same person, or a mix of people.
The client whose portfolio the proxy is tagged to should also see details on the placement and whatever cut is going to the client should also be updated on their client card as well for each proxy placement present.
Example: Assume Dhruv is a proxy employee and the client is Pratik. Dhruv is paid 60,000annuallyfromHypinxConsulting,Pratiktakesacutof1,100 per month.
After 1 year of employment - Dhruv earned 60,000whereasPratikearned13,200. We should be able to query for this data over some time range as well as see “lifetime” earnings of Pratik.
Internal Hypinx Consulting Employee
This is a simple category, these are employees we have hired internally which are paid either annual or hourly.
For annual (salaried) paid employees, whatever annual salary is given, we will divide by 2080 and this will be their hourly rate. Salaried employees will not need to enter an hour in timesheets as they will by default be paid on a 40 hour per week scale.
Hourly employees when setting up in the system, we will need to specify an hourly rate, a cap on how many weekly hours they can work (usually to 40 but part time employees might have a lower cap). They will need to enter hours on a per day basis in order to generate proper payroll. This type of internal employee will be rare but potentially will have 2-3 in the long run.
As of right now, payroll for these employees will also be ran from bill.com therefore when payroll is ran, we will need to manually enter on these employees and specify the date it was run. Eventually the idea is to integrate API’s from bill.com to automatically update this data into the application.
Certainly! Below is a comprehensive PostgreSQL DDL (Data Definition Language) script that captures the requirements you've outlined for your project. This script defines the necessary tables, relationships, and constraints to model users with multiple types, placements with various stages, financial transactions, and more.
Overview of the Schema
Users and User Types:
users: Stores general user information.
user_types: Defines the different types of users.
user_user_types: Many-to-many relationship between users and their types.
roles and user_roles: Defines roles like Admin and Superadmin with associated privileges.
User-Specific Information:
internal_employee_info
client_info
vendor_info
support_engineer_info
Organizational Structure:
employers
job_titles
work_locations
Placements:
placements
placement_statuses
placement_documents
placement_tasks
Financials:
commissions
payments
penalties
Additional Features:
feature_flags: To manage feature-based access.
notifications: To handle notifications for followers.
PostgreSQL DDL Script
sql
-- ================================================
-- ENUM TYPES
-- ================================================
-- Employee Types
CREATE TYPE employee_type_enum AS ENUM ('superadmin', 'admin', 'employee');
-- User Types
CREATE TYPE user_type_enum AS ENUM (
'internal_employee',
'payroll_employee',
'ghost_employee',
'client',
'vendor',
'support_engineer'
);
-- Placement Types
CREATE TYPE placement_type_enum AS ENUM ('regular', 'ghost');
-- Placement Statuses
CREATE TYPE placement_status_enum AS ENUM (
'pre_screen',
'awaiting_documents',
'awaiting_agreement_forms',
'pre_submission',
'submitted',
'interviewing',
'offer',
'background_check',
'onboarding',
'active',
'resigned',
'terminated',
'removed_from_consideration',
'failed'
);
-- Employment Types
CREATE TYPE employment_type_enum AS ENUM ('1099', 'W2', 'cash');
-- Payment Types
CREATE TYPE payment_type_enum AS ENUM ('deposit', 'lump_sum', 'installment', 'refund', 'rollover');
-- Penalty Types
CREATE TYPE penalty_type_enum AS ENUM ('failure_to_pay', 'late_fee', 'early_resignation');
-- ================================================
-- USERS AND USER TYPES
-- ================================================
-- Users Table
CREATE TABLE users (
id SERIAL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
phone VARCHAR(20),
email VARCHAR(100) UNIQUE NOT NULL,
is_active BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
referrer_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
reports_to_id INTEGER REFERENCES users(id) ON DELETE SET NULL
);
-- User Types Table
CREATE TABLE user_types (
id SERIAL PRIMARY KEY,
type_name user_type_enum UNIQUE NOT NULL
);
-- Insert User Types
INSERT INTO user_types (type_name) VALUES
('internal_employee'),
('payroll_employee'),
('ghost_employee'),
('client'),
('vendor'),
('support_engineer');
-- User_User_Types Linking Table
CREATE TABLE user_user_types (
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
user_type_id INTEGER REFERENCES user_types(id) ON DELETE CASCADE,
PRIMARY KEY (user_id, user_type_id)
);
-- Roles Table
CREATE TABLE roles (
id SERIAL PRIMARY KEY,
role_name VARCHAR(50) UNIQUE NOT NULL
);
-- Insert Roles
INSERT INTO roles (role_name) VALUES
('superadmin'),
('admin'),
('employee');
-- User_Roles Linking Table
CREATE TABLE user_roles (
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
role_id INTEGER REFERENCES roles(id) ON DELETE CASCADE,
PRIMARY KEY (user_id, role_id)
);
-- ================================================
-- FEATURE FLAGS
-- ================================================
CREATE TABLE feature_flags (
id SERIAL PRIMARY KEY,
feature_name VARCHAR(100) UNIQUE NOT NULL,
is_enabled BOOLEAN DEFAULT FALSE
);
-- User_Feature_Flags Linking Table
CREATE TABLE user_feature_flags (
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
feature_id INTEGER REFERENCES feature_flags(id) ON DELETE CASCADE,
is_enabled BOOLEAN DEFAULT FALSE,
PRIMARY KEY (user_id, feature_id)
);
-- ================================================
-- USER-SPECIFIC INFORMATION
-- ================================================
-- Internal Employee Info
CREATE TABLE internal_employee_info (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
employee_type employee_type_enum NOT NULL,
base_salary DECIMAL(15,2) DEFAULT 0,
start_date DATE,
job_title_id INTEGER REFERENCES job_titles(id),
-- Additional fields can be added here
UNIQUE (user_id)
);
-- Payroll Employee Info (inherits from internal_employee_info)
CREATE TABLE payroll_employee_info (
user_id INTEGER PRIMARY KEY REFERENCES internal_employee_info(user_id) ON DELETE CASCADE,
-- Additional fields specific to payroll employees can be added here
UNIQUE (user_id)
);
-- Ghost Employee Info (inherits from internal_employee_info)
CREATE TABLE ghost_employee_info (
user_id INTEGER PRIMARY KEY REFERENCES internal_employee_info(user_id) ON DELETE CASCADE,
-- Additional fields specific to ghost employees can be added here
UNIQUE (user_id)
);
-- Client Info
CREATE TABLE client_info (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
-- Additional client-specific fields can be added here
UNIQUE (user_id)
);
-- Vendor Info
CREATE TABLE vendor_info (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
reports_to INTEGER REFERENCES users(id) ON DELETE SET NULL,
UNIQUE (user_id)
);
-- Support Engineer Info
CREATE TABLE support_engineer_info (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
reports_to INTEGER REFERENCES users(id) ON DELETE SET NULL,
UNIQUE (user_id)
);
-- ================================================
-- ORGANIZATIONAL STRUCTURE
-- ================================================
-- Employers Table
CREATE TABLE employers (
id SERIAL PRIMARY KEY,
name VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Job Titles Table
CREATE TABLE job_titles (
id SERIAL PRIMARY KEY,
employer_id INTEGER REFERENCES employers(id) ON DELETE CASCADE,
title VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE (employer_id, title)
);
-- Work Locations Table
CREATE TABLE work_locations (
id SERIAL PRIMARY KEY,
employer_id INTEGER REFERENCES employers(id) ON DELETE CASCADE,
location VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE (employer_id, location)
);
-- ================================================
-- PLACEMENTS
-- ================================================
-- Placements Table
CREATE TABLE placements (
id SERIAL PRIMARY KEY,
placement_type placement_type_enum NOT NULL,
client_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
employer_id INTEGER REFERENCES employers(id) ON DELETE SET NULL,
job_title_id INTEGER REFERENCES job_titles(id) ON DELETE SET NULL,
placement_nickname VARCHAR(100),
status placement_status_enum DEFAULT 'pre_screen',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE (client_id, employer_id, job_title_id, placement_nickname)
);
-- Placements can have multiple work locations
CREATE TABLE placement_work_locations (
placement_id INTEGER REFERENCES placements(id) ON DELETE CASCADE,
work_location_id INTEGER REFERENCES work_locations(id) ON DELETE CASCADE,
PRIMARY KEY (placement_id, work_location_id)
);
-- Placement Statuses History
CREATE TABLE placement_status_history (
id SERIAL PRIMARY KEY,
placement_id INTEGER REFERENCES placements(id) ON DELETE CASCADE,
previous_status placement_status_enum,
new_status placement_status_enum,
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
changed_by INTEGER REFERENCES users(id) ON DELETE SET NULL
);
-- Placement Documents
CREATE TABLE placement_documents (
id SERIAL PRIMARY KEY,
placement_id INTEGER REFERENCES placements(id) ON DELETE CASCADE,
document_type VARCHAR(100),
document_url VARCHAR(255),
uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
uploaded_by INTEGER REFERENCES users(id) ON DELETE SET NULL
);
-- Placement Tasks (Mandatory requirements between stages)
CREATE TABLE placement_tasks (
id SERIAL PRIMARY KEY,
placement_id INTEGER REFERENCES placements(id) ON DELETE CASCADE,
task_description TEXT NOT NULL,
is_completed BOOLEAN DEFAULT FALSE,
completed_at TIMESTAMP,
completed_by INTEGER REFERENCES users(id) ON DELETE SET NULL
);
-- ================================================
-- FINANCIALS
-- ================================================
-- Commissions Table
CREATE TABLE commissions (
id SERIAL PRIMARY KEY,
placement_id INTEGER REFERENCES placements(id) ON DELETE CASCADE,
monthly_amount DECIMAL(15,2),
monthly_start_date DATE,
monthly_end_date DATE,
per_month_amount DECIMAL(15,2),
clearance_total DECIMAL(15,2),
clearance_deposit DECIMAL(15,2),
clearance_deposit_due_date DATE,
clearance_lump_sum DECIMAL(15,2),
clearance_lump_sum_due_date DATE,
clearance_remaining_balance DECIMAL(15,2) GENERATED ALWAYS AS (
clearance_total - clearance_deposit - clearance_lump_sum
) STORED,
clearance_payment_plan INTEGER,
clearance_payment_start_date DATE,
clearance_payment_end_date DATE,
discount_percentage DECIMAL(5,2) DEFAULT 0,
discount_start_date DATE,
discount_end_date DATE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Payments Table
CREATE TABLE payments (
id SERIAL PRIMARY KEY,
placement_id INTEGER REFERENCES placements(id) ON DELETE CASCADE,
payment_type payment_type_enum NOT NULL,
amount DECIMAL(15,2) NOT NULL,
payment_date DATE NOT NULL,
processed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
processed_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
note TEXT
);
-- Penalties Table
CREATE TABLE penalties (
id SERIAL PRIMARY KEY,
placement_id INTEGER REFERENCES placements(id) ON DELETE CASCADE,
penalty_type penalty_type_enum NOT NULL,
amount DECIMAL(15,2) NOT NULL,
accrued_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_resolved BOOLEAN DEFAULT FALSE,
resolved_at TIMESTAMP,
resolved_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
note TEXT
);
-- ================================================
-- ADDITIONAL FEATURES
-- ================================================
-- Feature Flags Table
CREATE TABLE feature_flags (
id SERIAL PRIMARY KEY,
feature_name VARCHAR(100) UNIQUE NOT NULL,
is_enabled BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Followers for Placements
CREATE TABLE placement_followers (
placement_id INTEGER REFERENCES placements(id) ON DELETE CASCADE,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
followed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (placement_id, user_id)
);
-- Notifications Table
CREATE TABLE notifications (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
placement_id INTEGER REFERENCES placements(id) ON DELETE CASCADE,
message TEXT NOT NULL,
is_read BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- ================================================
-- TRIGGERS AND FUNCTIONS
-- ================================================
-- Example Trigger to Update 'updated_at' on Row Modification
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
-- Attach Trigger to Relevant Tables
DO $$
BEGIN
-- List of tables to attach the trigger
PERFORM 'public.placements';
EXECUTE 'CREATE TRIGGER update_placements_updated_at BEFORE UPDATE ON placements
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();';
EXECUTE 'CREATE TRIGGER update_users_updated_at BEFORE UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();';
EXECUTE 'CREATE TRIGGER update_internal_employee_info_updated_at BEFORE UPDATE ON internal_employee_info
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();';
EXECUTE 'CREATE TRIGGER update_client_info_updated_at BEFORE UPDATE ON client_info
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();';
EXECUTE 'CREATE TRIGGER update_vendor_info_updated_at BEFORE UPDATE ON vendor_info
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();';
EXECUTE 'CREATE TRIGGER update_support_engineer_info_updated_at BEFORE UPDATE ON support_engineer_info
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();';
EXECUTE 'CREATE TRIGGER update_commissions_updated_at BEFORE UPDATE ON commissions
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();';
EXECUTE 'CREATE TRIGGER update_payments_updated_at BEFORE UPDATE ON payments
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();';
EXECUTE 'CREATE TRIGGER update_penalties_updated_at BEFORE UPDATE ON penalties
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();';
-- Add more triggers as necessary
END;
$$;
-- ================================================
-- SAMPLE INDEXES
-- ================================================
-- Index on Placements for Faster Lookup
CREATE INDEX idx_placements_client_id ON placements(client_id);
CREATE INDEX idx_placements_employer_id ON placements(employer_id);
CREATE INDEX idx_placements_status ON placements(status);
-- Index on Users for Searches
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_last_name ON users(last_name);
-- ================================================
-- CONSTRAINTS AND RULES
-- ================================================
-- Ensure a user cannot have duplicate user types
ALTER TABLE user_user_types
ADD CONSTRAINT unique_user_type_per_user UNIQUE (user_id, user_type_id);
-- Ensure a user has only one role (optional, if roles are exclusive)
-- ALTER TABLE user_roles
-- ADD CONSTRAINT unique_role_per_user UNIQUE (user_id);
-- Ensure that 'placement_nickname' follows the default naming if not provided
CREATE OR REPLACE FUNCTION set_default_nickname()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.placement_nickname IS NULL THEN
SELECT CONCAT(u.first_name, '_', u.last_name, '-', e.name, '-', COUNT(p.id)+1)
INTO NEW.placement_nickname
FROM users u
JOIN employers e ON e.id = NEW.employer_id
JOIN placements p ON p.client_id = NEW.client_id AND p.employer_id = NEW.employer_id
WHERE p.client_id = NEW.client_id AND p.employer_id = NEW.employer_id;
END IF;
RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';
CREATE TRIGGER set_default_nickname_trigger
BEFORE INSERT ON placements
FOR EACH ROW
EXECUTE FUNCTION set_default_nickname();
-- ================================================
-- SAMPLE DATA INSERTS (Optional)
-- ================================================
-- Insert Sample Employers
INSERT INTO employers (name) VALUES ('Apple'), ('Google'), ('Microsoft');
-- Insert Sample Job Titles
INSERT INTO job_titles (employer_id, title) VALUES
((SELECT id FROM employers WHERE name='Apple'), 'Software Engineer'),
((SELECT id FROM employers WHERE name='Google'), 'Data Scientist'),
((SELECT id FROM employers WHERE name='Microsoft'), 'Product Manager');
-- Insert Sample Work Locations
INSERT INTO work_locations (employer_id, location) VALUES
((SELECT id FROM employers WHERE name='Apple'), 'Cupertino, CA'),
((SELECT id FROM employers WHERE name='Google'), 'Mountain View, CA'),
((SELECT id FROM employers WHERE name='Microsoft'), 'Redmond, WA');
-- ================================================
-- VIEWS (Optional for Simplification)
-- ================================================
-- Example View: Active Placements
CREATE VIEW active_placements AS
SELECT * FROM placements
WHERE status = 'active';
-- ================================================
-- END OF DDL SCRIPT
-- ================================================
Explanation of Key Components
Users and User Types:
users: Central table storing all user-related information. The referrer_id and reports_to_id columns create a self-referential relationship to capture referral and reporting structures.
user_types: Defines the various user types as ENUMs for consistency.
user_user_types: Facilitates a many-to-many relationship between users and their types, allowing users to have multiple roles.
roles and user_roles: Separate from user types, these handle administrative privileges like Admin and Superadmin.
User-Specific Information:
Separate tables like internal_employee_info, client_info, vendor_info, and support_engineer_info store additional attributes specific to each user type.
Organizational Structure:
employers, job_titles, and work_locations tables organize information about employers, their job titles, and work locations. These are linked to placements.
Placements:
placements: Core table managing job placements with fields to distinguish between regular and ghost placements.
placement_work_locations: Handles the many-to-many relationship between placements and work locations.
placement_status_history: Tracks the history of status changes for each placement.
placement_documents and placement_tasks: Manage documents and mandatory tasks required for transitioning between placement stages.
Financials:
commissions: Manages commission-related information for each placement, including monthly amounts and clearance packages.
payments: Records all payments related to placements, including deposits, lump sums, installments, refunds, and rollovers.
Next Steps
Data Population: Use the provided sample inserts to populate initial data for employers, job titles, and work locations.
Extending the Schema: Depending on additional requirements, you might need to add more tables or fields, especially for handling complex financial calculations and integrations with payment processors like Bill.com.
API Integration: Implement APIs to handle dynamic features like sending emails, managing tasks, and updating placements based on external events.
Testing: Thoroughly test the schema with sample data to ensure all relationships and constraints behave as expected.
This schema provides a robust foundation based on your requirements. However, given the complexity of the project, it might require iterative refinements to cater to all edge cases and additional features you may envision in the future.