Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add invoice posting for GL Account purchase order lines (#50)

Brad Barbinf92e83597fa8
diff --git a/apps/carbon/app/components/Form/Account.tsx b/apps/carbon/app/components/Form/Account.tsx
index 2356ee1a55..1e28ffec34 100644
--- a/apps/carbon/app/components/Form/Account.tsx
+++ b/apps/carbon/app/components/Form/Account.tsx
@@ -8,11 +8,13 @@ import {
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo } from "react";
import { useControlField, useField } from "remix-validated-form";
-import type { getAccountsList } from "~/modules/accounting";
+import type { AccountClass, getAccountsList } from "~/modules/accounting";
import { path } from "~/utils/path";
import type { SelectProps } from "./Select";
-type AccountSelectProps = Omit<SelectProps, "options">;
+type AccountSelectProps = Omit<SelectProps, "options"> & {
+ classes: AccountClass[];
+};
const Account = ({
name,
@@ -21,6 +23,7 @@ const Account = ({
isLoading,
isReadOnly,
placeholder = "Select Account",
+ classes,
onChange,
...props
}: AccountSelectProps) => {
@@ -31,7 +34,10 @@ const Account = ({
useFetcher<Awaited<ReturnType<typeof getAccountsList>>>();
useMount(() => {
- accountFetcher.load(`${path.to.api.accounts}?type=Posting`);
+ let classQueryParamas = classes?.map((c) => `class=${c}`).join("&") ?? "";
+ accountFetcher.load(
+ `${path.to.api.accounts}?type=Posting&${classQueryParamas}`
+ );
});
const options = useMemo(
diff --git a/apps/carbon/app/modules/accounting/accounting.models.ts b/apps/carbon/app/modules/accounting/accounting.models.ts
index 43ee232882..8ec4f53b56 100644
--- a/apps/carbon/app/modules/accounting/accounting.models.ts
+++ b/apps/carbon/app/modules/accounting/accounting.models.ts
@@ -70,7 +70,13 @@ export const incomeBalanceTypes = [
"Balance Sheet",
"Income Statement",
] as const;
-export const normalBalanceTypes = ["Debit", "Credit", "Both"] as const;
+export const accountClassTypes = [
+ "Asset",
+ "Liability",
+ "Equity",
+ "Revenue",
+ "Expense",
+] as const;
export const accountValidator = withZod(
z
@@ -90,14 +96,38 @@ export const accountValidator = withZod(
message: "Income balance is required",
}),
}),
- normalBalance: z.enum(normalBalanceTypes, {
+ class: z.enum(accountClassTypes, {
errorMap: (issue, ctx) => ({
- message: "Normal balance is required",
+ message: "Class is required",
}),
}),
consolidatedRate: z.enum(consolidatedRateTypes),
directPosting: zfd.checkbox(),
})
+ .refine(
+ (data) => {
+ if (["Asset", "Liability", "Equity"].includes(data.class)) {
+ return data.incomeBalance === "Balance Sheet";
+ }
+ return true;
+ },
+ {
+ message: "Asset, Liability and Equity are Balance Sheet accounts",
+ path: ["class"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (["Revenue", "Expense"].includes(data.class)) {
+ return data.incomeBalance === "Income Statement";
+ }
+ return true;
+ },
+ {
+ message: "Revenue and Expense are Income Statement accounts",
+ path: ["class"],
+ }
+ )
.refine(
(data) => {
if (!["Heading", "Begin Total", "End Total"].includes(data.type)) {
@@ -144,9 +174,9 @@ export const accountCategoryValidator = withZod(
message: "Income balance is required",
}),
}),
- normalBalance: z.enum(normalBalanceTypes, {
+ class: z.enum(accountClassTypes, {
errorMap: (issue, ctx) => ({
- message: "Normal balance is required",
+ message: "Class is required",
}),
}),
})
diff --git a/apps/carbon/app/modules/accounting/accounting.service.ts b/apps/carbon/app/modules/accounting/accounting.service.ts
index feb023d8f5..7166a86a3f 100644
--- a/apps/carbon/app/modules/accounting/accounting.service.ts
+++ b/apps/carbon/app/modules/accounting/accounting.service.ts
@@ -140,6 +140,7 @@ export async function getAccountsList(
args?: {
type?: string | null;
incomeBalance?: string | null;
+ classes?: string[];
}
) {
let query = client.from("account").select("number, name").eq("active", true);
@@ -152,6 +153,10 @@ export async function getAccountsList(
query = query.eq("incomeBalance", args.incomeBalance);
}
+ if (args?.classes) {
+ query = query.in("class", args.classes);
+ }
+
query = query.order("number", { ascending: true });
return query;
}
@@ -160,7 +165,7 @@ export async function getAccountCategories(
client: SupabaseClient<Database>,
args: GenericQueryFilters & {
name: string | null;
- normalBalance: string | null;
+ class: string | null;
incomeBalance: string | null;
}
) {
@@ -172,8 +177,8 @@ export async function getAccountCategories(
query = query.ilike("category", `%${args.name}%`);
}
- if (args.normalBalance) {
- query = query.eq("normalBalance", args.normalBalance);
+ if (args.class) {
+ query = query.eq("class", args.class);
}
if (args.incomeBalance) {
diff --git a/apps/carbon/app/modules/accounting/types.ts b/apps/carbon/app/modules/accounting/types.ts
index 82a71072a5..e55cf0c577 100644
--- a/apps/carbon/app/modules/accounting/types.ts
+++ b/apps/carbon/app/modules/accounting/types.ts
@@ -33,8 +33,7 @@ export type AccountSubcategory = NonNullable<
export type AccountIncomeBalance =
Database["public"]["Enums"]["glIncomeBalance"];
-export type AccountNormalBalance =
- Database["public"]["Enums"]["glNormalBalance"];
+export type AccountClass = Database["public"]["Enums"]["glAccountClass"];
export type AccountType = Database["public"]["Enums"]["glAccountType"];
diff --git a/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx b/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx
index 00792d2611..04c0285e46 100644
--- a/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx
+++ b/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx
@@ -60,8 +60,8 @@ const AccountCategoriesTable = memo(
cell: (item) => item.getValue(),
},
{
- header: "Debit/Credit",
- accessorKey: "normalBalance",
+ header: "Class",
+ accessorKey: "class",
cell: (item) => item.getValue(),
},
diff --git a/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx b/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx
index c25a1d3d96..d78306d73d 100644
--- a/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx
+++ b/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTableFilters/AccountCategoriesTableFilters.tsx
@@ -4,7 +4,7 @@ import { Link } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
import { usePermissions, useUrlParams } from "~/hooks";
-import { incomeBalanceTypes, normalBalanceTypes } from "~/modules/accounting";
+import { accountClassTypes, incomeBalanceTypes } from "~/modules/accounting";
const AttributeCategoriesTableFilters = () => {
const permissions = usePermissions();
@@ -49,19 +49,19 @@ const AttributeCategoriesTableFilters = () => {
<Select
size="sm"
placeholder="Normal Balance"
- value={normalBalanceTypes
- .map((normalBalance) => ({
- value: normalBalance,
- label: normalBalance,
+ value={accountClassTypes
+ .map((accountClass) => ({
+ value: accountClass,
+ label: accountClass,
}))
- .filter((type) => type.value === params.get("normalBalance"))}
+ .filter((type) => type.value === params.get("accountClass"))}
isClearable
- options={normalBalanceTypes.map((normalBalance) => ({
- value: normalBalance,
- label: normalBalance,
+ options={accountClassTypes.map((accountClass) => ({
+ value: accountClass,
+ label: accountClass,
}))}
onChange={(selected) => {
- setParams({ normalBalance: selected?.value });
+ setParams({ accountClass: selected?.value });
}}
/>
</HStack>
diff --git a/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoryForm/AccountCategoryForm.tsx b/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoryForm/AccountCategoryForm.tsx
index 6b34773c45..0a349d5738 100644
--- a/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoryForm/AccountCategoryForm.tsx
+++ b/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoryForm/AccountCategoryForm.tsx
@@ -15,8 +15,8 @@ import { Hidden, Input, Select, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
import {
accountCategoryValidator,
+ accountClassTypes,
incomeBalanceTypes,
- normalBalanceTypes,
} from "~/modules/accounting";
import type { TypeOfValidator } from "~/types/validators";
import { path } from "~/utils/path";
@@ -68,11 +68,11 @@ const AccountCategoryForm = ({
}))}
/>
<Select
- name="normalBalance"
- label="Normal Balance"
- options={normalBalanceTypes.map((normalBalance) => ({
- value: normalBalance,
- label: normalBalance,
+ name="class"
+ label="Class"
+ options={accountClassTypes.map((accountClass) => ({
+ value: accountClass,
+ label: accountClass,
}))}
/>
</VStack>
diff --git a/apps/carbon/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountForm/ChartOfAccountForm.tsx b/apps/carbon/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountForm/ChartOfAccountForm.tsx
index d5bdd2a00d..4008f96423 100644
--- a/apps/carbon/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountForm/ChartOfAccountForm.tsx
+++ b/apps/carbon/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountForm/ChartOfAccountForm.tsx
@@ -28,15 +28,15 @@ import {
import { usePermissions } from "~/hooks";
import type {
AccountCategory as AccountCategoryType,
+ AccountClass,
AccountIncomeBalance,
- AccountNormalBalance,
} from "~/modules/accounting";
import {
+ accountClassTypes,
accountTypes,
accountValidator,
consolidatedRateTypes,
incomeBalanceTypes,
- normalBalanceTypes,
} from "~/modules/accounting";
import type { TypeOfValidator } from "~/types/validators";
import { path } from "~/utils/path";
@@ -53,12 +53,12 @@ const ChartOfAccountForm = ({ initialValues }: ChartOfAccountFormProps) => {
const [accountCategoryId, setAccountCategoryId] = useState<string>(
initialValues.accountCategoryId ?? ""
);
- const [incomeBalance, setIncomeBalance] = useState<
- "Balance Sheet" | "Income Statement"
- >(initialValues.incomeBalance);
- const [normalBalance, setNormalBalance] = useState<
- "Debit" | "Credit" | "Both"
- >(initialValues.normalBalance);
+ const [incomeBalance, setIncomeBalance] = useState<AccountIncomeBalance>(
+ initialValues.incomeBalance
+ );
+ const [accountClass, setAccountClass] = useState<AccountClass>(
+ initialValues.class
+ );
const isEditing = initialValues.id !== undefined;
const isDisabled = isEditing
@@ -69,7 +69,7 @@ const ChartOfAccountForm = ({ initialValues }: ChartOfAccountFormProps) => {
if (category) {
setAccountCategoryId(category.id ?? "");
setIncomeBalance(category.incomeBalance ?? "Income Statement");
- setNormalBalance(category.normalBalance ?? "Debit");
+ setAccountClass(category.class ?? "Asset");
}
};
@@ -139,16 +139,15 @@ const ChartOfAccountForm = ({ initialValues }: ChartOfAccountFormProps) => {
</VStack>
<VStack spacing={4} alignItems="start">
<SelectControlled
- name="normalBalance"
- label="Normal Balance"
- options={normalBalanceTypes.map((normalBalance) => ({
- label: normalBalance,
- value: normalBalance,
+ name="class"
+ label="Class"
+ options={accountClassTypes.map((accountClass) => ({
+ label: accountClass,
+ value: accountClass,
}))}
- value={normalBalance}
+ value={accountClass}
onChange={(newValue) => {
- if (newValue)
- setNormalBalance(newValue as AccountNormalBalance);
+ if (newValue) setAccountClass(newValue as AccountClass);
}}
/>
<Select
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
index d765226e9b..9b92ec28f3 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm/PurchaseOrderLineForm.tsx
@@ -232,6 +232,7 @@ const PurchaseOrderLineForm = ({
<Account
name="accountNumber"
label="Account"
+ classes={["Expense", "Asset"]}
onChange={({ label }) => {
setPartData({
partId: "",
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
index 73699c5855..45dd9ed11b 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLines/PurchaseOrderLines.tsx
@@ -237,6 +237,18 @@ const PurchaseOrderLines = () => {
}
},
},
+ {
+ id: "invoicedComplete",
+ header: "Invoiced Complete",
+ cell: ({ row }) => {
+ switch (row.original.purchaseOrderLineType) {
+ case "Comment":
+ return null;
+ default:
+ return <Checkbox isChecked={row.original.invoicedComplete} />;
+ }
+ },
+ },
];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [navigate]);
diff --git a/apps/carbon/app/routes/api+/accounting.accounts.ts b/apps/carbon/app/routes/api+/accounting.accounts.ts
index d949f66a3d..5f5d800acd 100644
--- a/apps/carbon/app/routes/api+/accounting.accounts.ts
+++ b/apps/carbon/app/routes/api+/accounting.accounts.ts
@@ -9,12 +9,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url);
const searchParams = new URLSearchParams(url.search);
const type = searchParams.get("type");
+ const classes = searchParams.getAll("class");
const incomeBalance = searchParams.get("incomeBalance");
return json(
await getAccountsList(authorized.client, {
type,
incomeBalance,
+ classes,
})
);
}
diff --git a/apps/carbon/app/routes/x+/accounting+/categories.new.tsx b/apps/carbon/app/routes/x+/accounting+/categories.new.tsx
index 92fbe5a3c7..3e7e7d1e55 100644
--- a/apps/carbon/app/routes/x+/accounting+/categories.new.tsx
+++ b/apps/carbon/app/routes/x+/accounting+/categories.new.tsx
@@ -2,10 +2,7 @@ import type { ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { useNavigate } from "@remix-run/react";
import { validationError } from "remix-validated-form";
-import type {
- AccountIncomeBalance,
- AccountNormalBalance,
-} from "~/modules/accounting";
+import type { AccountClass, AccountIncomeBalance } from "~/modules/accounting";
import {
AccountCategoryForm,
accountCategoryValidator,
@@ -60,7 +57,7 @@ export default function NewAccountCategoryRoute() {
const initialValues = {
category: "",
incomeBalance: "" as AccountIncomeBalance,
- normalBalance: "" as AccountNormalBalance,
+ class: "" as AccountClass,
};
return (
diff --git a/apps/carbon/app/routes/x+/accounting+/categories.tsx b/apps/carbon/app/routes/x+/accounting+/categories.tsx
index 3f26d907d8..58afbe3b19 100644
--- a/apps/carbon/app/routes/x+/accounting+/categories.tsx
+++ b/apps/carbon/app/routes/x+/accounting+/categories.tsx
@@ -29,13 +29,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
const searchParams = new URLSearchParams(url.search);
const name = searchParams.get("name");
const incomeBalance = searchParams.get("incomeBalance");
- const normalBalance = searchParams.get("normalBalance");
+ const accountClass = searchParams.get("class");
const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
const [categories] = await Promise.all([
getAccountCategories(client, {
name,
- normalBalance,
+ class: accountClass,
incomeBalance,
limit,
offset,
diff --git a/apps/carbon/app/routes/x+/accounting+/charts.$accountId.tsx b/apps/carbon/app/routes/x+/accounting+/charts.$accountId.tsx
index 0ebff68ce2..bf802a92a5 100644
--- a/apps/carbon/app/routes/x+/accounting+/charts.$accountId.tsx
+++ b/apps/carbon/app/routes/x+/accounting+/charts.$accountId.tsx
@@ -78,7 +78,7 @@ export default function EditChartOfAccountsRoute() {
type: account?.type ?? "Posting",
accountCategoryId: account?.accountCategoryId ?? undefined,
accountSubcategoryId: account?.accountSubcategoryId ?? undefined,
- normalBalance: account?.normalBalance ?? "Debit",
+ class: account?.class ?? "Asset",
incomeBalance: account?.incomeBalance ?? "Balance Sheet",
consolidatedRate: account?.consolidatedRate ?? "Average",
directPosting: account?.directPosting ?? false,
diff --git a/apps/carbon/app/routes/x+/accounting+/charts.new.tsx b/apps/carbon/app/routes/x+/accounting+/charts.new.tsx
index 25bf5c3bce..0f8aeb5ce7 100644
--- a/apps/carbon/app/routes/x+/accounting+/charts.new.tsx
+++ b/apps/carbon/app/routes/x+/accounting+/charts.new.tsx
@@ -2,14 +2,14 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
import type {
+ AccountClass,
AccountConsolidatedRate,
AccountIncomeBalance,
- AccountNormalBalance,
AccountType,
} from "~/modules/accounting";
import {
- accountValidator,
ChartOfAccountForm,
+ accountValidator,
upsertAccount,
} from "~/modules/accounting";
import { requirePermissions } from "~/services/auth";
@@ -74,8 +74,8 @@ export default function NewAccountRoute() {
number: "",
type: "Posting" as AccountType,
accountCategoryId: "",
+ class: "Asset" as AccountClass,
incomeBalance: "Balance Sheet" as AccountIncomeBalance,
- normalBalance: "Debit" as AccountNormalBalance,
consolidatedRate: "Average" as AccountConsolidatedRate,
directPosting: false,
};
diff --git a/packages/database/SCHEMA.md b/packages/database/SCHEMA.md
index b71d0f77eb..cb3a8f7ff1 100644
--- a/packages/database/SCHEMA.md
+++ b/packages/database/SCHEMA.md
@@ -2997,17 +2997,19 @@ CREATE TYPE "glAccountCategory" AS ENUM (
'Other Expense'
);
+CREATE TYPE "glAccountClass" AS ENUM (
+ 'Asset',
+ 'Liability',
+ 'Equity',
+ 'Revenue',
+ 'Expense'
+);
+
CREATE TYPE "glIncomeBalance" AS ENUM (
'Balance Sheet',
'Income Statement'
);
-CREATE TYPE "glNormalBalance" AS ENUM (
- 'Debit',
- 'Credit',
- 'Both'
-);
-
CREATE TYPE "glAccountType" AS ENUM (
'Posting',
'Heading',
@@ -3019,8 +3021,8 @@ CREATE TYPE "glAccountType" AS ENUM (
CREATE TABLE "accountCategory" (
"id" TEXT NOT NULL DEFAULT xid(),
"category" TEXT NOT NULL,
+ "class" "glAccountClass" NOT NULL,
"incomeBalance" "glIncomeBalance" NOT NULL,
- "normalBalance" "glNormalBalance" NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
@@ -3124,10 +3126,10 @@ CREATE TABLE "account" (
"number" TEXT NOT NULL,
"name" TEXT NOT NULL,
"type" "glAccountType" NOT NULL,
+ "class" "glAccountClass",
"accountCategoryId" TEXT,
"accountSubcategoryId" TEXT,
"incomeBalance" "glIncomeBalance" NOT NULL,
- "normalBalance" "glNormalBalance" NOT NULL,
"consolidatedRate" "glConsolidatedRate",
"directPosting" BOOLEAN NOT NULL DEFAULT false,
"active" BOOLEAN NOT NULL DEFAULT true,
@@ -3192,8 +3194,8 @@ CREATE OR REPLACE VIEW "accountCategories" AS
SELECT
"id",
"category",
+ "class",
"incomeBalance",
- "normalBalance",
"createdBy",
"createdAt",
"updatedBy",
@@ -3212,8 +3214,8 @@ CREATE OR REPLACE VIEW "accounts" AS
(SELECT "category" FROM "accountCategory" WHERE "accountCategory"."id" = "account"."accountCategoryId") AS "accountCategory",
"accountSubcategoryId",
(SELECT "name" FROM "accountSubcategory" WHERE "accountSubcategory"."id" = "account"."accountSubcategoryId") AS "accountSubCategory",
+ "class",
"incomeBalance",
- "normalBalance",
"consolidatedRate",
"directPosting",
"active",
@@ -6595,7 +6597,8 @@ CREATE POLICY "Employees with invoicing_view can view AP invoices status history
CREATE TYPE "payableLineType" AS ENUM (
'G/L Account',
'Part',
- 'Fixed Asset'
+ 'Fixed Asset',
+ 'Comment'
);
CREATE TABLE "purchaseInvoiceLine" (
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 762da4ba1d..8f61c23a9d 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -100,6 +100,7 @@ export interface Database {
accountCategoryId: string | null
accountSubcategoryId: string | null
active: boolean
+ class: Database["public"]["Enums"]["glAccountClass"] | null
consolidatedRate:
| Database["public"]["Enums"]["glConsolidatedRate"]
| null
@@ -109,7 +110,6 @@ export interface Database {
id: string
incomeBalance: Database["public"]["Enums"]["glIncomeBalance"]
name: string
- normalBalance: Database["public"]["Enums"]["glNormalBalance"]
number: string
type: Database["public"]["Enums"]["glAccountType"]
updatedAt: string | null
@@ -119,6 +119,7 @@ export interface Database {
accountCategoryId?: string | null
accountSubcategoryId?: string | null
active?: boolean
+ class?: Database["public"]["Enums"]["glAccountClass"] | null
consolidatedRate?:
| Database["public"]["Enums"]["glConsolidatedRate"]
| null
@@ -128,7 +129,6 @@ export interface Database {
id?: string
incomeBalance: Database["public"]["Enums"]["glIncomeBalance"]
name: string
- normalBalance: Database["public"]["Enums"]["glNormalBalance"]
number: string
type: Database["public"]["Enums"]["glAccountType"]
updatedAt?: string | null
@@ -138,6 +138,7 @@ export interface Database {
accountCategoryId?: string | null
accountSubcategoryId?: string | null
active?: boolean
+ class?: Database["public"]["Enums"]["glAccountClass"] | null
consolidatedRate?:
| Database["public"]["Enums"]["glConsolidatedRate"]
| null
@@ -147,7 +148,6 @@ export interface Database {
id?: string
incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"]
name?: string
- normalBalance?: Database["public"]["Enums"]["glNormalBalance"]
number?: string
type?: Database["public"]["Enums"]["glAccountType"]
updatedAt?: string | null
@@ -195,31 +195,31 @@ export interface Database {
accountCategory: {
Row: {
category: string
+ class: Database["public"]["Enums"]["glAccountClass"]
createdAt: string
createdBy: string
id: string
incomeBalance: Database["public"]["Enums"]["glIncomeBalance"]
- normalBalance: Database["public"]["Enums"]["glNormalBalance"]
updatedAt: string | null
updatedBy: string | null
}
Insert: {
category: string
+ class: Database["public"]["Enums"]["glAccountClass"]
createdAt?: string
createdBy: string
id?: string
incomeBalance: Database["public"]["Enums"]["glIncomeBalance"]
- normalBalance: Database["public"]["Enums"]["glNormalBalance"]
updatedAt?: string | null
updatedBy?: string | null
}
Update: {
category?: string
+ class?: Database["public"]["Enums"]["glAccountClass"]
createdAt?: string
createdBy?: string
id?: string
incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"]
- normalBalance?: Database["public"]["Enums"]["glNormalBalance"]
updatedAt?: string | null
updatedBy?: string | null
}
@@ -7901,33 +7901,33 @@ export interface Database {
accountCategories: {
Row: {
category: string | null
+ class: Database["public"]["Enums"]["glAccountClass"] | null
createdAt: string | null
createdBy: string | null
id: string | null
incomeBalance: Database["public"]["Enums"]["glIncomeBalance"] | null
- normalBalance: Database["public"]["Enums"]["glNormalBalance"] | null
subCategoriesCount: number | null
updatedAt: string | null
updatedBy: string | null
}
Insert: {
category?: string | null
+ class?: Database["public"]["Enums"]["glAccountClass"] | null
createdAt?: string | null
createdBy?: string | null
id?: string | null
incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"] | null
- normalBalance?: Database["public"]["Enums"]["glNormalBalance"] | null
subCategoriesCount?: never
updatedAt?: string | null
updatedBy?: string | null
}
Update: {
category?: string | null
+ class?: Database["public"]["Enums"]["glAccountClass"] | null
createdAt?: string | null
createdBy?: string | null
id?: string | null
incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"] | null
- normalBalance?: Database["public"]["Enums"]["glNormalBalance"] | null
subCategoriesCount?: never
updatedAt?: string | null
updatedBy?: string | null
@@ -7966,6 +7966,7 @@ export interface Database {
accountSubCategory: string | null
accountSubcategoryId: string | null
active: boolean | null
+ class: Database["public"]["Enums"]["glAccountClass"] | null
consolidatedRate:
| Database["public"]["Enums"]["glConsolidatedRate"]
| null
@@ -7975,7 +7976,6 @@ export interface Database {
id: string | null
incomeBalance: Database["public"]["Enums"]["glIncomeBalance"] | null
name: string | null
- normalBalance: Database["public"]["Enums"]["glNormalBalance"] | null
number: string | null
type: Database["public"]["Enums"]["glAccountType"] | null
updatedAt: string | null
@@ -7987,6 +7987,7 @@ export interface Database {
accountSubCategory?: never
accountSubcategoryId?: string | null
active?: boolean | null
+ class?: Database["public"]["Enums"]["glAccountClass"] | null
consolidatedRate?:
| Database["public"]["Enums"]["glConsolidatedRate"]
| null
@@ -7996,7 +7997,6 @@ export interface Database {
id?: string | null
incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"] | null
name?: string | null
- normalBalance?: Database["public"]["Enums"]["glNormalBalance"] | null
number?: string | null
type?: Database["public"]["Enums"]["glAccountType"] | null
updatedAt?: string | null
@@ -8008,6 +8008,7 @@ export interface Database {
accountSubCategory?: never
accountSubcategoryId?: string | null
active?: boolean | null
+ class?: Database["public"]["Enums"]["glAccountClass"] | null
consolidatedRate?:
| Database["public"]["Enums"]["glConsolidatedRate"]
| null
@@ -8017,7 +8018,6 @@ export interface Database {
id?: string | null
incomeBalance?: Database["public"]["Enums"]["glIncomeBalance"] | null
name?: string | null
- normalBalance?: Database["public"]["Enums"]["glNormalBalance"] | null
number?: string | null
type?: Database["public"]["Enums"]["glAccountType"] | null
updatedAt?: string | null
@@ -8852,10 +8852,10 @@ export interface Database {
| "Expense"
| "Other Income"
| "Other Expense"
+ glAccountClass: "Asset" | "Liability" | "Equity" | "Revenue" | "Expense"
glAccountType: "Posting" | "Heading" | "Begin Total" | "End Total"
glConsolidatedRate: "Average" | "Current" | "Historical"
glIncomeBalance: "Balance Sheet" | "Income Statement"
- glNormalBalance: "Debit" | "Credit" | "Both"
journalLineDocumentType:
| "Receipt"
| "Invoice"
@@ -8912,7 +8912,7 @@ export interface Database {
| "Maximum Quantity"
partReplenishmentSystem: "Buy" | "Make" | "Buy and Make"
partType: "Inventory" | "Non-Inventory" | "Service"
- payableLineType: "G/L Account" | "Part" | "Fixed Asset"
+ payableLineType: "G/L Account" | "Part" | "Fixed Asset" | "Comment"
paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"
purchaseInvoiceStatus:
| "Draft"
diff --git a/packages/database/supabase/functions/create-purchase-invoice-from-purchase-order/index.ts b/packages/database/supabase/functions/create-purchase-invoice-from-purchase-order/index.ts
index 155ac0525e..94311779cc 100644
--- a/packages/database/supabase/functions/create-purchase-invoice-from-purchase-order/index.ts
+++ b/packages/database/supabase/functions/create-purchase-invoice-from-purchase-order/index.ts
@@ -104,9 +104,9 @@ serve(async (req: Request) => {
Database["public"]["Tables"]["purchaseInvoiceLine"]["Insert"][]
>((acc, line) => {
if (
- line.purchaseOrderLineType !== "Comment" &&
line?.quantityToInvoice &&
- line.quantityToInvoice > 0
+ line.quantityToInvoice > 0 &&
+ !line.invoicedComplete
) {
acc.push({
invoiceId: purchaseInvoiceId,
diff --git a/packages/database/supabase/functions/create-purchase-invoice-from-receipt/index.ts b/packages/database/supabase/functions/create-purchase-invoice-from-receipt/index.ts
deleted file mode 100644
index ea29803b86..0000000000
--- a/packages/database/supabase/functions/create-purchase-invoice-from-receipt/index.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
-
-import { corsHeaders } from "../lib/headers.ts";
-import { getSupabaseServiceRole } from "../lib/supabase.ts";
-
-const pool = getConnectionPool(1);
-const db = getDatabaseClient<DB>(pool);
-
-serve(async (req: Request) => {
- if (req.method === "OPTIONS") {
- return new Response("ok", { headers: corsHeaders });
- }
- const { id } = await req.json();
-
- try {
- if (!id) throw new Error("Payload is missing id");
-
- const client = getSupabaseServiceRole(req.headers.get("Authorization"));
- await db.transaction().execute(async (trx) => {});
-
- return new Response(
- JSON.stringify({
- id: "abc",
- }),
- {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- }
- );
- } catch (err) {
- console.error(err);
- return new Response(JSON.stringify(err), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 500,
- });
- }
-});
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index dbc3aaab70..c4e5ca8fb7 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -1,3 +1,4 @@
+// deno-lint-ignore-file no-case-declarations
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { format } from "https://deno.land/[email protected]/datetime/mod.ts";
import type { Database } from "../../../src/types.ts";
@@ -196,309 +197,434 @@ serve(async (req: Request) => {
> = {};
for await (const invoiceLine of purchaseInvoiceLines.data) {
- let postingGroupInventory:
- | Database["public"]["Tables"]["postingGroupInventory"]["Row"]
- | null = null;
-
- const partGroupId: string | null =
- partGroups.data.find((partGroup) => partGroup.id === invoiceLine.partId)
- ?.partGroupId ?? null;
- const locationId = invoiceLine.locationId ?? null;
- const supplierTypeId: string | null =
- supplier.data.supplierTypeId ?? null;
-
- // inventory posting group
- if (`${partGroupId}-${locationId}` in inventoryPostingGroups) {
- postingGroupInventory =
- inventoryPostingGroups[`${partGroupId}-${locationId}`];
- } else {
- const inventoryPostingGroup = await getInventoryPostingGroup(client, {
- partGroupId,
- locationId,
- });
-
- if (inventoryPostingGroup.error || !inventoryPostingGroup.data) {
- throw new Error("Error getting inventory posting group");
- }
-
- postingGroupInventory = inventoryPostingGroup.data ?? null;
- inventoryPostingGroups[`${partGroupId}-${locationId}`] =
- postingGroupInventory;
- }
-
- if (!postingGroupInventory) {
- throw new Error("No inventory posting group found");
- }
-
- // purchasing posting group
- const purchasingPostingGroups: Record<
- string,
- Database["public"]["Tables"]["postingGroupPurchasing"]["Row"] | null
- > = {};
-
- let postingGroupPurchasing:
- | Database["public"]["Tables"]["postingGroupPurchasing"]["Row"]
- | null = null;
-
- if (`${partGroupId}-${supplierTypeId}` in purchasingPostingGroups) {
- postingGroupPurchasing =
- purchasingPostingGroups[`${partGroupId}-${supplierTypeId}`];
- } else {
- const purchasingPostingGroup = await getPurchasingPostingGroup(client, {
- partGroupId,
- supplierTypeId,
- });
-
- if (purchasingPostingGroup.error || !purchasingPostingGroup.data) {
- throw new Error("Error getting purchasing posting group");
- }
-
- postingGroupPurchasing = purchasingPostingGroup.data ?? null;
- purchasingPostingGroups[`${partGroupId}-${supplierTypeId}`] =
- postingGroupPurchasing;
- }
-
- if (!postingGroupPurchasing) {
- throw new Error("No purchasing posting group found");
- }
-
- // determine the journal lines that should be reversed
- const existingJournalLines = invoiceLine.purchaseOrderLineId
- ? journalLinesByPurchaseOrderLine[invoiceLine.purchaseOrderLineId] ?? []
- : [];
-
- let previousJournalId: number | null = null;
- let previousAccrual: boolean | null = null;
- let currentGroup = 0;
-
- const existingJournalLineGroups = existingJournalLines.reduce<
- Database["public"]["Tables"]["journalLine"]["Row"][][]
- >((acc, entry) => {
- const { journalId, accrual } = entry;
-
- if (journalId === previousJournalId && accrual === previousAccrual) {
- acc[currentGroup - 1].push(entry);
- } else {
- acc.push([entry]);
- currentGroup++;
- }
+ switch (invoiceLine.invoiceLineType) {
+ case "G/L Account":
+ const [account, accountDefaults] = await Promise.all([
+ client
+ .from("accounts")
+ .select("name, number, directPosting")
+ .eq("number", invoiceLine.accountNumber ?? "")
+ .single(),
+ client
+ .from("accountDefault")
+ .select(
+ "overheadCostAppliedAccount, payablesAccount, purchaseAccount"
+ )
+ .single(),
+ ]);
+ if (account.error || !account.data)
+ throw new Error("Failed to fetch account");
+ if (!account.data.directPosting)
+ throw new Error("Account is not a direct posting account");
+
+ if (accountDefaults.error || !accountDefaults.data)
+ throw new Error("Failed to fetch account defaults");
+
+ // debit the G/L account
+ journalLineInserts.push({
+ accountNumber: account.data.number!,
+ description: account.data.name!,
+ // we limit the account to assets and expenses in the UI, so we don't need to check here
+ amount: debit(
+ "asset",
+ invoiceLine.quantity * invoiceLine.unitPrice
+ ),
+ quantity: invoiceLine.quantity,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId!
+ ),
+ });
+
+ // creidt the direct cost applied account
+ journalLineInserts.push({
+ accountNumber: accountDefaults.data.overheadCostAppliedAccount!,
+ description: "Overhead Cost Applied",
+ amount: credit(
+ "expense",
+ invoiceLine.quantity * invoiceLine.unitPrice
+ ),
+ quantity: invoiceLine.quantity,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId!
+ ),
+ });
+
+ // debit the purchase account
+ journalLineInserts.push({
+ accountNumber: accountDefaults.data.purchaseAccount!,
+ description: "Purchase Account",
+ amount: debit(
+ "expense",
+ invoiceLine.quantity * invoiceLine.unitPrice
+ ),
+ quantity: invoiceLine.quantity,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId!
+ ),
+ });
+
+ // credit the accounts payable account
+ journalLineInserts.push({
+ accountNumber: accountDefaults.data.payablesAccount!,
+ description: "Accounts Payable",
+ amount: credit(
+ "liability",
+ invoiceLine.quantity * invoiceLine.unitPrice
+ ),
+ quantity: invoiceLine.quantity,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId!
+ ),
+ });
+ break;
+ case "Part":
+ let postingGroupInventory:
+ | Database["public"]["Tables"]["postingGroupInventory"]["Row"]
+ | null = null;
+
+ const partGroupId: string | null =
+ partGroups.data.find(
+ (partGroup) => partGroup.id === invoiceLine.partId
+ )?.partGroupId ?? null;
+ const locationId = invoiceLine.locationId ?? null;
+ const supplierTypeId: string | null =
+ supplier.data.supplierTypeId ?? null;
+
+ // inventory posting group
+ if (`${partGroupId}-${locationId}` in inventoryPostingGroups) {
+ postingGroupInventory =
+ inventoryPostingGroups[`${partGroupId}-${locationId}`];
+ } else {
+ const inventoryPostingGroup = await getInventoryPostingGroup(
+ client,
+ {
+ partGroupId,
+ locationId,
+ }
+ );
- previousJournalId = journalId;
- previousAccrual = accrual;
- return acc;
- }, []);
+ if (inventoryPostingGroup.error || !inventoryPostingGroup.data) {
+ throw new Error("Error getting inventory posting group");
+ }
- const purchaseOrderLine = purchaseOrderLines.data.find(
- (line) => line.id === invoiceLine.purchaseOrderLineId
- );
+ postingGroupInventory = inventoryPostingGroup.data ?? null;
+ inventoryPostingGroups[`${partGroupId}-${locationId}`] =
+ postingGroupInventory;
+ }
- const quantityReceived = purchaseOrderLine?.quantityReceived ?? 0;
- const quantityInvoiced = purchaseOrderLine?.quantityInvoiced ?? 0;
- const quantityToReverse = Math.max(
- 0,
- Math.min(invoiceLine.quantity ?? 0, quantityReceived - quantityInvoiced)
- );
+ if (!postingGroupInventory) {
+ throw new Error("No inventory posting group found");
+ }
- const quantityAlreadyReversed =
- quantityReceived > quantityInvoiced ? quantityInvoiced : 0;
+ // purchasing posting group
+ const purchasingPostingGroups: Record<
+ string,
+ Database["public"]["Tables"]["postingGroupPurchasing"]["Row"] | null
+ > = {};
+
+ let postingGroupPurchasing:
+ | Database["public"]["Tables"]["postingGroupPurchasing"]["Row"]
+ | null = null;
+
+ if (`${partGroupId}-${supplierTypeId}` in purchasingPostingGroups) {
+ postingGroupPurchasing =
+ purchasingPostingGroups[`${partGroupId}-${supplierTypeId}`];
+ } else {
+ const purchasingPostingGroup = await getPurchasingPostingGroup(
+ client,
+ {
+ partGroupId,
+ supplierTypeId,
+ }
+ );
- if (quantityToReverse > 0) {
- let counted = 0;
- let reversed = 0;
+ if (purchasingPostingGroup.error || !purchasingPostingGroup.data) {
+ throw new Error("Error getting purchasing posting group");
+ }
- existingJournalLineGroups.forEach((entry) => {
- if (entry[0].quantity) {
- const unitCostForEntry = (entry[0].amount ?? 0) / entry[0].quantity;
+ postingGroupPurchasing = purchasingPostingGroup.data ?? null;
+ purchasingPostingGroups[`${partGroupId}-${supplierTypeId}`] =
+ postingGroupPurchasing;
+ }
- // we don't want to reverse an entry twice, so we need to keep track of what's been previously reversed
+ if (!postingGroupPurchasing) {
+ throw new Error("No purchasing posting group found");
+ }
- // akin to supply
- const quantityAvailableToReverseForEntry =
- quantityAlreadyReversed > counted
- ? entry[0].quantity + counted - quantityAlreadyReversed
- : entry[0].quantity;
+ // determine the journal lines that should be reversed
+ const existingJournalLines = invoiceLine.purchaseOrderLineId
+ ? journalLinesByPurchaseOrderLine[
+ invoiceLine.purchaseOrderLineId
+ ] ?? []
+ : [];
- // akin to demand
- const quantityRequiredToReverse = quantityToReverse - reversed;
+ let previousJournalId: number | null = null;
+ let previousAccrual: boolean | null = null;
+ let currentGroup = 0;
- // we can't reverse more than what's available or what's required
- const quantityToReverseForEntry = Math.max(
- 0,
- Math.min(
- quantityAvailableToReverseForEntry,
- quantityRequiredToReverse
- )
- );
+ const existingJournalLineGroups = existingJournalLines.reduce<
+ Database["public"]["Tables"]["journalLine"]["Row"][][]
+ >((acc, entry) => {
+ const { journalId, accrual } = entry;
- if (quantityToReverseForEntry > 0) {
- // create the reversal entries
- journalLineInserts.push({
- accountNumber: entry[0].accountNumber!,
- description: entry[0].description,
- amount:
- entry[0].description === "Interim Inventory Accrual"
- ? credit(
- "asset",
- quantityToReverseForEntry * unitCostForEntry
- )
- : debit(
- "liability",
- quantityToReverseForEntry * unitCostForEntry
- ),
- quantity: quantityToReverseForEntry,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice?.data.supplierReference,
- reference: invoiceLine.purchaseOrderLineId
- ? journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId
- )
- : null,
- });
-
- journalLineInserts.push({
- accountNumber: entry[1].accountNumber!,
- description: entry[1].description,
- amount:
- entry[1].description === "Interim Inventory Accrual"
- ? credit(
- "asset",
- quantityToReverseForEntry * unitCostForEntry
- )
- : debit(
- "liability",
- quantityToReverseForEntry * unitCostForEntry
- ),
- quantity: quantityToReverseForEntry,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice?.data.supplierReference,
- reference: journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId!
- ),
- });
+ if (
+ journalId === previousJournalId &&
+ accrual === previousAccrual
+ ) {
+ acc[currentGroup - 1].push(entry);
+ } else {
+ acc.push([entry]);
+ currentGroup++;
}
- counted += entry[0].quantity;
- reversed += quantityToReverseForEntry;
+ previousJournalId = journalId;
+ previousAccrual = accrual;
+ return acc;
+ }, []);
+
+ const purchaseOrderLine = purchaseOrderLines.data.find(
+ (line) => line.id === invoiceLine.purchaseOrderLineId
+ );
+
+ const quantityReceived = purchaseOrderLine?.quantityReceived ?? 0;
+ const quantityInvoiced = purchaseOrderLine?.quantityInvoiced ?? 0;
+ const quantityToReverse = Math.max(
+ 0,
+ Math.min(
+ invoiceLine.quantity ?? 0,
+ quantityReceived - quantityInvoiced
+ )
+ );
+
+ const quantityAlreadyReversed =
+ quantityReceived > quantityInvoiced ? quantityInvoiced : 0;
+
+ if (quantityToReverse > 0) {
+ let counted = 0;
+ let reversed = 0;
+
+ existingJournalLineGroups.forEach((entry) => {
+ if (entry[0].quantity) {
+ const unitCostForEntry =
+ (entry[0].amount ?? 0) / entry[0].quantity;
+
+ // we don't want to reverse an entry twice, so we need to keep track of what's been previously reversed
+
+ // akin to supply
+ const quantityAvailableToReverseForEntry =
+ quantityAlreadyReversed > counted
+ ? entry[0].quantity + counted - quantityAlreadyReversed
+ : entry[0].quantity;
+
+ // akin to demand
+ const quantityRequiredToReverse = quantityToReverse - reversed;
+
+ // we can't reverse more than what's available or what's required
+ const quantityToReverseForEntry = Math.max(
+ 0,
+ Math.min(
+ quantityAvailableToReverseForEntry,
+ quantityRequiredToReverse
+ )
+ );
+
+ if (quantityToReverseForEntry > 0) {
+ // create the reversal entries
+ journalLineInserts.push({
+ accountNumber: entry[0].accountNumber!,
+ description: entry[0].description,
+ amount:
+ entry[0].description === "Interim Inventory Accrual"
+ ? credit(
+ "asset",
+ quantityToReverseForEntry * unitCostForEntry
+ )
+ : debit(
+ "liability",
+ quantityToReverseForEntry * unitCostForEntry
+ ),
+ quantity: quantityToReverseForEntry,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice?.data.supplierReference,
+ reference: invoiceLine.purchaseOrderLineId
+ ? journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId
+ )
+ : null,
+ });
+
+ journalLineInserts.push({
+ accountNumber: entry[1].accountNumber!,
+ description: entry[1].description,
+ amount:
+ entry[1].description === "Interim Inventory Accrual"
+ ? credit(
+ "asset",
+ quantityToReverseForEntry * unitCostForEntry
+ )
+ : debit(
+ "liability",
+ quantityToReverseForEntry * unitCostForEntry
+ ),
+ quantity: quantityToReverseForEntry,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice?.data.supplierReference,
+ reference: journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId!
+ ),
+ });
+ }
+
+ counted += entry[0].quantity;
+ reversed += quantityToReverseForEntry;
+ }
+ });
+
+ // create the cost entry
+ costLedgerInserts.push({
+ partLedgerType: "Purchase",
+ costLedgerType: "Direct Cost",
+ adjustment: false,
+ documentType: "Purchase Invoice",
+ documentId: purchaseInvoice.data?.id ?? undefined,
+ externalDocumentId:
+ purchaseInvoice.data?.supplierReference ?? undefined,
+ partId: invoiceLine.partId,
+ quantity: quantityToReverse,
+ cost: quantityToReverse * invoiceLine.unitPrice,
+ costPostedToGL: quantityToReverse * invoiceLine.unitPrice,
+ });
+
+ // create the normal GL entries
+
+ // debit the inventory account
+ journalLineInserts.push({
+ accountNumber: postingGroupInventory.inventoryAccount,
+ description: "Inventory Account",
+ amount: debit("asset", quantityToReverse * invoiceLine.unitPrice),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId!
+ ),
+ });
+
+ // creidt the direct cost applied account
+ journalLineInserts.push({
+ accountNumber: postingGroupInventory.directCostAppliedAccount,
+ description: "Direct Cost Applied",
+ amount: credit(
+ "expense",
+ quantityToReverse * invoiceLine.unitPrice
+ ),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId!
+ ),
+ });
+
+ // debit the purchase account
+ journalLineInserts.push({
+ accountNumber: postingGroupPurchasing.purchaseAccount,
+ description: "Purchase Account",
+ amount: debit(
+ "expense",
+ quantityToReverse * invoiceLine.unitPrice
+ ),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId!
+ ),
+ });
+
+ // credit the accounts payable account
+ journalLineInserts.push({
+ accountNumber: postingGroupPurchasing.payablesAccount,
+ description: "Accounts Payable",
+ amount: credit(
+ "liability",
+ quantityToReverse * invoiceLine.unitPrice
+ ),
+ quantity: quantityToReverse,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId!
+ ),
+ });
}
- });
-
- // create the cost entry
- costLedgerInserts.push({
- partLedgerType: "Purchase",
- costLedgerType: "Direct Cost",
- adjustment: false,
- documentType: "Purchase Invoice",
- documentId: purchaseInvoice.data?.id ?? undefined,
- externalDocumentId:
- purchaseInvoice.data?.supplierReference ?? undefined,
- partId: invoiceLine.partId,
- quantity: quantityToReverse,
- cost: quantityToReverse * invoiceLine.unitPrice,
- costPostedToGL: quantityToReverse * invoiceLine.unitPrice,
- });
-
- // create the normal GL entries
-
- // debit the inventory account
- journalLineInserts.push({
- accountNumber: postingGroupInventory.inventoryAccount,
- description: "Inventory Account",
- amount: debit("asset", quantityToReverse * invoiceLine.unitPrice),
- quantity: quantityToReverse,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice.data?.supplierReference,
- reference: journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId!
- ),
- });
-
- // creidt the direct cost applied account
- journalLineInserts.push({
- accountNumber: postingGroupInventory.directCostAppliedAccount,
- description: "Direct Cost Applied",
- amount: credit("expense", quantityToReverse * invoiceLine.unitPrice),
- quantity: quantityToReverse,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice.data?.supplierReference,
- reference: journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId!
- ),
- });
-
- // debit the purchase account
- journalLineInserts.push({
- accountNumber: postingGroupPurchasing.purchaseAccount,
- description: "Purchase Account",
- amount: debit("expense", quantityToReverse * invoiceLine.unitPrice),
- quantity: quantityToReverse,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice.data?.supplierReference,
- reference: journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId!
- ),
- });
-
- // credit the accounts payable account
- journalLineInserts.push({
- accountNumber: postingGroupPurchasing.payablesAccount,
- description: "Accounts Payable",
- amount: credit(
- "liability",
- quantityToReverse * invoiceLine.unitPrice
- ),
- quantity: quantityToReverse,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice.data?.supplierReference,
- reference: journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId!
- ),
- });
- }
- if (invoiceLine.quantity > quantityToReverse) {
- // create the accrual entries for invoiced not received
- const quantityToAccrue = invoiceLine.quantity - quantityToReverse;
-
- // debit the inventory invoiced not received account
- journalLineInserts.push({
- accountNumber:
- postingGroupInventory.inventoryInvoicedNotReceivedAccount,
- description: "Inventory Invoiced Not Received",
- accrual: true,
- amount: debit("asset", quantityToAccrue * invoiceLine.unitPrice),
- quantity: quantityToAccrue,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice.data?.supplierReference,
- reference: invoiceLine.purchaseOrderLineId
- ? journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId
- )
- : null,
- });
-
- // credit the inventory interim accrual account
- journalLineInserts.push({
- accountNumber: postingGroupInventory.inventoryInterimAccrualAccount,
- accrual: true,
- description: "Interim Inventory Accrual",
- amount: credit("asset", quantityToAccrue * invoiceLine.unitPrice),
- quantity: quantityToAccrue,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice.data?.supplierReference,
- reference: invoiceLine.purchaseOrderLineId
- ? journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId
- )
- : null,
- });
+ if (invoiceLine.quantity > quantityToReverse) {
+ // create the accrual entries for invoiced not received
+ const quantityToAccrue = invoiceLine.quantity - quantityToReverse;
+
+ // debit the inventory invoiced not received account
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.inventoryInvoicedNotReceivedAccount,
+ description: "Inventory Invoiced Not Received",
+ accrual: true,
+ amount: debit("asset", quantityToAccrue * invoiceLine.unitPrice),
+ quantity: quantityToAccrue,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: invoiceLine.purchaseOrderLineId
+ ? journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId
+ )
+ : null,
+ });
+
+ // credit the inventory interim accrual account
+ journalLineInserts.push({
+ accountNumber:
+ postingGroupInventory.inventoryInterimAccrualAccount,
+ accrual: true,
+ description: "Interim Inventory Accrual",
+ amount: credit("asset", quantityToAccrue * invoiceLine.unitPrice),
+ quantity: quantityToAccrue,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ reference: invoiceLine.purchaseOrderLineId
+ ? journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId
+ )
+ : null,
+ });
+ }
+ break;
+ case "Fixed Asset":
+ // TODO: fixed assets
+ break;
+ case "Comment":
+ break;
+ default:
+ throw new Error("Unsupported invoice line type");
}
}
diff --git a/packages/database/supabase/migrations/20230330024715_accounts.sql b/packages/database/supabase/migrations/20230330024715_accounts.sql
index af51919ddb..98df2a9e88 100644
--- a/packages/database/supabase/migrations/20230330024715_accounts.sql
+++ b/packages/database/supabase/migrations/20230330024715_accounts.sql
@@ -70,17 +70,19 @@ CREATE TYPE "glAccountCategory" AS ENUM (
'Other Expense'
);
+CREATE TYPE "glAccountClass" AS ENUM (
+ 'Asset',
+ 'Liability',
+ 'Equity',
+ 'Revenue',
+ 'Expense'
+);
+
CREATE TYPE "glIncomeBalance" AS ENUM (
'Balance Sheet',
'Income Statement'
);
-CREATE TYPE "glNormalBalance" AS ENUM (
- 'Debit',
- 'Credit',
- 'Both'
-);
-
CREATE TYPE "glAccountType" AS ENUM (
'Posting',
'Heading',
@@ -92,8 +94,8 @@ CREATE TYPE "glAccountType" AS ENUM (
CREATE TABLE "accountCategory" (
"id" TEXT NOT NULL DEFAULT xid(),
"category" TEXT NOT NULL,
+ "class" "glAccountClass" NOT NULL,
"incomeBalance" "glIncomeBalance" NOT NULL,
- "normalBalance" "glNormalBalance" NOT NULL,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
"updatedBy" TEXT,
@@ -197,10 +199,10 @@ CREATE TABLE "account" (
"number" TEXT NOT NULL,
"name" TEXT NOT NULL,
"type" "glAccountType" NOT NULL,
+ "class" "glAccountClass",
"accountCategoryId" TEXT,
"accountSubcategoryId" TEXT,
"incomeBalance" "glIncomeBalance" NOT NULL,
- "normalBalance" "glNormalBalance" NOT NULL,
"consolidatedRate" "glConsolidatedRate",
"directPosting" BOOLEAN NOT NULL DEFAULT false,
"active" BOOLEAN NOT NULL DEFAULT true,
@@ -265,8 +267,8 @@ CREATE OR REPLACE VIEW "accountCategories" AS
SELECT
"id",
"category",
+ "class",
"incomeBalance",
- "normalBalance",
"createdBy",
"createdAt",
"updatedBy",
@@ -285,8 +287,8 @@ CREATE OR REPLACE VIEW "accounts" AS
(SELECT "category" FROM "accountCategory" WHERE "accountCategory"."id" = "account"."accountCategoryId") AS "accountCategory",
"accountSubcategoryId",
(SELECT "name" FROM "accountSubcategory" WHERE "accountSubcategory"."id" = "account"."accountSubcategoryId") AS "accountSubCategory",
+ "class",
"incomeBalance",
- "normalBalance",
"consolidatedRate",
"directPosting",
"active",
diff --git a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql b/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
index 25ea3a5f51..0e3726f27a 100644
--- a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
+++ b/packages/database/supabase/migrations/20230924004608_accounts-payable.sql
@@ -110,7 +110,8 @@ CREATE POLICY "Employees with invoicing_view can view AP invoices status history
CREATE TYPE "payableLineType" AS ENUM (
'G/L Account',
'Part',
- 'Fixed Asset'
+ 'Fixed Asset',
+ 'Comment'
);
CREATE TABLE "purchaseInvoiceLine" (
diff --git a/packages/database/supabase/seed.sql b/packages/database/supabase/seed.sql
index 011207be05..ca2371fc45 100644
--- a/packages/database/supabase/seed.sql
+++ b/packages/database/supabase/seed.sql
@@ -60,96 +60,96 @@ VALUES
-- account categories
-INSERT INTO public."accountCategory" (id, category, "incomeBalance", "normalBalance", "createdBy")
+INSERT INTO public."accountCategory" (id, category, class, "incomeBalance", "createdBy")
VALUES
- ('cjgo71si60lg1aoj5p40', 'Bank', 'Balance Sheet', 'Credit', 'system'),
- ('cjgo71si60lg1aoj5p4g', 'Accounts Receivable', 'Balance Sheet', 'Credit', 'system'),
- ('cjgo71si60lg1aoj5p50', 'Inventory', 'Balance Sheet', 'Debit', 'system'),
- ('cjgo71si60lg1aoj5p5g', 'Other Current Asset', 'Balance Sheet', 'Debit', 'system'),
- ('cjgo71si60lg1aoj5p60', 'Fixed Asset', 'Balance Sheet', 'Debit', 'system'),
- ('cjgo71si60lg1aoj5p6g', 'Accumulated Depreciation', 'Balance Sheet', 'Credit', 'system'),
- ('cjgo71si60lg1aoj5p70', 'Other Asset', 'Balance Sheet', 'Debit', 'system'),
- ('cjgo71si60lg1aoj5p7g', 'Accounts Payable', 'Balance Sheet', 'Debit', 'system'),
- ('cjgo71si60lg1aoj5p80', 'Other Current Liability', 'Balance Sheet', 'Debit', 'system'),
- ('cjgo71si60lg1aoj5p8g', 'Long Term Liability', 'Balance Sheet', 'Debit', 'system'),
- ('cjgo71si60lg1aoj5p90', 'Equity - No Close', 'Balance Sheet', 'Credit', 'system'),
- ('cjgo71si60lg1aoj5p9g', 'Equity - Close', 'Balance Sheet', 'Credit', 'system'),
- ('cjgo71si60lg1aoj5pa0', 'Retained Earnings', 'Balance Sheet', 'Credit', 'system'),
- ('cjgo71si60lg1aoj5pag', 'Income', 'Income Statement', 'Credit', 'system'),
- ('cjgo71si60lg1aoj5pb0', 'Cost of Goods Sold', 'Income Statement', 'Debit', 'system'),
- ('cjgo71si60lg1aoj5pbg', 'Expense', 'Income Statement', 'Debit', 'system'),
- ('cjgo71si60lg1aoj5pc0', 'Other Income', 'Income Statement', 'Credit', 'system'),
- ('cjgo71si60lg1aoj5pcg', 'Other Expense', 'Income Statement', 'Debit', 'system');
+ ('cjgo71si60lg1aoj5p40', 'Bank', 'Asset', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p4g', 'Accounts Receivable', 'Asset', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p50', 'Inventory', 'Asset', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p5g', 'Other Current Asset', 'Asset', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p60', 'Fixed Asset', 'Asset', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p6g', 'Accumulated Depreciation', 'Asset', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p70', 'Other Asset', 'Asset', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p7g', 'Accounts Payable', 'Liability', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p80', 'Other Current Liability', 'Liability', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p8g', 'Long Term Liability', 'Liability', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p90', 'Equity - No Close', 'Equity', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5p9g', 'Equity - Close', 'Equity', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5pa0', 'Retained Earnings', 'Equity', 'Balance Sheet', 'system'),
+ ('cjgo71si60lg1aoj5pag', 'Income', 'Revenue', 'Income Statement', 'system'),
+ ('cjgo71si60lg1aoj5pb0', 'Cost of Goods Sold', 'Expense', 'Income Statement', 'system'),
+ ('cjgo71si60lg1aoj5pbg', 'Expense', 'Expense', 'Income Statement', 'system'),
+ ('cjgo71si60lg1aoj5pc0', 'Other Income', 'Expense', 'Income Statement', 'system'),
+ ('cjgo71si60lg1aoj5pcg', 'Other Expense', 'Expense', 'Income Statement', 'system');
-- accounts
INSERT INTO public.account
- (number, name, type, "accountCategoryId", "accountSubcategoryId", "incomeBalance", "normalBalance", "consolidatedRate", "directPosting", active, "createdBy")
+ (number, name, type, "accountCategoryId", "accountSubcategoryId", "incomeBalance", "class", "consolidatedRate", "directPosting", active, "createdBy")
VALUES
- ('10000', 'Income Statement', 'Begin Total', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Both', 'Average', false, true, 'system'),
- ('11000', 'Revenue', 'Begin Total', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Credit', 'Average', false, true, 'system'),
- ('11210', 'Sales', 'Posting', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Credit', 'Average', true, true, 'system'),
- ('11600', 'Sales Discounts', 'Posting', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('19999', 'Revenue, Total', 'End Total', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Credit', 'Average', false, true, 'system'),
- ('20000', 'Costs of Goods Sold', 'Begin Total', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Debit', 'Average', false, true, 'system'),
- ('21210', 'Cost of Goods Sold', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('21410', 'Purchases', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('21590', 'Direct Cost Applied', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('21600', 'Overhead Applied', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('21610', 'Purchase Variance', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('21700', 'Inventory Adjustment', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('24999', 'Costs of Goods Sold, Total', 'End Total', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Debit', 'Average', false, true, 'system'),
- ('25000', 'Direct Capacity Cost', 'Begin Total', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Debit', 'Average', false, true, 'system'),
- ('25705', 'Material Variance', 'Posting', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('25710', 'Capacity Variance', 'Posting', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('25720', 'Overhead Accounts', 'Posting', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('47045', 'Maintenance Expense', 'Posting', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('49999', 'Direct Capacity Cost, Total', 'End Total', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('50000', 'Depreciation of Fixed Assets', 'Begin Total', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', false, true, 'system'),
- ('50015', 'Depreciation Expense', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('50040', 'Gains and Losses on Disposal', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('50045', 'Service Charge Account', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('50999', 'Depreciation of Fixed Assets, Total', 'End Total', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', false, true, 'system'),
- ('51000', 'Interest', 'Begin Total', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', false, true, 'system'),
- ('51110', 'Interest Account', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('51115', 'Supplier Payment Discounts', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('51120', 'Customer Payment Discounts', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('51235', 'Rounding Account', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', true, true, 'system'),
- ('51999', 'Interest, Total', 'End Total', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Debit', 'Average', false, true, 'system'),
- ('79999', 'Income Statement, Total', 'End Total', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Both', 'Average', true, true, 'system'),
- ('80000', 'Balance Sheet', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Both', 'Average', false, true, 'system'),
- ('80001', 'Assets', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),
- ('81000', 'Fixed Assets', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),
- ('81010', 'Fixed Asset Acquisition Cost', 'Posting', 'cjgo71si60lg1aoj5p60', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),
- ('81015', 'Fixed Asset Acquisition Cost on Disposal', 'Posting', 'cjgo71si60lg1aoj5p60', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),
- ('81020', 'Accumulated Depreciation', 'Posting', 'cjgo71si60lg1aoj5p6g', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('81030', 'Fixed Asset Acquisition Depreciation on Disposal', 'Posting', 'cjgo71si60lg1aoj5p6g', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('81999', 'Fixed Assets, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),
- ('83000', 'Current Assets', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Both', 'Average', false, true, 'system'),
- ('83105', 'Inventory', 'Posting', 'cjgo71si60lg1aoj5p50', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),
- ('83120', 'Inventory Interim', 'Posting', 'cjgo71si60lg1aoj5p50', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),
- ('83125', 'Work In Progress (WIP)', 'Posting', 'cjgo71si60lg1aoj5p50', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),
- ('85005', 'Receivables', 'Posting', 'cjgo71si60lg1aoj5p4g', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('85020', 'Inventory Invoiced Not Received', 'Posting', 'cjgo71si60lg1aoj5p4g', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('86005', 'Bank - Cash', 'Posting', 'cjgo71si60lg1aoj5p40', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('86010', 'Bank - Local Currency', 'Posting', 'cjgo71si60lg1aoj5p40', NULL, 'Balance Sheet', 'Credit', 'Average', false, true, 'system'),
- ('86015', 'Bank - Foreign Currency', 'Posting', 'cjgo71si60lg1aoj5p40', NULL, 'Balance Sheet', 'Credit', 'Average', false, true, 'system'),
- ('87999', 'Current Assets, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Both', 'Average', false, true, 'system'),
- ('89999', 'Assets, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),
- ('90000', 'Liabilities', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),
- ('92210', 'Prepayments', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('93005', 'Payables', 'Posting', 'cjgo71si60lg1aoj5p7g', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('93010', 'Inventory Received Not Invoiced', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('93110', 'Inventory Shipped Not Invoiced', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),
- ('94100', 'Sales Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('94110', 'Purchase Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),
- ('94115', 'Reverse Charge Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),
- ('94999', 'Liabilities, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),
- ('95000', 'Equity', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),
- ('95010', 'Retained Earnings', 'Posting', 'cjgo71si60lg1aoj5pa0', NULL, 'Balance Sheet', 'Credit', 'Average', false, true, 'system'),
- ('96010', 'Owner Equity', 'Posting', 'cjgo71si60lg1aoj5p90', NULL, 'Balance Sheet', 'Both', 'Average', true, true, 'system'),
- ('96999', 'Equity, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),
- ('99999', 'Balance Sheet, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Both', 'Average', false, true, 'system');
+ ('10000', 'Income Statement', 'Begin Total', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', null, 'Average', false, true, 'system'),
+ ('11000', 'Revenue', 'Begin Total', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Revenue', 'Average', false, true, 'system'),
+ ('11210', 'Sales', 'Posting', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Revenue', 'Average', true, true, 'system'),
+ ('11600', 'Sales Discounts', 'Posting', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Revenue', 'Average', true, true, 'system'),
+ ('19999', 'Revenue, Total', 'End Total', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', 'Revenue', 'Average', false, true, 'system'),
+ ('20000', 'Costs of Goods Sold', 'Begin Total', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Expense', 'Average', false, true, 'system'),
+ ('21210', 'Cost of Goods Sold', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('21410', 'Purchases', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('21590', 'Direct Cost Applied', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('21600', 'Overhead Applied', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('21610', 'Purchase Variance', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('21700', 'Inventory Adjustment', 'Posting', 'cjgo71si60lg1aoj5pb0', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('24999', 'Costs of Goods Sold, Total', 'End Total', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Expense', 'Average', false, true, 'system'),
+ ('25000', 'Direct Capacity Cost', 'Begin Total', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Expense', 'Average', false, true, 'system'),
+ ('25705', 'Material Variance', 'Posting', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('25710', 'Capacity Variance', 'Posting', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('25720', 'Overhead Accounts', 'Posting', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('47045', 'Maintenance Expense', 'Posting', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('49999', 'Direct Capacity Cost, Total', 'End Total', 'cjgo71si60lg1aoj5pbg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('50000', 'Depreciation of Fixed Assets', 'Begin Total', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', false, true, 'system'),
+ ('50015', 'Depreciation Expense', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('50040', 'Gains and Losses on Disposal', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('50045', 'Service Charge Account', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('50999', 'Depreciation of Fixed Assets, Total', 'End Total', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', false, true, 'system'),
+ ('51000', 'Interest', 'Begin Total', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', false, true, 'system'),
+ ('51110', 'Interest Account', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('51115', 'Supplier Payment Discounts', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('51120', 'Customer Payment Discounts', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('51235', 'Rounding Account', 'Posting', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', true, true, 'system'),
+ ('51999', 'Interest, Total', 'End Total', 'cjgo71si60lg1aoj5pcg', NULL, 'Income Statement', 'Expense', 'Average', false, true, 'system'),
+ ('79999', 'Income Statement, Total', 'End Total', 'cjgo71si60lg1aoj5pag', NULL, 'Income Statement', null, 'Average', true, true, 'system'),
+ ('80000', 'Balance Sheet', 'Begin Total', NULL, NULL, 'Balance Sheet', null, 'Average', false, true, 'system'),
+ ('80001', 'Assets', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Asset', 'Average', false, true, 'system'),
+ ('81000', 'Fixed Assets', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Asset', 'Average', false, true, 'system'),
+ ('81010', 'Fixed Asset Acquisition Cost', 'Posting', 'cjgo71si60lg1aoj5p60', NULL, 'Balance Sheet', 'Asset', 'Average', true, true, 'system'),
+ ('81015', 'Fixed Asset Acquisition Cost on Disposal', 'Posting', 'cjgo71si60lg1aoj5p60', NULL, 'Balance Sheet', 'Asset','Average', true, true, 'system'),
+ ('81020', 'Accumulated Depreciation', 'Posting', 'cjgo71si60lg1aoj5p6g', NULL, 'Balance Sheet', 'Asset', 'Average', true, true, 'system'),
+ ('81030', 'Fixed Asset Acquisition Depreciation on Disposal', 'Posting', 'cjgo71si60lg1aoj5p6g', NULL, 'Balance Sheet', 'Asset', 'Average', true, true, 'system'),
+ ('81999', 'Fixed Assets, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Asset', 'Average', false, true, 'system'),
+ ('83000', 'Current Assets', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Asset', 'Average', false, true, 'system'),
+ ('83105', 'Inventory', 'Posting', 'cjgo71si60lg1aoj5p50', NULL, 'Balance Sheet', 'Asset', 'Average', true, true, 'system'),
+ ('83120', 'Inventory Interim', 'Posting', 'cjgo71si60lg1aoj5p50', NULL, 'Balance Sheet', 'Asset', 'Average', true, true, 'system'),
+ ('83125', 'Work In Progress (WIP)', 'Posting', 'cjgo71si60lg1aoj5p50', NULL, 'Balance Sheet', 'Asset', 'Average', true, true, 'system'),
+ ('85005', 'Receivables', 'Posting', 'cjgo71si60lg1aoj5p4g', NULL, 'Balance Sheet', 'Asset', 'Average', true, true, 'system'),
+ ('85020', 'Inventory Invoiced Not Received', 'Posting', 'cjgo71si60lg1aoj5p4g', NULL, 'Balance Sheet', 'Asset', 'Average', true, true, 'system'),
+ ('86005', 'Bank - Cash', 'Posting', 'cjgo71si60lg1aoj5p40', NULL, 'Balance Sheet', 'Asset', 'Average', true, true, 'system'),
+ ('86010', 'Bank - Local Currency', 'Posting', 'cjgo71si60lg1aoj5p40', NULL, 'Balance Sheet', 'Asset', 'Average', false, true, 'system'),
+ ('86015', 'Bank - Foreign Currency', 'Posting', 'cjgo71si60lg1aoj5p40', NULL, 'Balance Sheet', 'Asset', 'Average', false, true, 'system'),
+ ('87999', 'Current Assets, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Asset', 'Average', false, true, 'system'),
+ ('89999', 'Assets, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Asset', 'Average', false, true, 'system'),
+ ('90000', 'Liabilities', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Liability', 'Average', false, true, 'system'),
+ ('92210', 'Customer Prepayments', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Liability', 'Average', true, true, 'system'),
+ ('93005', 'Payables', 'Posting', 'cjgo71si60lg1aoj5p7g', NULL, 'Balance Sheet', 'Liability', 'Average', true, true, 'system'),
+ ('93010', 'Inventory Received Not Invoiced', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Liability', 'Average', true, true, 'system'),
+ ('93110', 'Inventory Shipped Not Invoiced', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Liability', 'Average', true, true, 'system'),
+ ('94100', 'Sales Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Liability', 'Average', true, true, 'system'),
+ ('94110', 'Purchase Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Liability', 'Average', true, true, 'system'),
+ ('94115', 'Reverse Charge Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Liability', 'Average', true, true, 'system'),
+ ('94999', 'Liabilities, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Liability', 'Average', false, true, 'system'),
+ ('95000', 'Equity', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Equity', 'Average', false, true, 'system'),
+ ('95010', 'Retained Earnings', 'Posting', 'cjgo71si60lg1aoj5pa0', NULL, 'Balance Sheet', 'Equity', 'Average', false, true, 'system'),
+ ('96010', 'Owner Equity', 'Posting', 'cjgo71si60lg1aoj5p90', NULL, 'Balance Sheet', 'Equity', 'Average', true, true, 'system'),
+ ('96999', 'Equity, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Equity', 'Average', false, true, 'system'),
+ ('99999', 'Balance Sheet, Total', 'End Total', NULL, NULL, 'Balance Sheet', null, 'Average', false, true, 'system');
INSERT INTO public."accountDefault" (
"id",