Initial copy from influencer-biz

This commit is contained in:
Jakob Wennberg
2026-02-13 14:00:46 +01:00
commit a25d10a528
391 changed files with 96224 additions and 0 deletions
+480
View File
@@ -0,0 +1,480 @@
---
name: langchain
description: Framework for building LLM-powered applications with agents, chains, and RAG. Supports multiple providers (OpenAI, Anthropic, Google), 500+ integrations, ReAct agents, tool calling, memory management, and vector store retrieval. Use for building chatbots, question-answering systems, autonomous agents, or RAG applications. Best for rapid prototyping and production deployments.
version: 1.0.0
author: Orchestra Research
license: MIT
tags: [Agents, LangChain, RAG, Tool Calling, ReAct, Memory Management, Vector Stores, LLM Applications, Chatbots, Production]
dependencies: [langchain, langchain-core, langchain-openai, langchain-anthropic]
---
# LangChain - Build LLM Applications with Agents & RAG
The most popular framework for building LLM-powered applications.
## When to use LangChain
**Use LangChain when:**
- Building agents with tool calling and reasoning (ReAct pattern)
- Implementing RAG (retrieval-augmented generation) pipelines
- Need to swap LLM providers easily (OpenAI, Anthropic, Google)
- Creating chatbots with conversation memory
- Rapid prototyping of LLM applications
- Production deployments with LangSmith observability
**Metrics**:
- **119,000+ GitHub stars**
- **272,000+ repositories** use LangChain
- **500+ integrations** (models, vector stores, tools)
- **3,800+ contributors**
**Use alternatives instead**:
- **LlamaIndex**: RAG-focused, better for document Q&A
- **LangGraph**: Complex stateful workflows, more control
- **Haystack**: Production search pipelines
- **Semantic Kernel**: Microsoft ecosystem
## Quick start
### Installation
```bash
# Core library (Python 3.10+)
pip install -U langchain
# With OpenAI
pip install langchain-openai
# With Anthropic
pip install langchain-anthropic
# Common extras
pip install langchain-community # 500+ integrations
pip install langchain-chroma # Vector store
```
### Basic LLM usage
```python
from langchain_anthropic import ChatAnthropic
# Initialize model
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
# Simple completion
response = llm.invoke("Explain quantum computing in 2 sentences")
print(response.content)
```
### Create an agent (ReAct pattern)
```python
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
# Define tools
def get_weather(city: str) -> str:
"""Get current weather for a city."""
return f"It's sunny in {city}, 72°F"
def search_web(query: str) -> str:
"""Search the web for information."""
return f"Search results for: {query}"
# Create agent (<10 lines!)
agent = create_agent(
model=ChatAnthropic(model="claude-sonnet-4-5-20250929"),
tools=[get_weather, search_web],
system_prompt="You are a helpful assistant. Use tools when needed."
)
# Run agent
result = agent.invoke({"messages": [{"role": "user", "content": "What's the weather in Paris?"}]})
print(result["messages"][-1].content)
```
## Core concepts
### 1. Models - LLM abstraction
```python
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
from langchain_google_genai import ChatGoogleGenerativeAI
# Swap providers easily
llm = ChatOpenAI(model="gpt-4o")
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929")
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-exp")
# Streaming
for chunk in llm.stream("Write a poem"):
print(chunk.content, end="", flush=True)
```
### 2. Chains - Sequential operations
```python
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
# Define prompt template
prompt = PromptTemplate(
input_variables=["topic"],
template="Write a 3-sentence summary about {topic}"
)
# Create chain
chain = LLMChain(llm=llm, prompt=prompt)
# Run chain
result = chain.run(topic="machine learning")
```
### 3. Agents - Tool-using reasoning
**ReAct (Reasoning + Acting) pattern:**
```python
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain.tools import Tool
# Define custom tool
calculator = Tool(
name="Calculator",
func=lambda x: eval(x),
description="Useful for math calculations. Input: valid Python expression."
)
# Create agent with tools
agent = create_tool_calling_agent(
llm=llm,
tools=[calculator, search_web],
prompt="Answer questions using available tools"
)
# Create executor
agent_executor = AgentExecutor(agent=agent, tools=[calculator], verbose=True)
# Run with reasoning
result = agent_executor.invoke({"input": "What is 25 * 17 + 142?"})
```
### 4. Memory - Conversation history
```python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
# Add memory to track conversation
memory = ConversationBufferMemory()
conversation = ConversationChain(
llm=llm,
memory=memory,
verbose=True
)
# Multi-turn conversation
conversation.predict(input="Hi, I'm Alice")
conversation.predict(input="What's my name?") # Remembers "Alice"
```
## RAG (Retrieval-Augmented Generation)
### Basic RAG pipeline
```python
from langchain_community.document_loaders import WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma
from langchain.chains import RetrievalQA
# 1. Load documents
loader = WebBaseLoader("https://docs.python.org/3/tutorial/")
docs = loader.load()
# 2. Split into chunks
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
splits = text_splitter.split_documents(docs)
# 3. Create embeddings and vector store
vectorstore = Chroma.from_documents(
documents=splits,
embedding=OpenAIEmbeddings()
)
# 4. Create retriever
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
# 5. Create QA chain
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
retriever=retriever,
return_source_documents=True
)
# 6. Query
result = qa_chain({"query": "What are Python decorators?"})
print(result["result"])
print(f"Sources: {result['source_documents']}")
```
### Conversational RAG with memory
```python
from langchain.chains import ConversationalRetrievalChain
# RAG with conversation memory
qa = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=retriever,
memory=ConversationBufferMemory(
memory_key="chat_history",
return_messages=True
)
)
# Multi-turn RAG
qa({"question": "What is Python used for?"})
qa({"question": "Can you elaborate on web development?"}) # Remembers context
```
## Advanced agent patterns
### Structured output
```python
from langchain_core.pydantic_v1 import BaseModel, Field
# Define schema
class WeatherReport(BaseModel):
city: str = Field(description="City name")
temperature: float = Field(description="Temperature in Fahrenheit")
condition: str = Field(description="Weather condition")
# Get structured response
structured_llm = llm.with_structured_output(WeatherReport)
result = structured_llm.invoke("What's the weather in SF? It's 65F and sunny")
print(result.city, result.temperature, result.condition)
```
### Parallel tool execution
```python
from langchain.agents import create_tool_calling_agent
# Agent automatically parallelizes independent tool calls
agent = create_tool_calling_agent(
llm=llm,
tools=[get_weather, search_web, calculator]
)
# This will call get_weather("Paris") and get_weather("London") in parallel
result = agent.invoke({
"messages": [{"role": "user", "content": "Compare weather in Paris and London"}]
})
```
### Streaming agent execution
```python
# Stream agent steps
for step in agent_executor.stream({"input": "Research AI trends"}):
if "actions" in step:
print(f"Tool: {step['actions'][0].tool}")
if "output" in step:
print(f"Output: {step['output']}")
```
## Common patterns
### Multi-document QA
```python
from langchain.chains.qa_with_sources import load_qa_with_sources_chain
# Load multiple documents
docs = [
loader.load("https://docs.python.org"),
loader.load("https://docs.numpy.org")
]
# QA with source citations
chain = load_qa_with_sources_chain(llm, chain_type="stuff")
result = chain({"input_documents": docs, "question": "How to use numpy arrays?"})
print(result["output_text"]) # Includes source citations
```
### Custom tools with error handling
```python
from langchain.tools import tool
@tool
def risky_operation(query: str) -> str:
"""Perform a risky operation that might fail."""
try:
# Your operation here
result = perform_operation(query)
return f"Success: {result}"
except Exception as e:
return f"Error: {str(e)}"
# Agent handles errors gracefully
agent = create_agent(model=llm, tools=[risky_operation])
```
### LangSmith observability
```python
import os
# Enable tracing
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-api-key"
os.environ["LANGCHAIN_PROJECT"] = "my-project"
# All chains/agents automatically traced
agent = create_agent(model=llm, tools=[calculator])
result = agent.invoke({"input": "Calculate 123 * 456"})
# View traces at smith.langchain.com
```
## Vector stores
### Chroma (local)
```python
from langchain_chroma import Chroma
vectorstore = Chroma.from_documents(
documents=docs,
embedding=OpenAIEmbeddings(),
persist_directory="./chroma_db"
)
```
### Pinecone (cloud)
```python
from langchain_pinecone import PineconeVectorStore
vectorstore = PineconeVectorStore.from_documents(
documents=docs,
embedding=OpenAIEmbeddings(),
index_name="my-index"
)
```
### FAISS (similarity search)
```python
from langchain_community.vectorstores import FAISS
vectorstore = FAISS.from_documents(docs, OpenAIEmbeddings())
vectorstore.save_local("faiss_index")
# Load later
vectorstore = FAISS.load_local("faiss_index", OpenAIEmbeddings())
```
## Document loaders
```python
# Web pages
from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://example.com")
# PDFs
from langchain_community.document_loaders import PyPDFLoader
loader = PyPDFLoader("paper.pdf")
# GitHub
from langchain_community.document_loaders import GithubFileLoader
loader = GithubFileLoader(repo="user/repo", file_filter=lambda x: x.endswith(".py"))
# CSV
from langchain_community.document_loaders import CSVLoader
loader = CSVLoader("data.csv")
```
## Text splitters
```python
# Recursive (recommended for general text)
from langchain.text_splitter import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
separators=["\n\n", "\n", " ", ""]
)
# Code-aware
from langchain.text_splitter import PythonCodeTextSplitter
splitter = PythonCodeTextSplitter(chunk_size=500)
# Semantic (by meaning)
from langchain_experimental.text_splitter import SemanticChunker
splitter = SemanticChunker(OpenAIEmbeddings())
```
## Best practices
1. **Start simple** - Use `create_agent()` for most cases
2. **Enable streaming** - Better UX for long responses
3. **Add error handling** - Tools can fail, handle gracefully
4. **Use LangSmith** - Essential for debugging agents
5. **Optimize chunk size** - 500-1000 chars for RAG
6. **Version prompts** - Track changes in production
7. **Cache embeddings** - Expensive, cache when possible
8. **Monitor costs** - Track token usage with LangSmith
## Performance benchmarks
| Operation | Latency | Notes |
|-----------|---------|-------|
| Simple LLM call | ~1-2s | Depends on provider |
| Agent with 1 tool | ~3-5s | ReAct reasoning overhead |
| RAG retrieval | ~0.5-1s | Vector search + LLM |
| Embedding 1000 docs | ~10-30s | Depends on model |
## LangChain vs LangGraph
| Feature | LangChain | LangGraph |
|---------|-----------|-----------|
| **Best for** | Quick agents, RAG | Complex workflows |
| **Abstraction level** | High | Low |
| **Code to start** | <10 lines | ~30 lines |
| **Control** | Simple | Full control |
| **Stateful workflows** | Limited | Native |
| **Cyclic graphs** | No | Yes |
| **Human-in-loop** | Basic | Advanced |
**Use LangGraph when:**
- Need stateful workflows with cycles
- Require fine-grained control
- Building multi-agent systems
- Production apps with complex logic
## References
- **[Agents Guide](references/agents.md)** - ReAct, tool calling, streaming
- **[RAG Guide](references/rag.md)** - Document loaders, retrievers, QA chains
- **[Integration Guide](references/integration.md)** - Vector stores, LangSmith, deployment
## Resources
- **GitHub**: https://github.com/langchain-ai/langchain ⭐ 119,000+
- **Docs**: https://docs.langchain.com
- **API Reference**: https://reference.langchain.com/python
- **LangSmith**: https://smith.langchain.com (observability)
- **Version**: 0.3+ (stable)
- **License**: MIT
@@ -0,0 +1,499 @@
# LangChain Agents Guide
Complete guide to building agents with ReAct, tool calling, and streaming.
## What are agents?
Agents combine language models with tools to solve complex tasks through reasoning and action:
1. **Reasoning**: LLM decides what to do
2. **Acting**: Execute tools based on reasoning
3. **Observation**: Receive tool results
4. **Loop**: Repeat until task complete
This is the **ReAct pattern** (Reasoning + Acting).
## Basic agent creation
```python
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
# Define tools
def calculator(expression: str) -> str:
"""Evaluate a math expression."""
return str(eval(expression))
def search(query: str) -> str:
"""Search for information."""
return f"Results for: {query}"
# Create agent
agent = create_agent(
model=ChatAnthropic(model="claude-sonnet-4-5-20250929"),
tools=[calculator, search],
system_prompt="You are a helpful assistant. Use tools when needed."
)
# Run agent
result = agent.invoke({
"messages": [{"role": "user", "content": "What is 25 * 17?"}]
})
print(result["messages"][-1].content)
```
## Agent components
### 1. Model - The reasoning engine
```python
from langchain_openai import ChatOpenAI
from langchain_anthropic import ChatAnthropic
# OpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)
# Anthropic (better for complex reasoning)
model = ChatAnthropic(model="claude-sonnet-4-5-20250929", temperature=0)
# Dynamic model selection
def select_model(task_complexity: str):
if task_complexity == "high":
return ChatAnthropic(model="claude-sonnet-4-5-20250929")
else:
return ChatOpenAI(model="gpt-4o-mini")
```
### 2. Tools - Actions the agent can take
```python
from langchain.tools import tool
# Simple function tool
@tool
def get_current_time() -> str:
"""Get the current time."""
from datetime import datetime
return datetime.now().strftime("%H:%M:%S")
# Tool with parameters
@tool
def fetch_weather(city: str, units: str = "fahrenheit") -> str:
"""Fetch weather for a city.
Args:
city: City name
units: Temperature units (fahrenheit or celsius)
"""
# Your weather API call here
return f"Weather in {city}: 72°{units[0].upper()}"
# Tool with error handling
@tool
def risky_api_call(endpoint: str) -> str:
"""Call an external API that might fail."""
try:
response = requests.get(endpoint, timeout=5)
return response.text
except Exception as e:
return f"Error calling API: {str(e)}"
```
### 3. System prompt - Agent behavior
```python
# General assistant
system_prompt = "You are a helpful assistant. Use tools when needed."
# Domain expert
system_prompt = """You are a financial analyst assistant.
- Use the calculator for precise calculations
- Search for recent financial data
- Provide data-driven recommendations
- Always cite your sources"""
# Constrained agent
system_prompt = """You are a customer support agent.
- Only use search_kb tool to find answers
- If answer not found, escalate to human
- Be concise and professional
- Never make up information"""
```
## Agent types
### 1. Tool-calling agent (recommended)
Uses native function calling for best performance:
```python
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain.prompts import ChatPromptTemplate
# Create prompt
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant"),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
# Create agent
agent = create_tool_calling_agent(
llm=model,
tools=[calculator, search],
prompt=prompt
)
# Wrap in executor
agent_executor = AgentExecutor(
agent=agent,
tools=[calculator, search],
verbose=True,
max_iterations=5,
handle_parsing_errors=True
)
# Run
result = agent_executor.invoke({"input": "What is the weather in Paris?"})
```
### 2. ReAct agent (reasoning trace)
Shows step-by-step reasoning:
```python
from langchain.agents import create_react_agent
# ReAct prompt shows thought process
react_prompt = """Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought: {agent_scratchpad}"""
agent = create_react_agent(
llm=model,
tools=[calculator, search],
prompt=ChatPromptTemplate.from_template(react_prompt)
)
# Run with visible reasoning
result = agent_executor.invoke({"input": "What is 25 * 17 + 142?"})
```
### 3. Conversational agent (with memory)
Remembers conversation history:
```python
from langchain.agents import create_conversational_retrieval_agent
from langchain.memory import ConversationBufferMemory
# Add memory
memory = ConversationBufferMemory(
memory_key="chat_history",
return_messages=True
)
# Conversational agent
agent_executor = AgentExecutor(
agent=agent,
tools=[calculator, search],
memory=memory,
verbose=True
)
# Multi-turn conversation
agent_executor.invoke({"input": "My name is Alice"})
agent_executor.invoke({"input": "What's my name?"}) # Remembers "Alice"
agent_executor.invoke({"input": "What is 25 * 17?"})
```
## Tool execution patterns
### Parallel tool execution
```python
# Agent automatically parallelizes independent calls
agent = create_tool_calling_agent(llm=model, tools=[get_weather, search])
# This calls get_weather("Paris") and get_weather("London") in parallel
result = agent_executor.invoke({
"input": "Compare weather in Paris and London"
})
```
### Sequential tool chaining
```python
# Agent chains tools automatically
@tool
def search_company(name: str) -> str:
"""Search for company information."""
return f"Company ID: 12345, Industry: Tech"
@tool
def get_stock_price(company_id: str) -> str:
"""Get stock price for a company."""
return f"${150.00}"
# Agent will: search_company → get_stock_price
result = agent_executor.invoke({
"input": "What is Apple's current stock price?"
})
```
### Conditional tool usage
```python
# Agent decides when to use tools
@tool
def expensive_tool(query: str) -> str:
"""Use only when necessary - costs $0.10 per call."""
return perform_expensive_operation(query)
# Agent uses tool only if needed
result = agent_executor.invoke({
"input": "What is 2+2?" # Won't use expensive_tool
})
```
## Streaming
### Stream agent steps
```python
# Stream intermediate steps
for step in agent_executor.stream({"input": "Research quantum computing"}):
if "actions" in step:
action = step["actions"][0]
print(f"Tool: {action.tool}, Input: {action.tool_input}")
if "steps" in step:
print(f"Observation: {step['steps'][0].observation}")
if "output" in step:
print(f"Final: {step['output']}")
```
### Stream LLM tokens
```python
from langchain.callbacks import StreamingStdOutCallbackHandler
# Stream model responses
agent_executor = AgentExecutor(
agent=agent,
tools=[calculator],
callbacks=[StreamingStdOutCallbackHandler()],
verbose=True
)
result = agent_executor.invoke({"input": "Explain quantum computing"})
```
## Error handling
### Tool error handling
```python
@tool
def fallible_tool(query: str) -> str:
"""A tool that might fail."""
try:
result = risky_operation(query)
return f"Success: {result}"
except Exception as e:
return f"Error: {str(e)}. Please try a different approach."
# Agent adapts to errors
agent_executor = AgentExecutor(
agent=agent,
tools=[fallible_tool],
handle_parsing_errors=True, # Handle malformed tool calls
max_iterations=5
)
```
### Timeout handling
```python
from langchain.callbacks import TimeoutCallback
# Set timeout
agent_executor = AgentExecutor(
agent=agent,
tools=[slow_tool],
callbacks=[TimeoutCallback(timeout=30)], # 30 second timeout
max_iterations=10
)
```
### Retry logic
```python
from langchain.callbacks import RetryCallback
# Retry on failure
agent_executor = AgentExecutor(
agent=agent,
tools=[unreliable_tool],
callbacks=[RetryCallback(max_retries=3)],
max_execution_time=60
)
```
## Advanced patterns
### Dynamic tool selection
```python
# Select tools based on context
def get_tools_for_user(user_role: str):
if user_role == "admin":
return [search, calculator, database_query, delete_data]
elif user_role == "analyst":
return [search, calculator, database_query]
else:
return [search, calculator]
# Create agent with role-based tools
tools = get_tools_for_user(current_user.role)
agent = create_agent(model=model, tools=tools)
```
### Multi-step reasoning
```python
# Agent plans multiple steps
system_prompt = """Break down complex tasks into steps:
1. Analyze the question
2. Determine required information
3. Use tools to gather data
4. Synthesize findings
5. Provide final answer"""
agent = create_agent(
model=model,
tools=[search, calculator, database],
system_prompt=system_prompt
)
result = agent.invoke({
"input": "Compare revenue growth of top 3 tech companies over 5 years"
})
```
### Structured output from agents
```python
from langchain_core.pydantic_v1 import BaseModel, Field
class ResearchReport(BaseModel):
summary: str = Field(description="Executive summary")
findings: list[str] = Field(description="Key findings")
sources: list[str] = Field(description="Source URLs")
# Agent returns structured output
structured_agent = agent.with_structured_output(ResearchReport)
report = structured_agent.invoke({"input": "Research AI safety"})
print(report.summary, report.findings)
```
## Middleware & customization
### Custom agent middleware
```python
from langchain.agents import AgentExecutor
def logging_middleware(agent_executor):
"""Log all agent actions."""
original_invoke = agent_executor.invoke
def wrapped_invoke(*args, **kwargs):
print(f"Agent invoked with: {args[0]}")
result = original_invoke(*args, **kwargs)
print(f"Agent result: {result}")
return result
agent_executor.invoke = wrapped_invoke
return agent_executor
# Apply middleware
agent_executor = logging_middleware(agent_executor)
```
### Custom stopping conditions
```python
from langchain.agents import EarlyStoppingMethod
# Stop early if confident
agent_executor = AgentExecutor(
agent=agent,
tools=[search],
early_stopping_method=EarlyStoppingMethod.GENERATE, # or FORCE
max_iterations=10
)
```
## Best practices
1. **Use tool-calling agents** - Fastest and most reliable
2. **Keep tool descriptions clear** - Agent needs to understand when to use each tool
3. **Add error handling** - Tools will fail, handle gracefully
4. **Set max_iterations** - Prevent infinite loops (default: 15)
5. **Enable streaming** - Better UX for long tasks
6. **Use verbose=True during dev** - See agent reasoning
7. **Test tool combinations** - Ensure tools work together
8. **Monitor with LangSmith** - Essential for production
9. **Cache tool results** - Avoid redundant API calls
10. **Version system prompts** - Track changes in behavior
## Common pitfalls
1. **Vague tool descriptions** - Agent won't know when to use tool
2. **Too many tools** - Agent gets confused (limit to 5-10)
3. **Tools without error handling** - One failure crashes agent
4. **Circular tool dependencies** - Agent gets stuck in loops
5. **Missing max_iterations** - Agent runs forever
6. **Poor system prompts** - Agent doesn't follow instructions
## Debugging agents
```python
# Enable verbose logging
agent_executor = AgentExecutor(
agent=agent,
tools=[calculator],
verbose=True, # See all steps
return_intermediate_steps=True # Get full trace
)
result = agent_executor.invoke({"input": "Calculate 25 * 17"})
# Inspect intermediate steps
for step in result["intermediate_steps"]:
print(f"Action: {step[0].tool}")
print(f"Input: {step[0].tool_input}")
print(f"Output: {step[1]}")
```
## Resources
- **ReAct Paper**: https://arxiv.org/abs/2210.03629
- **LangChain Agents Docs**: https://docs.langchain.com/oss/python/langchain/agents
- **LangSmith Debugging**: https://smith.langchain.com
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+41
View File
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
+36
View File
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
+35
View File
@@ -0,0 +1,35 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url)
const code = searchParams.get('code')
const next = searchParams.get('next') ?? '/'
if (code) {
const supabase = await createClient()
const { error } = await supabase.auth.exchangeCodeForSession(code)
if (!error) {
// Check if user has completed onboarding
const { data: { user } } = await supabase.auth.getUser()
if (user) {
const { data: settings } = await supabase
.from('company_settings')
.select('onboarding_complete')
.eq('user_id', user.id)
.single()
if (!settings?.onboarding_complete) {
return NextResponse.redirect(`${origin}/onboarding`)
}
}
return NextResponse.redirect(`${origin}${next}`)
}
}
// Return the user to an error page with instructions
return NextResponse.redirect(`${origin}/login?error=auth_error`)
}
+144
View File
@@ -0,0 +1,144 @@
'use client'
import { useState } from 'react'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { useToast } from '@/components/ui/use-toast'
import { Loader2, Mail, Sparkles } from 'lucide-react'
export default function LoginPage() {
const [email, setEmail] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [isEmailSent, setIsEmailSent] = useState(false)
const { toast } = useToast()
const supabase = createClient()
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault()
setIsLoading(true)
try {
const { error } = await supabase.auth.signInWithOtp({
email,
options: {
emailRedirectTo: `${process.env.NEXT_PUBLIC_APP_URL || window.location.origin}/auth/callback`,
},
})
if (error) {
toast({
title: 'Fel',
description: error.message,
variant: 'destructive',
})
return
}
setIsEmailSent(true)
toast({
title: 'E-post skickad!',
description: 'Kolla din inkorg för att logga in.',
})
} catch {
toast({
title: 'Fel',
description: 'Något gick fel. Försök igen.',
variant: 'destructive',
})
} finally {
setIsLoading(false)
}
}
if (isEmailSent) {
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 via-background to-primary/10 p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="mx-auto mb-4 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
<Mail className="h-6 w-6 text-primary" />
</div>
<CardTitle className="text-2xl">Kolla din e-post</CardTitle>
<CardDescription>
Vi har skickat en inloggningslänk till <strong>{email}</strong>
</CardDescription>
</CardHeader>
<CardContent className="text-center">
<p className="text-sm text-muted-foreground mb-4">
Klicka på länken i e-posten för att logga in. Länken är giltig i 1 timme.
</p>
<Button
variant="ghost"
onClick={() => setIsEmailSent(false)}
>
Använd en annan e-post
</Button>
</CardContent>
</Card>
</div>
)
}
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-primary/5 via-background to-primary/10 p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="mx-auto mb-4 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
<Sparkles className="h-6 w-6 text-primary" />
</div>
<CardTitle className="text-2xl">Influencer Assistant</CardTitle>
<CardDescription>
Logga in med din e-post för att hantera din verksamhet
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleLogin} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">E-postadress</Label>
<Input
id="email"
type="email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
disabled={isLoading}
/>
</div>
<Button
type="submit"
className="w-full"
disabled={isLoading || !email}
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Skickar...
</>
) : (
<>
<Mail className="mr-2 h-4 w-4" />
Skicka inloggningslänk
</>
)}
</Button>
</form>
<p className="mt-4 text-center text-sm text-muted-foreground">
Genom att logga in godkänner du våra{' '}
<a href="#" className="underline hover:text-primary">
villkor
</a>{' '}
och{' '}
<a href="#" className="underline hover:text-primary">
integritetspolicy
</a>
.
</p>
</CardContent>
</Card>
</div>
)
}
+333
View File
@@ -0,0 +1,333 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { createClient } from '@/lib/supabase/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
TikTokConnectButton,
TikTokAccountCard,
TikTokStatsWidget,
TikTokGrowthChart,
TikTokVideoList,
VideoLinkModal,
TikTokROITable,
} from '@/components/tiktok'
import type { TikTokAccount, TikTokStatsSummary, TikTokVideo, TikTokCampaignROI } from '@/types'
import {
Loader2,
TrendingUp,
Video,
Target,
BarChart3,
} from 'lucide-react'
export default function AnalyticsPage() {
const router = useRouter()
const supabase = createClient()
const [isLoading, setIsLoading] = useState(true)
const [accounts, setAccounts] = useState<TikTokAccount[]>([])
const [stats, setStats] = useState<TikTokStatsSummary | null>(null)
const [roiData, setRoiData] = useState<TikTokCampaignROI[]>([])
const [selectedVideo, setSelectedVideo] = useState<TikTokVideo | null>(null)
const [isLinkModalOpen, setIsLinkModalOpen] = useState(false)
const [isSyncing, setIsSyncing] = useState(false)
useEffect(() => {
checkAuth()
}, [])
const checkAuth = async () => {
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
router.push('/login')
return
}
fetchData()
}
const fetchData = async () => {
setIsLoading(true)
await Promise.all([
fetchAccounts(),
fetchStats(),
fetchROI(),
])
setIsLoading(false)
}
const fetchAccounts = async () => {
try {
const response = await fetch('/api/tiktok/accounts')
const data = await response.json()
setAccounts(data.accounts || [])
} catch (error) {
console.error('Failed to fetch accounts:', error)
}
}
const fetchStats = async () => {
try {
const response = await fetch('/api/tiktok/stats')
const data = await response.json()
setStats(data.summary || null)
} catch (error) {
console.error('Failed to fetch stats:', error)
}
}
const fetchROI = async () => {
// Fetch campaigns with TikTok videos for ROI calculation
try {
const response = await fetch('/api/tiktok/videos?limit=100')
const data = await response.json()
// Group videos by campaign and calculate ROI
// This is a simplified version - the actual calculation is in the API
const campaignVideos = new Map<string, TikTokVideo[]>()
for (const video of data.videos || []) {
if (video.campaign_id) {
if (!campaignVideos.has(video.campaign_id)) {
campaignVideos.set(video.campaign_id, [])
}
campaignVideos.get(video.campaign_id)!.push(video)
}
}
// For now, just set empty - actual ROI data would come from a dedicated endpoint
setRoiData([])
} catch (error) {
console.error('Failed to fetch ROI data:', error)
}
}
const handleSync = async () => {
if (accounts.length === 0) return
setIsSyncing(true)
try {
const activeAccount = accounts.find(a => a.status === 'active')
if (activeAccount) {
await fetch('/api/tiktok/sync', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_id: activeAccount.id, sync_type: 'full' }),
})
await fetchData()
}
} catch (error) {
console.error('Sync failed:', error)
}
setIsSyncing(false)
}
const handleVideoLinkClick = (video: TikTokVideo) => {
setSelectedVideo(video)
setIsLinkModalOpen(true)
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
)
}
const activeAccount = accounts.find(a => a.status === 'active')
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Analytics</h1>
<p className="text-muted-foreground">
Analysera din sociala medieprestanda och kampanj-ROI
</p>
</div>
{/* No connected account */}
{accounts.length === 0 && (
<Card>
<CardHeader>
<CardTitle>Koppla TikTok</CardTitle>
<CardDescription>
Anslut ditt TikTok-konto för att se statistik och analysera kampanjprestanda
</CardDescription>
</CardHeader>
<CardContent>
<TikTokConnectButton />
</CardContent>
</Card>
)}
{/* Connected account */}
{activeAccount && (
<>
{/* Stats overview */}
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-2">
<TrendingUp className="h-4 w-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">Följare</span>
</div>
<p className="text-2xl font-bold mt-2">
{stats?.currentFollowers.toLocaleString('sv-SE') || '0'}
</p>
{stats?.followerChange7d !== undefined && (
<p className={`text-sm ${stats.followerChange7d >= 0 ? 'text-success' : 'text-destructive'}`}>
{stats.followerChange7d >= 0 ? '+' : ''}{stats.followerChange7d.toLocaleString('sv-SE')} senaste 7 dagar
</p>
)}
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-2">
<Video className="h-4 w-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">Videor</span>
</div>
<p className="text-2xl font-bold mt-2">
{stats?.totalVideos || 0}
</p>
<p className="text-sm text-muted-foreground">
{stats?.totalLikes.toLocaleString('sv-SE') || '0'} totala likes
</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-2">
<Target className="h-4 w-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">Engagement Rate</span>
</div>
<p className="text-2xl font-bold mt-2">
{stats?.engagementRate.toFixed(1) || '0'}%
</p>
<p className="text-sm text-muted-foreground">
Genomsnitt senaste videor
</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-2">
<BarChart3 className="h-4 w-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">30-dagars tillväxt</span>
</div>
<p className="text-2xl font-bold mt-2">
{stats?.followerChange30d !== undefined ? (
<>
{stats.followerChange30d >= 0 ? '+' : ''}
{stats.followerChange30d.toLocaleString('sv-SE')}
</>
) : '0'}
</p>
<p className="text-sm text-muted-foreground">
nya följare
</p>
</CardContent>
</Card>
</div>
{/* Tabs for different views */}
<Tabs defaultValue="growth" className="space-y-6">
<TabsList>
<TabsTrigger value="growth">Tillväxt</TabsTrigger>
<TabsTrigger value="videos">Videor</TabsTrigger>
<TabsTrigger value="roi">Kampanj-ROI</TabsTrigger>
</TabsList>
<TabsContent value="growth" className="space-y-6">
<TikTokGrowthChart accountId={activeAccount.id} />
{/* Recent videos with metrics */}
<Card>
<CardHeader>
<CardTitle>Senaste videor</CardTitle>
<CardDescription>
Prestanda för dina senaste publiceringar
</CardDescription>
</CardHeader>
<CardContent>
<TikTokVideoList
accountId={activeAccount.id}
limit={6}
onLinkClick={handleVideoLinkClick}
/>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="videos" className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>Alla videor</CardTitle>
<CardDescription>
Klicka på länk-ikonen för att koppla en video till en kampanj
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent>
<TikTokVideoList
accountId={activeAccount.id}
limit={20}
onLinkClick={handleVideoLinkClick}
/>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="roi" className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Kampanj-ROI</CardTitle>
<CardDescription>
Analysera avkastningen på dina influencer-kampanjer baserat på TikTok-prestanda
</CardDescription>
</CardHeader>
<CardContent>
<TikTokROITable campaigns={roiData} />
</CardContent>
</Card>
</TabsContent>
</Tabs>
{/* Account info at bottom */}
<Card>
<CardHeader>
<CardTitle>Kopplat konto</CardTitle>
</CardHeader>
<CardContent>
<TikTokAccountCard
account={activeAccount}
onDisconnect={fetchData}
onSync={fetchData}
/>
</CardContent>
</Card>
</>
)}
{/* Video link modal */}
<VideoLinkModal
video={selectedVideo}
isOpen={isLinkModalOpen}
onClose={() => {
setIsLinkModalOpen(false)
setSelectedVideo(null)
}}
onSuccess={fetchData}
/>
</div>
)
}
+42
View File
@@ -0,0 +1,42 @@
'use client'
import { useState } from 'react'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import JournalEntryList from '@/components/bookkeeping/JournalEntryList'
import JournalEntryForm from '@/components/bookkeeping/JournalEntryForm'
import ChartOfAccounts from '@/components/bookkeeping/ChartOfAccounts'
export default function BookkeepingPage() {
const [refreshKey, setRefreshKey] = useState(0)
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Bokföring</h1>
<p className="text-muted-foreground">
Verifikationer, kontoplan och manuella bokföringsorder
</p>
</div>
<Tabs defaultValue="journal">
<TabsList>
<TabsTrigger value="journal">Verifikationer</TabsTrigger>
<TabsTrigger value="new-entry">Ny verifikation</TabsTrigger>
<TabsTrigger value="accounts">Kontoplan</TabsTrigger>
</TabsList>
<TabsContent value="journal">
<JournalEntryList key={refreshKey} />
</TabsContent>
<TabsContent value="new-entry">
<JournalEntryForm onCreated={() => setRefreshKey((k) => k + 1)} />
</TabsContent>
<TabsContent value="accounts">
<ChartOfAccounts />
</TabsContent>
</Tabs>
</div>
)
}
+142
View File
@@ -0,0 +1,142 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { createClient } from '@/lib/supabase/client'
import { useToast } from '@/components/ui/use-toast'
import { PaymentCalendar } from '@/components/calendar/PaymentCalendar'
import type { Invoice, Deadline } from '@/types'
export default function CalendarPage() {
const [invoices, setInvoices] = useState<Invoice[]>([])
const [deadlines, setDeadlines] = useState<Deadline[]>([])
const [customers, setCustomers] = useState<{ id: string; name: string }[]>([])
const [isLoading, setIsLoading] = useState(true)
const { toast } = useToast()
const supabase = createClient()
const fetchData = useCallback(async () => {
setIsLoading(true)
try {
// Fetch invoices with customer names
const { data: invoicesData, error: invoicesError } = await supabase
.from('invoices')
.select('*, customer:customers(name)')
.order('due_date', { ascending: true })
if (invoicesError) throw invoicesError
// Fetch deadlines with customer names
const { data: deadlinesData, error: deadlinesError } = await supabase
.from('deadlines')
.select('*, customer:customers(name)')
.order('due_date', { ascending: true })
if (deadlinesError) throw deadlinesError
// Fetch customers for the form
const { data: customersData, error: customersError } = await supabase
.from('customers')
.select('id, name')
.order('name', { ascending: true })
if (customersError) throw customersError
setInvoices(invoicesData || [])
setDeadlines(deadlinesData || [])
setCustomers(customersData || [])
} catch (error) {
toast({
title: 'Fel',
description: 'Kunde inte hämta data',
variant: 'destructive',
})
} finally {
setIsLoading(false)
}
}, [supabase, toast])
useEffect(() => {
fetchData()
}, [fetchData])
const handleDeadlineCreate = async (
data: Omit<Deadline, 'id' | 'user_id' | 'created_at' | 'updated_at'>
) => {
try {
const { error } = await supabase.from('deadlines').insert([data])
if (error) throw error
toast({
title: 'Deadline skapad',
description: 'Din deadline har sparats',
})
fetchData()
} catch (error) {
toast({
title: 'Fel',
description: 'Kunde inte skapa deadline',
variant: 'destructive',
})
throw error
}
}
const handleDeadlineToggle = async (deadline: Deadline) => {
try {
const { error } = await supabase
.from('deadlines')
.update({
is_completed: !deadline.is_completed,
completed_at: !deadline.is_completed ? new Date().toISOString() : null,
})
.eq('id', deadline.id)
if (error) throw error
toast({
title: deadline.is_completed ? 'Markerad som ej klar' : 'Markerad som klar',
})
fetchData()
} catch (error) {
toast({
title: 'Fel',
description: 'Kunde inte uppdatera deadline',
variant: 'destructive',
})
}
}
if (isLoading) {
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Kalender</h1>
</div>
<div className="animate-pulse">
<div className="h-10 bg-muted rounded w-48 mb-4" />
<div className="h-96 bg-muted rounded" />
</div>
</div>
)
}
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Kalender</h1>
</div>
<PaymentCalendar
invoices={invoices}
deadlines={deadlines}
customers={customers}
onDeadlineCreate={handleDeadlineCreate}
onDeadlineToggle={handleDeadlineToggle}
/>
</div>
)
}
+103
View File
@@ -0,0 +1,103 @@
'use client'
import { useState, useEffect, use } from 'react'
import { createClient } from '@/lib/supabase/client'
import { Campaign, Customer } from '@/types'
import { CampaignDetail, CampaignForm } from '@/components/campaigns'
import { useToast } from '@/components/ui/use-toast'
import { Skeleton } from '@/components/ui/skeleton'
interface PageProps {
params: Promise<{ id: string }>
}
export default function CampaignDetailPage({ params }: PageProps) {
const { id } = use(params)
const supabase = createClient()
const { toast } = useToast()
const [campaign, setCampaign] = useState<Campaign | null>(null)
const [customers, setCustomers] = useState<Customer[]>([])
const [loading, setLoading] = useState(true)
const [editFormOpen, setEditFormOpen] = useState(false)
const fetchCampaign = async () => {
try {
const response = await fetch(`/api/campaigns/${id}`)
if (response.ok) {
const { data } = await response.json()
setCampaign(data)
} else {
toast({
title: 'Fel',
description: 'Samarbetet hittades inte',
variant: 'destructive',
})
}
} catch (error) {
toast({
title: 'Fel',
description: 'Kunde inte ladda samarbetet',
variant: 'destructive',
})
} finally {
setLoading(false)
}
}
const fetchCustomers = async () => {
const { data } = await supabase
.from('customers')
.select('*')
.order('name')
setCustomers(data || [])
}
useEffect(() => {
fetchCampaign()
fetchCustomers()
}, [id])
if (loading) {
return (
<div className="space-y-6">
<Skeleton className="h-10 w-64" />
<Skeleton className="h-6 w-48" />
<div className="grid gap-4 md:grid-cols-4">
{[1, 2, 3, 4].map(i => (
<Skeleton key={i} className="h-24" />
))}
</div>
<Skeleton className="h-96" />
</div>
)
}
if (!campaign) {
return (
<div className="text-center py-12">
<p className="text-muted-foreground">Samarbetet hittades inte</p>
</div>
)
}
return (
<>
<CampaignDetail
campaign={campaign}
onUpdate={fetchCampaign}
onEdit={() => setEditFormOpen(true)}
/>
<CampaignForm
open={editFormOpen}
onOpenChange={setEditFormOpen}
initialData={campaign}
customers={customers}
onSuccess={() => {
setEditFormOpen(false)
fetchCampaign()
}}
/>
</>
)
}
+40
View File
@@ -0,0 +1,40 @@
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import { ContractImportWizard } from '@/components/contracts/ContractImportWizard'
export const metadata = {
title: 'Importera avtal | Samarbeten',
description: 'Importera och analysera avtal med AI',
}
export default async function CampaignImportPage() {
const supabase = await createClient()
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) {
redirect('/login')
}
// Fetch customers for matching
const { data: customers } = await supabase
.from('customers')
.select('*')
.eq('user_id', user.id)
.order('name')
return (
<div className="container max-w-6xl py-8">
<div className="mb-8">
<h1 className="text-2xl font-semibold tracking-tight">Importera avtal</h1>
<p className="text-muted-foreground mt-1">
Ladda upp ett avtal och låt AI extrahera samarbetsinformation automatiskt
</p>
</div>
<ContractImportWizard customers={customers || []} />
</div>
)
}
+351
View File
@@ -0,0 +1,351 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { createClient } from '@/lib/supabase/client'
import { Customer, CreateCampaignInput, CampaignType, BillingFrequency } from '@/types'
import {
CAMPAIGN_TYPE_LABELS,
BILLING_FREQUENCY_LABELS,
} from '@/types'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { useToast } from '@/components/ui/use-toast'
import { ArrowLeft } from 'lucide-react'
import Link from 'next/link'
const CURRENCIES = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
export default function NewCampaignPage() {
const router = useRouter()
const supabase = createClient()
const { toast } = useToast()
const [customers, setCustomers] = useState<Customer[]>([])
const [isLoading, setIsLoading] = useState(false)
const [formData, setFormData] = useState<CreateCampaignInput>({
name: '',
description: '',
customer_id: '',
brand_name: '',
campaign_type: 'influencer',
total_value: undefined,
currency: 'SEK',
vat_included: false,
payment_terms: 30,
billing_frequency: undefined,
publication_date: '',
draft_deadline: '',
notes: '',
})
useEffect(() => {
const fetchCustomers = async () => {
const { data } = await supabase
.from('customers')
.select('*')
.order('name')
setCustomers(data || [])
}
fetchCustomers()
}, [])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name) {
toast({ title: 'Namn krävs', variant: 'destructive' })
return
}
setIsLoading(true)
try {
const response = await fetch('/api/campaigns', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...formData,
customer_id: formData.customer_id || null,
brand_name: formData.brand_name || null,
total_value: formData.total_value || null,
payment_terms: formData.payment_terms || null,
billing_frequency: formData.billing_frequency || null,
publication_date: formData.publication_date || null,
draft_deadline: formData.draft_deadline || null,
}),
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.error || 'Failed to create campaign')
}
const { data } = await response.json()
toast({
title: 'Samarbete skapat',
description: formData.name,
})
router.push(`/campaigns/${data.id}`)
} catch (error) {
toast({
title: 'Fel',
description: error instanceof Error ? error.message : 'Något gick fel',
variant: 'destructive',
})
} finally {
setIsLoading(false)
}
}
return (
<div className="max-w-2xl mx-auto space-y-6">
<div>
<Link
href="/campaigns"
className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-2"
>
<ArrowLeft className="h-4 w-4" />
Tillbaka till samarbeten
</Link>
<h1 className="text-2xl font-bold">Nytt samarbete</h1>
<p className="text-muted-foreground">
Skapa ett nytt samarbete för att spåra innehåll, avtal och betalningar
</p>
</div>
<form onSubmit={handleSubmit}>
<Card>
<CardHeader>
<CardTitle>Grundläggande information</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label htmlFor="name">Namn på samarbete *</Label>
<Input
id="name"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="T.ex. Sommarkampanj 2025"
required
/>
</div>
<div>
<Label htmlFor="description">Beskrivning</Label>
<Textarea
id="description"
value={formData.description || ''}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Kort beskrivning av kampanjen..."
rows={2}
/>
</div>
<div>
<Label htmlFor="brand_name">Varumärke</Label>
<Input
id="brand_name"
value={formData.brand_name || ''}
onChange={(e) => setFormData({ ...formData, brand_name: e.target.value })}
placeholder="T.ex. Nike, Adidas..."
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="campaign_type">Typ</Label>
<Select
value={formData.campaign_type}
onValueChange={(v) => setFormData({ ...formData, campaign_type: v as CampaignType })}
>
<SelectTrigger>
<SelectValue placeholder="Välj typ" />
</SelectTrigger>
<SelectContent>
{Object.entries(CAMPAIGN_TYPE_LABELS).map(([value, label]) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="customer_id">Byrå / Uppdragsgivare</Label>
<Select
value={formData.customer_id || ''}
onValueChange={(v) => setFormData({
...formData,
customer_id: v,
})}
>
<SelectTrigger>
<SelectValue placeholder="Välj kund" />
</SelectTrigger>
<SelectContent>
{customers.map((customer) => (
<SelectItem key={customer.id} value={customer.id}>
{customer.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</CardContent>
</Card>
<Card className="mt-4">
<CardHeader>
<CardTitle>Ekonomi</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-3 gap-4">
<div>
<Label htmlFor="total_value">Totalvärde</Label>
<Input
id="total_value"
type="number"
value={formData.total_value || ''}
onChange={(e) => setFormData({
...formData,
total_value: e.target.value ? parseFloat(e.target.value) : undefined
})}
placeholder="0"
/>
</div>
<div>
<Label htmlFor="currency">Valuta</Label>
<Select
value={formData.currency}
onValueChange={(v) => setFormData({ ...formData, currency: v })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{CURRENCIES.map((c) => (
<SelectItem key={c} value={c}>{c}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-end gap-2 pb-2">
<Switch
id="vat_included"
checked={formData.vat_included}
onCheckedChange={(v) => setFormData({ ...formData, vat_included: v })}
/>
<Label htmlFor="vat_included" className="font-normal">Inkl. moms</Label>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="payment_terms">Betalningsvillkor (dagar)</Label>
<Input
id="payment_terms"
type="number"
value={formData.payment_terms || ''}
onChange={(e) => setFormData({
...formData,
payment_terms: e.target.value ? parseInt(e.target.value) : undefined
})}
placeholder="30"
/>
</div>
<div>
<Label htmlFor="billing_frequency">Faktureringsmodell</Label>
<Select
value={formData.billing_frequency || ''}
onValueChange={(v) => setFormData({
...formData,
billing_frequency: v as BillingFrequency || undefined
})}
>
<SelectTrigger>
<SelectValue placeholder="Välj..." />
</SelectTrigger>
<SelectContent>
{Object.entries(BILLING_FREQUENCY_LABELS).map(([value, label]) => (
<SelectItem key={value} value={value}>
{label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</CardContent>
</Card>
<Card className="mt-4">
<CardHeader>
<CardTitle>Datum</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="publication_date">Publiceringsdatum</Label>
<Input
id="publication_date"
type="date"
value={formData.publication_date || ''}
onChange={(e) => setFormData({ ...formData, publication_date: e.target.value })}
/>
</div>
<div>
<Label htmlFor="draft_deadline">Utkastdeadline</Label>
<Input
id="draft_deadline"
type="date"
value={formData.draft_deadline || ''}
onChange={(e) => setFormData({ ...formData, draft_deadline: e.target.value })}
/>
</div>
</div>
<div>
<Label htmlFor="notes">Anteckningar</Label>
<Textarea
id="notes"
value={formData.notes || ''}
onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
placeholder="Interna anteckningar..."
rows={3}
/>
</div>
</CardContent>
</Card>
<div className="flex justify-end gap-3 mt-6">
<Link href="/campaigns">
<Button type="button" variant="outline">Avbryt</Button>
</Link>
<Button type="submit" disabled={isLoading}>
{isLoading ? 'Skapar...' : 'Skapa samarbete'}
</Button>
</div>
</form>
</div>
)
}
+85
View File
@@ -0,0 +1,85 @@
'use client'
import { useState, useEffect } from 'react'
import { createClient } from '@/lib/supabase/client'
import { Campaign, Customer } from '@/types'
import { CampaignList, CampaignForm } from '@/components/campaigns'
import { useToast } from '@/components/ui/use-toast'
import { PageHeader } from '@/components/ui/page-header'
import { Button } from '@/components/ui/button'
import { Plus, FileUp } from 'lucide-react'
import { useRouter } from 'next/navigation'
export default function CampaignsPage() {
const supabase = createClient()
const router = useRouter()
const { toast } = useToast()
const [campaigns, setCampaigns] = useState<Campaign[]>([])
const [customers, setCustomers] = useState<Customer[]>([])
const [loading, setLoading] = useState(true)
const [formOpen, setFormOpen] = useState(false)
const fetchData = async () => {
try {
// Fetch campaigns
const campaignsResponse = await fetch('/api/campaigns')
if (campaignsResponse.ok) {
const { data } = await campaignsResponse.json()
setCampaigns(data || [])
}
// Fetch customers for the form
const { data: customersData } = await supabase
.from('customers')
.select('*')
.order('name')
setCustomers(customersData || [])
} catch (error) {
toast({
title: 'Fel',
description: 'Kunde inte ladda data',
variant: 'destructive',
})
} finally {
setLoading(false)
}
}
useEffect(() => {
fetchData()
}, [])
return (
<div className="space-y-6">
<PageHeader
title="Samarbeten"
description="Hantera dina samarbeten, innehåll och avtal"
action={
<div className="flex gap-2">
<Button onClick={() => setFormOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
Skapa samarbete
</Button>
<Button variant="outline" onClick={() => router.push('/campaigns/import')}>
<FileUp className="mr-2 h-4 w-4" />
Importera avtal
</Button>
</div>
}
/>
<CampaignList campaigns={campaigns} loading={loading} />
<CampaignForm
open={formOpen}
onOpenChange={setFormOpen}
customers={customers}
onSuccess={() => {
setFormOpen(false)
fetchData()
}}
/>
</div>
)
}
+445
View File
@@ -0,0 +1,445 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { use } from 'react'
import Link from 'next/link'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import CustomerForm from '@/components/customers/CustomerForm'
import { CampaignStatusBadge } from '@/components/campaigns/CampaignStatusBadge'
import {
ArrowLeft,
Building,
Globe,
User,
Mail,
Phone,
MapPin,
Edit2,
Trash2,
FileText,
Loader2,
Receipt,
Briefcase,
} from 'lucide-react'
import type { Customer, CustomerType, CreateCustomerInput, CampaignStatus } from '@/types'
const customerTypeLabels: Record<CustomerType, string> = {
individual: 'Privatperson',
swedish_business: 'Svenskt foretag',
eu_business: 'EU-foretag',
non_eu_business: 'Utanfor EU',
}
const customerTypeIcons: Record<CustomerType, React.ElementType> = {
individual: User,
swedish_business: Building,
eu_business: Globe,
non_eu_business: Globe,
}
interface RelatedCampaign {
id: string
name: string
status: CampaignStatus
total_value: number | null
currency: string | null
publication_date: string | null
brand_name: string | null
}
interface RelatedInvoice {
id: string
invoice_number: string
invoice_date: string
due_date: string
status: string
total: number
currency: string
payment_status: string
}
interface CustomerWithRelations extends Customer {
campaigns: RelatedCampaign[]
invoices: RelatedInvoice[]
}
export default function CustomerDetailPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = use(params)
const router = useRouter()
const { toast } = useToast()
const [customer, setCustomer] = useState<CustomerWithRelations | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [isEditOpen, setIsEditOpen] = useState(false)
const [isUpdating, setIsUpdating] = useState(false)
useEffect(() => {
fetchCustomer()
}, [id])
async function fetchCustomer() {
setIsLoading(true)
try {
const response = await fetch(`/api/customers/${id}`)
if (!response.ok) {
throw new Error('Not found')
}
const { data } = await response.json()
setCustomer(data)
} catch {
toast({
title: 'Fel',
description: 'Kunde inte hitta kunden',
variant: 'destructive',
})
router.push('/customers')
} finally {
setIsLoading(false)
}
}
async function handleUpdate(data: CreateCustomerInput) {
setIsUpdating(true)
try {
const response = await fetch(`/api/customers/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
if (!response.ok) {
throw new Error('Update failed')
}
toast({
title: 'Kund uppdaterad',
description: data.name,
})
setIsEditOpen(false)
fetchCustomer()
} catch {
toast({
title: 'Fel',
description: 'Kunde inte uppdatera kunden',
variant: 'destructive',
})
} finally {
setIsUpdating(false)
}
}
async function handleDelete() {
if (!customer) return
if (!confirm(`Ta bort "${customer.name}"? Detta kan inte angras.`)) return
try {
const response = await fetch(`/api/customers/${id}`, {
method: 'DELETE',
})
if (!response.ok) {
throw new Error('Delete failed')
}
toast({
title: 'Kund borttagen',
description: customer.name,
})
router.push('/customers')
} catch {
toast({
title: 'Fel',
description: 'Kunde inte ta bort kunden',
variant: 'destructive',
})
}
}
const formatCurrency = (amount: number | null, currency: string | null) => {
if (!amount) return '-'
return new Intl.NumberFormat('sv-SE', {
style: 'currency',
currency: currency || 'SEK',
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(amount)
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
)
}
if (!customer) return null
const Icon = customerTypeIcons[customer.customer_type]
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-start justify-between gap-4">
<div>
<Link
href="/customers"
className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-2"
>
<ArrowLeft className="h-4 w-4" />
Tillbaka till kunder
</Link>
<div className="flex items-center gap-3">
<div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
<Icon className="h-6 w-6 text-primary" />
</div>
<div>
<h1 className="text-3xl font-bold tracking-tight">{customer.name}</h1>
<Badge variant="secondary">{customerTypeLabels[customer.customer_type]}</Badge>
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => setIsEditOpen(true)}>
<Edit2 className="h-4 w-4 mr-1" />
Redigera
</Button>
<Button
variant="outline"
size="sm"
onClick={handleDelete}
className="text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4 mr-1" />
Ta bort
</Button>
</div>
</div>
{/* Info cards */}
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{/* Contact */}
<Card>
<CardHeader>
<CardTitle className="text-base">Kontaktuppgifter</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{customer.email && (
<div className="flex items-center gap-2 text-sm">
<Mail className="h-4 w-4 text-muted-foreground" />
<a href={`mailto:${customer.email}`} className="hover:underline">
{customer.email}
</a>
</div>
)}
{customer.phone && (
<div className="flex items-center gap-2 text-sm">
<Phone className="h-4 w-4 text-muted-foreground" />
{customer.phone}
</div>
)}
{(customer.address_line1 || customer.city) && (
<div className="flex items-start gap-2 text-sm">
<MapPin className="h-4 w-4 text-muted-foreground mt-0.5" />
<div>
{customer.address_line1 && <p>{customer.address_line1}</p>}
{customer.address_line2 && <p>{customer.address_line2}</p>}
{(customer.postal_code || customer.city) && (
<p>{[customer.postal_code, customer.city].filter(Boolean).join(' ')}</p>
)}
{customer.country && <p>{customer.country}</p>}
</div>
</div>
)}
{!customer.email && !customer.phone && !customer.address_line1 && !customer.city && (
<p className="text-sm text-muted-foreground">Inga kontaktuppgifter</p>
)}
</CardContent>
</Card>
{/* Business details */}
<Card>
<CardHeader>
<CardTitle className="text-base">Foretagsuppgifter</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{customer.org_number && (
<div className="text-sm">
<span className="text-muted-foreground">Org.nr: </span>
{customer.org_number}
</div>
)}
{customer.vat_number && (
<div className="text-sm flex items-center gap-2">
<span className="text-muted-foreground">VAT: </span>
{customer.vat_number}
{customer.vat_number_validated && (
<Badge variant="success" className="text-xs">Verifierad</Badge>
)}
</div>
)}
<div className="text-sm">
<span className="text-muted-foreground">Betalningsvillkor: </span>
{customer.default_payment_terms || 30} dagar
</div>
{!customer.org_number && !customer.vat_number && (
<p className="text-sm text-muted-foreground">Inga foretagsuppgifter</p>
)}
</CardContent>
</Card>
{/* Summary */}
<Card>
<CardHeader>
<CardTitle className="text-base">Oversikt</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-center gap-2 text-sm">
<Briefcase className="h-4 w-4 text-muted-foreground" />
<span>{customer.campaigns?.length || 0} samarbeten</span>
</div>
<div className="flex items-center gap-2 text-sm">
<Receipt className="h-4 w-4 text-muted-foreground" />
<span>{customer.invoices?.length || 0} fakturor</span>
</div>
</CardContent>
</Card>
</div>
{/* Notes */}
{customer.notes && (
<Card>
<CardHeader>
<CardTitle className="text-base">Anteckningar</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground whitespace-pre-wrap">{customer.notes}</p>
</CardContent>
</Card>
)}
{/* Related campaigns */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Briefcase className="h-4 w-4" />
Samarbeten
{customer.campaigns?.length > 0 && (
<Badge variant="secondary">{customer.campaigns.length}</Badge>
)}
</CardTitle>
</CardHeader>
<CardContent>
{customer.campaigns?.length > 0 ? (
<div className="space-y-2">
{customer.campaigns.map((campaign) => (
<Link
key={campaign.id}
href={`/campaigns/${campaign.id}`}
className="flex items-center justify-between p-3 rounded-lg border hover:bg-muted/50 transition-colors"
>
<div>
<p className="font-medium">{campaign.name}</p>
{campaign.brand_name && (
<p className="text-sm text-muted-foreground">{campaign.brand_name}</p>
)}
</div>
<div className="flex items-center gap-3">
<span className="text-sm tabular-nums">
{formatCurrency(campaign.total_value, campaign.currency)}
</span>
<CampaignStatusBadge status={campaign.status} />
</div>
</Link>
))}
</div>
) : (
<p className="text-sm text-muted-foreground text-center py-4">
Inga samarbeten kopplade till denna kund
</p>
)}
</CardContent>
</Card>
{/* Related invoices */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Receipt className="h-4 w-4" />
Fakturor
{customer.invoices?.length > 0 && (
<Badge variant="secondary">{customer.invoices.length}</Badge>
)}
</CardTitle>
</CardHeader>
<CardContent>
{customer.invoices?.length > 0 ? (
<div className="space-y-2">
{customer.invoices.map((invoice) => (
<Link
key={invoice.id}
href={`/invoices/${invoice.id}`}
className="flex items-center justify-between p-3 rounded-lg border hover:bg-muted/50 transition-colors"
>
<div>
<p className="font-medium">{invoice.invoice_number}</p>
<p className="text-sm text-muted-foreground">{invoice.invoice_date}</p>
</div>
<div className="flex items-center gap-3">
<span className="text-sm tabular-nums">
{formatCurrency(invoice.total, invoice.currency)}
</span>
<Badge variant={invoice.payment_status === 'paid' ? 'success' : 'secondary'}>
{invoice.payment_status === 'paid' ? 'Betald' : invoice.payment_status === 'overdue' ? 'Forsenad' : 'Obestallt'}
</Badge>
</div>
</Link>
))}
</div>
) : (
<p className="text-sm text-muted-foreground text-center py-4">
Inga fakturor kopplade till denna kund
</p>
)}
</CardContent>
</Card>
{/* Edit dialog */}
<Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Redigera kund</DialogTitle>
</DialogHeader>
<CustomerForm
onSubmit={handleUpdate}
isLoading={isUpdating}
initialData={{
name: customer.name,
customer_type: customer.customer_type,
email: customer.email || undefined,
phone: customer.phone || undefined,
address_line1: customer.address_line1 || undefined,
address_line2: customer.address_line2 || undefined,
postal_code: customer.postal_code || undefined,
city: customer.city || undefined,
country: customer.country || undefined,
org_number: customer.org_number || undefined,
vat_number: customer.vat_number || undefined,
default_payment_terms: customer.default_payment_terms || undefined,
notes: customer.notes || undefined,
}}
/>
</DialogContent>
</Dialog>
</div>
)
}
+217
View File
@@ -0,0 +1,217 @@
'use client'
import { useState, useEffect } from 'react'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { Plus, Search, Users, Building, Globe, User } from 'lucide-react'
import CustomerForm from '@/components/customers/CustomerForm'
import { EmptyCustomers } from '@/components/ui/empty-state'
import Link from 'next/link'
import type { Customer, CustomerType, CreateCustomerInput } from '@/types'
const customerTypeLabels: Record<CustomerType, string> = {
individual: 'Privatperson',
swedish_business: 'Svenskt företag',
eu_business: 'EU-företag',
non_eu_business: 'Utanför EU',
}
const customerTypeIcons: Record<CustomerType, React.ElementType> = {
individual: User,
swedish_business: Building,
eu_business: Globe,
non_eu_business: Globe,
}
export default function CustomersPage() {
const [customers, setCustomers] = useState<Customer[]>([])
const [isLoading, setIsLoading] = useState(true)
const [searchTerm, setSearchTerm] = useState('')
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [isCreating, setIsCreating] = useState(false)
const { toast } = useToast()
const supabase = createClient()
useEffect(() => {
fetchCustomers()
}, [])
async function fetchCustomers() {
setIsLoading(true)
const { data, error } = await supabase
.from('customers')
.select('*')
.order('name', { ascending: true })
if (error) {
toast({
title: 'Fel',
description: 'Kunde inte hämta kunder',
variant: 'destructive',
})
} else {
setCustomers(data || [])
}
setIsLoading(false)
}
async function handleCreateCustomer(data: CreateCustomerInput) {
setIsCreating(true)
const response = await fetch('/api/customers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
const result = await response.json()
if (!response.ok) {
toast({
title: 'Fel',
description: result.error || 'Kunde inte skapa kund',
variant: 'destructive',
})
} else {
toast({
title: 'Kund skapad',
description: `${data.name} har lagts till`,
})
setCustomers([...customers, result.data])
setIsDialogOpen(false)
}
setIsCreating(false)
}
const filteredCustomers = customers.filter((customer) =>
customer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
customer.email?.toLowerCase().includes(searchTerm.toLowerCase()) ||
customer.org_number?.includes(searchTerm)
)
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Kunder</h1>
<p className="text-muted-foreground">
Hantera dina kunder och deras faktureringsuppgifter
</p>
</div>
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="mr-2 h-4 w-4" />
Ny kund
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Lägg till kund</DialogTitle>
</DialogHeader>
<CustomerForm
onSubmit={handleCreateCustomer}
isLoading={isCreating}
/>
</DialogContent>
</Dialog>
</div>
{/* Search */}
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Sök på namn, e-post eller org.nr..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div>
{/* Customer list */}
{isLoading ? (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{[1, 2, 3].map((i) => (
<Card key={i} className="animate-pulse">
<CardHeader>
<div className="h-5 bg-muted rounded w-1/2" />
<div className="h-4 bg-muted rounded w-1/3 mt-2" />
</CardHeader>
<CardContent>
<div className="h-4 bg-muted rounded w-full" />
</CardContent>
</Card>
))}
</div>
) : filteredCustomers.length === 0 ? (
<Card>
<CardContent>
{searchTerm ? (
<div className="flex flex-col items-center justify-center py-12">
<Users className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-medium">Inga träffar</h3>
<p className="text-muted-foreground text-center mt-1">
Inga kunder matchar "{searchTerm}"
</p>
</div>
) : (
<EmptyCustomers />
)}
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{filteredCustomers.map((customer) => {
const Icon = customerTypeIcons[customer.customer_type]
return (
<Link key={customer.id} href={`/customers/${customer.id}`}>
<Card className="hover:border-primary/50 transition-colors cursor-pointer h-full">
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex items-center gap-3">
<div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center">
<Icon className="h-5 w-5 text-primary" />
</div>
<div>
<CardTitle className="text-base">{customer.name}</CardTitle>
<CardDescription>{customer.email || 'Ingen e-post'}</CardDescription>
</div>
</div>
<Badge variant="secondary">
{customerTypeLabels[customer.customer_type]}
</Badge>
</div>
</CardHeader>
<CardContent>
<div className="text-sm text-muted-foreground space-y-1">
{customer.org_number && (
<p>Org.nr: {customer.org_number}</p>
)}
{customer.vat_number && (
<p className="flex items-center gap-1">
VAT: {customer.vat_number}
{customer.vat_number_validated && (
<Badge variant="success" className="text-xs">Verifierad</Badge>
)}
</p>
)}
{customer.city && (
<p>{customer.city}, {customer.country}</p>
)}
</div>
</CardContent>
</Card>
</Link>
)
})}
</div>
)}
</div>
)
}
+379
View File
@@ -0,0 +1,379 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { createClient } from '@/lib/supabase/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useToast } from '@/components/ui/use-toast'
import { formatCurrency, formatDate } from '@/lib/utils'
import {
getSchablonavdragSummary,
groupMileageEntriesByMonth,
formatMonthKey,
SCHABLONAVDRAG_RATES,
} from '@/lib/tax/schablonavdrag'
import SchablonavdragSettings from '@/components/settings/SchablonavdragSettings'
import MileageEntry from '@/components/transactions/MileageEntry'
import {
Loader2,
Home,
Car,
Plus,
Trash2,
Calendar,
MapPin,
ChevronDown,
ChevronUp,
} from 'lucide-react'
import type {
CompanySettings,
SchablonavdragSettings as SchablonavdragSettingsType,
MileageEntry as MileageEntryType,
CreateMileageEntryInput,
} from '@/types'
export default function DeductionsPage() {
const router = useRouter()
const { toast } = useToast()
const supabase = createClient()
const [isLoading, setIsLoading] = useState(true)
const [settings, setSettings] = useState<CompanySettings | null>(null)
const [mileageEntries, setMileageEntries] = useState<MileageEntryType[]>([])
const [showAddForm, setShowAddForm] = useState(false)
const [expandedMonths, setExpandedMonths] = useState<Set<string>>(new Set())
useEffect(() => {
fetchData()
}, [])
async function fetchData() {
setIsLoading(true)
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) {
router.push('/login')
return
}
// Fetch settings
const { data: settingsData } = await supabase
.from('company_settings')
.select('*')
.eq('user_id', user.id)
.single()
setSettings(settingsData)
// Fetch mileage entries for current year
const startOfYear = new Date(new Date().getFullYear(), 0, 1).toISOString().split('T')[0]
const { data: entries } = await supabase
.from('mileage_entries')
.select('*')
.eq('user_id', user.id)
.gte('date', startOfYear)
.order('date', { ascending: false })
setMileageEntries(entries || [])
setIsLoading(false)
}
async function handleSaveSettings(newSettings: SchablonavdragSettingsType) {
if (!settings) return
const { error } = await supabase
.from('company_settings')
.update({ schablonavdrag_settings: newSettings })
.eq('id', settings.id)
if (error) {
throw error
}
setSettings({
...settings,
schablonavdrag_settings: newSettings,
} as CompanySettings & { schablonavdrag_settings: SchablonavdragSettingsType })
}
async function handleAddMileageEntry(entry: CreateMileageEntryInput) {
const {
data: { user },
} = await supabase.auth.getUser()
if (!user) return
const { data, error } = await supabase
.from('mileage_entries')
.insert({
user_id: user.id,
date: entry.date,
distance_km: entry.distance_km,
purpose: entry.purpose,
from_location: entry.from_location || null,
to_location: entry.to_location || null,
})
.select()
.single()
if (error) {
throw error
}
setMileageEntries([data, ...mileageEntries])
setShowAddForm(false)
}
async function handleDeleteMileageEntry(id: string) {
const { error } = await supabase.from('mileage_entries').delete().eq('id', id)
if (error) {
toast({
title: 'Fel',
description: 'Kunde inte ta bort körningen',
variant: 'destructive',
})
return
}
setMileageEntries(mileageEntries.filter((e) => e.id !== id))
toast({
title: 'Borttaget',
description: 'Körningen har tagits bort',
})
}
function toggleMonth(monthKey: string) {
const newExpanded = new Set(expandedMonths)
if (newExpanded.has(monthKey)) {
newExpanded.delete(monthKey)
} else {
newExpanded.add(monthKey)
}
setExpandedMonths(newExpanded)
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
)
}
// Get schablonavdrag settings
const schablonavdragSettings = ((settings as CompanySettings & { schablonavdrag_settings?: SchablonavdragSettingsType })?.schablonavdrag_settings) || {
hemmakontor_enabled: false,
bil_enabled: false,
}
// Calculate summary
const currentYear = new Date().getFullYear()
const currentMonth = new Date().getMonth() + 1
const summary = getSchablonavdragSummary(
schablonavdragSettings,
mileageEntries,
currentYear,
currentMonth
)
// Group mileage entries by month
const entriesByMonth = groupMileageEntriesByMonth(mileageEntries)
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Schablonavdrag</h1>
<p className="text-muted-foreground">
Hantera dina schablonmässiga avdrag för hemmakontor och bilkostnader
</p>
</div>
{/* Summary cards */}
<div className="grid gap-4 md:grid-cols-3">
{/* Total deduction */}
<Card className="bg-gradient-to-br from-success/10 via-success/5 to-background border-success/20">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground">
Totalt avdrag {currentYear}
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold text-success">
{formatCurrency(summary.total_deduction)}
</div>
</CardContent>
</Card>
{/* Hemmakontor */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<Home className="h-4 w-4" />
Hemmakontor
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{summary.hemmakontor.enabled ? formatCurrency(summary.hemmakontor.deduction) : '-'}
</div>
{summary.hemmakontor.enabled && (
<p className="text-xs text-muted-foreground">
{summary.hemmakontor.months_active} månader
</p>
)}
</CardContent>
</Card>
{/* Bilkostnader */}
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium text-muted-foreground flex items-center gap-2">
<Car className="h-4 w-4" />
Bilkostnader
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">
{summary.mileage.enabled ? formatCurrency(summary.mileage.total_deduction) : '-'}
</div>
{summary.mileage.enabled && summary.mileage.total_km > 0 && (
<p className="text-xs text-muted-foreground">
{summary.mileage.total_km.toFixed(0)} km loggade
</p>
)}
</CardContent>
</Card>
</div>
<Tabs defaultValue="settings" className="space-y-6">
<TabsList>
<TabsTrigger value="settings">Inställningar</TabsTrigger>
<TabsTrigger value="mileage" disabled={!schablonavdragSettings.bil_enabled}>
Körjournal
{schablonavdragSettings.bil_enabled && mileageEntries.length > 0 && (
<Badge variant="secondary" className="ml-2">
{mileageEntries.length}
</Badge>
)}
</TabsTrigger>
</TabsList>
{/* Settings tab */}
<TabsContent value="settings">
<SchablonavdragSettings
settings={schablonavdragSettings}
onSave={handleSaveSettings}
/>
</TabsContent>
{/* Mileage log tab */}
<TabsContent value="mileage" className="space-y-6">
{/* Add new entry button/form */}
{showAddForm ? (
<MileageEntry onSave={handleAddMileageEntry} onCancel={() => setShowAddForm(false)} />
) : (
<Button onClick={() => setShowAddForm(true)}>
<Plus className="mr-2 h-4 w-4" />
Ny körning
</Button>
)}
{/* Entries list grouped by month */}
{mileageEntries.length === 0 ? (
<Card>
<CardContent className="pt-6 text-center">
<Car className="mx-auto h-12 w-12 text-muted-foreground/50" />
<h3 className="mt-4 text-lg font-medium">Ingen körning loggad</h3>
<p className="mt-2 text-sm text-muted-foreground">
Börja logga dina tjänsteresor för att få milersättning
</p>
</CardContent>
</Card>
) : (
<div className="space-y-4">
{Array.from(entriesByMonth.entries()).map(([monthKey, monthData]) => (
<Card key={monthKey}>
<CardHeader
className="cursor-pointer"
onClick={() => toggleMonth(monthKey)}
>
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-base">
{formatMonthKey(monthKey)}
</CardTitle>
<CardDescription>
{monthData.entries.length} körningar · {monthData.totalKm.toFixed(0)} km
</CardDescription>
</div>
<div className="flex items-center gap-4">
<span className="text-lg font-medium text-success">
{formatCurrency(monthData.totalDeduction)}
</span>
{expandedMonths.has(monthKey) ? (
<ChevronUp className="h-5 w-5" />
) : (
<ChevronDown className="h-5 w-5" />
)}
</div>
</div>
</CardHeader>
{expandedMonths.has(monthKey) && (
<CardContent className="pt-0">
<div className="space-y-3">
{monthData.entries.map((entry) => (
<div
key={entry.id}
className="flex items-start justify-between p-3 rounded-lg border bg-muted/30"
>
<div className="space-y-1">
<div className="flex items-center gap-2 text-sm">
<Calendar className="h-3.5 w-3.5 text-muted-foreground" />
<span>{formatDate(entry.date)}</span>
<Badge variant="secondary">
{Number(entry.distance_km).toFixed(1)} km
</Badge>
</div>
<p className="text-sm">{entry.purpose}</p>
{(entry.from_location || entry.to_location) && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<MapPin className="h-3 w-3" />
{entry.from_location && entry.to_location
? `${entry.from_location} → ${entry.to_location}`
: entry.from_location || entry.to_location}
</div>
)}
</div>
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-success">
{formatCurrency(Number(entry.total_deduction))}
</span>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
onClick={() => handleDeleteMileageEntry(entry.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
</CardContent>
)}
</Card>
))}
</div>
)}
</TabsContent>
</Tabs>
</div>
)
}
+366
View File
@@ -0,0 +1,366 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Skeleton } from '@/components/ui/skeleton'
import { useToast } from '@/components/ui/use-toast'
import GiftForm from '@/components/benefits/GiftForm'
import GiftList from '@/components/benefits/GiftList'
import { formatCurrency } from '@/lib/utils'
import { Plus, Gift, TrendingUp, CheckCircle, Receipt, AlertTriangle } from 'lucide-react'
import type { Gift as GiftType, GiftSummary, CreateGiftInput, EntityType } from '@/types'
export default function GiftsPage() {
const router = useRouter()
const searchParams = useSearchParams()
const { toast } = useToast()
// State
const [gifts, setGifts] = useState<GiftType[]>([])
const [summary, setSummary] = useState<GiftSummary | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [isSubmitting, setIsSubmitting] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [entityType, setEntityType] = useState<EntityType>('enskild_firma')
const isLightMode = entityType === 'light'
// Dialog state
const [isFormOpen, setIsFormOpen] = useState(false)
const [editingGift, setEditingGift] = useState<GiftType | null>(null)
// Year filter
const currentYear = new Date().getFullYear()
const [selectedYear, setSelectedYear] = useState(
searchParams.get('year') || currentYear.toString()
)
const years = Array.from({ length: 5 }, (_, i) => currentYear - i)
// Fetch gifts and summary
const fetchData = useCallback(async () => {
setIsLoading(true)
try {
const [giftsRes, summaryRes, settingsRes] = await Promise.all([
fetch(`/api/gifts?year=${selectedYear}`),
fetch(`/api/gifts/summary?year=${selectedYear}`),
fetch('/api/settings'),
])
if (giftsRes.ok) {
const giftsData = await giftsRes.json()
setGifts(giftsData.data || [])
}
if (summaryRes.ok) {
const summaryData = await summaryRes.json()
setSummary(summaryData.data || null)
}
if (settingsRes.ok) {
const settingsData = await settingsRes.json()
if (settingsData.data?.entity_type) {
setEntityType(settingsData.data.entity_type as EntityType)
}
}
} catch (error) {
console.error('Failed to fetch gifts:', error)
toast({
title: 'Fel',
description: 'Kunde inte hämta gåvor',
variant: 'destructive',
})
} finally {
setIsLoading(false)
}
}, [selectedYear, toast])
useEffect(() => {
fetchData()
}, [fetchData])
// Update URL when year changes
const handleYearChange = (year: string) => {
setSelectedYear(year)
router.push(`/gifts?year=${year}`)
}
// Handle form submit (create or update)
const handleSubmit = async (data: CreateGiftInput) => {
setIsSubmitting(true)
try {
const url = editingGift ? `/api/gifts/${editingGift.id}` : '/api/gifts'
const method = editingGift ? 'PUT' : 'POST'
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
if (!res.ok) {
const error = await res.json()
throw new Error(error.error || 'Unknown error')
}
toast({
title: editingGift ? 'Gåva uppdaterad' : 'Gåva sparad',
description: `${data.description} från ${data.brand_name}`,
})
setIsFormOpen(false)
setEditingGift(null)
fetchData()
} catch (error) {
toast({
title: 'Fel',
description: error instanceof Error ? error.message : 'Kunde inte spara gåva',
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
// Handle edit
const handleEdit = (gift: GiftType) => {
setEditingGift(gift)
setIsFormOpen(true)
}
// Handle delete
const handleDelete = async (id: string) => {
setIsDeleting(true)
try {
const res = await fetch(`/api/gifts/${id}`, { method: 'DELETE' })
if (!res.ok) {
const error = await res.json()
throw new Error(error.error || 'Unknown error')
}
toast({
title: 'Gåva borttagen',
})
fetchData()
} catch (error) {
toast({
title: 'Fel',
description: error instanceof Error ? error.message : 'Kunde inte ta bort gåva',
variant: 'destructive',
})
} finally {
setIsDeleting(false)
}
}
// Handle dialog close
const handleDialogClose = (open: boolean) => {
if (!open) {
setIsFormOpen(false)
setEditingGift(null)
}
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold tracking-tight">Gåvor & Förmåner</h1>
<p className="text-muted-foreground">
Logga produkter och gåvor du fått för korrekt skattehantering
</p>
</div>
<div className="flex items-center gap-2">
<Select value={selectedYear} onValueChange={handleYearChange}>
<SelectTrigger className="w-[120px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{years.map((year) => (
<SelectItem key={year} value={year.toString()}>
{year}
</SelectItem>
))}
</SelectContent>
</Select>
<Button onClick={() => setIsFormOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
Ny gåva
</Button>
</div>
</div>
{/* Summary Cards */}
{isLoading ? (
<div className="grid gap-4 md:grid-cols-4">
{[...Array(4)].map((_, i) => (
<Card key={i}>
<CardContent className="pt-6">
<Skeleton className="h-4 w-24 mb-2" />
<Skeleton className="h-8 w-32" />
</CardContent>
</Card>
))}
</div>
) : summary ? (
<div className="grid gap-4 md:grid-cols-4">
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-2 text-muted-foreground mb-1">
<Gift className="h-4 w-4" />
<span className="text-sm">Totalt antal</span>
</div>
<p className="text-2xl font-bold">{summary.total_count}</p>
<p className="text-sm text-muted-foreground">{formatCurrency(summary.total_value)}</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-2 text-destructive mb-1">
<TrendingUp className="h-4 w-4" />
<span className="text-sm">Skattepliktig</span>
</div>
<p className="text-2xl font-bold">{summary.taxable_count}</p>
<p className="text-sm text-muted-foreground">
{formatCurrency(summary.taxable_value)}
</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-2 text-success mb-1">
<CheckCircle className="h-4 w-4" />
<span className="text-sm">Skattefria</span>
</div>
<p className="text-2xl font-bold">{summary.tax_free_count}</p>
<p className="text-sm text-muted-foreground">
{formatCurrency(summary.tax_free_value)}
</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
{isLightMode ? (
<>
<div className="flex items-center gap-2 text-warning mb-1">
<AlertTriangle className="h-4 w-4" />
<span className="text-sm">Virtuell skatteskuld</span>
</div>
<p className="text-2xl font-bold">
{formatCurrency(summary.taxable_value * 0.32)}
</p>
<p className="text-sm text-muted-foreground">
ca 32% av skattepliktiga gåvor
</p>
</>
) : (
<>
<div className="flex items-center gap-2 text-primary mb-1">
<Receipt className="h-4 w-4" />
<span className="text-sm">Avdragsgilla</span>
</div>
<p className="text-2xl font-bold">{summary.deductible_count}</p>
<p className="text-sm text-muted-foreground">
{formatCurrency(summary.deductible_value)}
</p>
</>
)}
</CardContent>
</Card>
</div>
) : null}
{/* Info Card */}
<Card className="bg-muted/50">
<CardContent className="pt-6">
<div className="flex gap-4">
<Gift className="h-8 w-8 text-primary flex-shrink-0" />
<div>
<h3 className="font-medium mb-1">Varför logga gåvor?</h3>
<p className="text-sm text-muted-foreground">
Skatteverket granskar aktivt gåvor och förmåner som influencers får. Produkter du
fått i utbyte mot att posta om dem är skattepliktiga. Genom att logga allt korrekt
undviker du skattetillägg och kan dessutom göra avdrag för produkter som endast
används i verksamheten.
</p>
</div>
</div>
</CardContent>
</Card>
{/* Gift List */}
{isLoading ? (
<div className="space-y-3">
{[...Array(3)].map((_, i) => (
<Card key={i}>
<CardContent className="pt-4">
<Skeleton className="h-6 w-48 mb-2" />
<Skeleton className="h-4 w-32" />
</CardContent>
</Card>
))}
</div>
) : (
<GiftList
gifts={gifts}
onEdit={handleEdit}
onDelete={handleDelete}
isDeleting={isDeleting}
/>
)}
{/* Form Dialog */}
<Dialog open={isFormOpen} onOpenChange={handleDialogClose}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>{editingGift ? 'Redigera gåva' : 'Lägg till ny gåva'}</DialogTitle>
<DialogDescription>
Fyll i information om produkten eller gåvan du fått
</DialogDescription>
</DialogHeader>
<GiftForm
onSubmit={handleSubmit}
initialData={
editingGift
? {
date: editingGift.date,
brand_name: editingGift.brand_name,
description: editingGift.description,
estimated_value: Number(editingGift.estimated_value),
has_motprestation: editingGift.has_motprestation,
used_in_business: editingGift.used_in_business,
used_privately: editingGift.used_privately,
is_simple_promo: editingGift.is_simple_promo,
returned: editingGift.returned,
}
: undefined
}
isLoading={isSubmitting}
isLightMode={isLightMode}
/>
</DialogContent>
</Dialog>
</div>
)
}
+428
View File
@@ -0,0 +1,428 @@
'use client'
import { useState, useMemo } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { HelpLink } from '@/components/ui/info-tooltip'
import {
Search,
BookOpen,
Receipt,
Calculator,
Building2,
FileText,
ExternalLink,
ChevronDown,
ChevronUp,
} from 'lucide-react'
import { cn } from '@/lib/utils'
interface GlossaryTerm {
term: string
simpleTerm?: string // Vardagligt alternativ
definition: string
category: 'skatt' | 'moms' | 'faktura' | 'bokföring' | 'bank' | 'företag'
skatteverketUrl?: string
relatedTerms?: string[]
}
const glossaryTerms: GlossaryTerm[] = [
// Skatt
{
term: 'F-skatt',
simpleTerm: 'Månatlig skatteinbetalning',
definition:
'F-skatt (företagsskatt) innebär att du som företagare själv ansvarar för att betala in preliminärskatt och egenavgifter. Du betalar in en fast summa varje månad baserat på din beräknade årsinkomst. Om du betalat för lite under året kan du få restskatt.',
category: 'skatt',
skatteverketUrl: 'https://www.skatteverket.se/foretag/foretagarguiden/foretagsformer/enskildnaringsverksamhet/fskatt.4.361dc8c15312eff6fd1f8a3.html',
relatedTerms: ['Preliminärskatt', 'Restskatt', 'Egenavgifter'],
},
{
term: 'Preliminärskatt',
definition:
'Skatt som betalas in i förskott under inkomståret, baserat på uppskattad årsinkomst. Din F-skatteinbetalning är en form av preliminärskatt.',
category: 'skatt',
relatedTerms: ['F-skatt', 'Restskatt'],
},
{
term: 'Egenavgifter',
simpleTerm: 'Sociala avgifter',
definition:
'Som enskild näringsidkare betalar du egenavgifter (ca 28,97%) istället för arbetsgivaravgifter. Avgifterna finansierar socialförsäkringar som pension, sjukpenning och föräldrapenning - saker som anställda får via sin arbetsgivare.',
category: 'skatt',
skatteverketUrl: 'https://www.skatteverket.se/foretag/foretagarguiden/avgifterochegenavgifter/egenavgifter.4.361dc8c15312eff6fd1e5e7.html',
relatedTerms: ['Enskild firma'],
},
{
term: 'Restskatt',
definition:
'Om du betalat in för lite preliminärskatt under året får du restskatt att betala. Det betyder att din faktiska skatt var högre än vad du betalade in via F-skatten.',
category: 'skatt',
relatedTerms: ['F-skatt', 'Preliminärskatt'],
},
{
term: 'Schablonavdrag',
simpleTerm: 'Enkla avdrag',
definition:
'Förenklade avdrag där du använder fasta belopp istället för att spara kvitton. Exempel: hemmakontor (2 000 kr/år) eller milersättning (25 kr/mil för bil). Perfekt om du inte vill krångla med att spara alla kvitton.',
category: 'skatt',
skatteverketUrl: 'https://www.skatteverket.se/privat/skatter/arbeteochinkomst/avdrag.4.6efe6285127ab4f1d25800023187.html',
relatedTerms: ['Avdrag', 'Hemmakontor'],
},
{
term: 'NE-bilaga',
definition:
'En bilaga till din inkomstdeklaration där du redovisar resultatet från din enskilda näringsverksamhet. Appen hjälper dig samla underlaget - du behöver inte förstå alla detaljer.',
category: 'skatt',
skatteverketUrl: 'https://www.skatteverket.se/privat/deklaration/blanketter/inkomstochfastighetsdeklaration/blankett21.4.6efe6285127ab4f1d25800023142.html',
relatedTerms: ['Enskild firma', 'Inkomstdeklaration'],
},
{
term: 'Disponibelt',
simpleTerm: 'Ditt att spendera',
definition:
'Det belopp du kan använda fritt efter att vi räknat bort uppskattad skatt och moms från ditt saldo. Resten bör du "låsa" för framtida skatteinbetalningar.',
category: 'skatt',
},
// Moms
{
term: 'Moms',
simpleTerm: 'Mervärdesskatt',
definition:
'Mervärdesskatt som läggs på varor och tjänster. Som momsregistrerad lägger du på moms på dina fakturor och drar av moms på dina inköp. Skillnaden betalar eller får du tillbaka från Skatteverket.',
category: 'moms',
skatteverketUrl: 'https://www.skatteverket.se/foretag/moms.4.65fc817e1077c25b8328000206.html',
relatedTerms: ['Momsperiod', 'Ingående moms', 'Utgående moms'],
},
{
term: 'Momsperiod',
simpleTerm: 'Hur ofta du rapporterar moms',
definition:
'Hur ofta du redovisar och betalar moms till Skatteverket. Vanligast är kvartal (4 gånger/år). Osäker? Börja med kvartal - du kan ändra senare. Omsättning under 1 miljon = år möjlig, över 40 miljoner = månad krävs.',
category: 'moms',
relatedTerms: ['Moms', 'Momsdeklaration'],
},
{
term: 'Omvänd skattskyldighet',
simpleTerm: 'Kunden betalar momsen',
definition:
'När du säljer till företag i andra EU-länder betalar köparen momsen i sitt eget land. Du fakturerar 0% moms och skriver "Omvänd skattskyldighet" eller "Reverse charge" på fakturan.',
category: 'moms',
skatteverketUrl: 'https://www.skatteverket.se/foretag/moms/saljavarortjanster/omvandskattskyldighetvidsaljandeinomeu.4.7be5268414bea0646940d0e.html',
relatedTerms: ['EU-försäljning', 'Momsfri export'],
},
{
term: 'Ingående moms',
definition:
'Moms du betalar på dina inköp (utgifter). Denna moms får du dra av från din momsredovisning.',
category: 'moms',
relatedTerms: ['Utgående moms', 'Moms'],
},
{
term: 'Utgående moms',
definition:
'Moms du tar ut av dina kunder (lägger på fakturan). Denna moms ska du redovisa till Skatteverket.',
category: 'moms',
relatedTerms: ['Ingående moms', 'Moms'],
},
// Faktura
{
term: 'Förfallodag',
definition:
'Sista dag kunden ska betala fakturan. Vanligast är 30 dagar efter fakturadatum. Efter förfallodagen kan du skicka påminnelse och ta ut dröjsmålsränta.',
category: 'faktura',
relatedTerms: ['Dröjsmålsränta', 'Påminnelse'],
},
{
term: 'OCR-nummer',
definition:
'Ett referensnummer som gör det enkelt att matcha inbetalningar med rätt faktura. Genereras automatiskt och bör alltid anges på fakturan.',
category: 'faktura',
},
{
term: 'Kreditfaktura',
definition:
'En "minusfaktura" som du skapar om du behöver korrigera eller makulera en redan skickad faktura. Beloppet blir negativt och kvittar ut originalfakturan.',
category: 'faktura',
relatedTerms: ['Faktura'],
},
// Bank
{
term: 'Clearingnummer',
definition:
'De första 4-5 siffrorna i ditt bankkonto som identifierar vilken bank och vilket kontor det tillhör. Exempel: 5331 = Avanza, 3300 = Nordea. Ofta separerat från kontonumret med bindestreck.',
category: 'bank',
relatedTerms: ['IBAN', 'BIC/SWIFT'],
},
{
term: 'IBAN',
definition:
'Internationellt bankkontonummer som används för utlandsbetalningar. Svenska IBAN börjar med SE följt av 22 siffror. Din bank kan ge dig ditt IBAN.',
category: 'bank',
relatedTerms: ['BIC/SWIFT', 'Clearingnummer'],
},
{
term: 'BIC/SWIFT',
definition:
'Bankens internationella identifieringskod, används tillsammans med IBAN för utlandsbetalningar. Exempel: SWEDSESS (Swedbank), NDEASESS (Nordea).',
category: 'bank',
relatedTerms: ['IBAN'],
},
// Företag
{
term: 'Enskild firma',
simpleTerm: 'Enskild näringsverksamhet',
definition:
'Den enklaste företagsformen där du och företaget är samma juridiska person. Du äger allt personligen och ansvarar personligen för skulder. Lättast att starta men du betalar skatt via din privata deklaration.',
category: 'företag',
skatteverketUrl: 'https://www.skatteverket.se/foretag/foretagarguiden/foretagsformer/enskildnaringsverksamhet.4.361dc8c15312eff6fd1e5dc.html',
relatedTerms: ['Aktiebolag', 'Egenavgifter', 'NE-bilaga'],
},
{
term: 'Aktiebolag',
simpleTerm: 'AB',
definition:
'Företagsform där företaget är en egen juridisk person, skild från dig. Kräver 25 000 kr i aktiekapital och mer administration, men ger begränsat personligt ansvar och andra skattemöjligheter.',
category: 'företag',
skatteverketUrl: 'https://www.skatteverket.se/foretag/foretagarguiden/foretagsformer/aktiebolag.4.361dc8c15312eff6fd18a05.html',
relatedTerms: ['Enskild firma', 'Bolagsskatt'],
},
{
term: 'Organisationsnummer',
definition:
'Ditt företags unika identitetsnummer. För enskild firma är det ditt personnummer + 100 på århundradesiffran (199001011234 blir 199101011234).',
category: 'företag',
},
]
const categoryConfig = {
skatt: { label: 'Skatt', icon: Calculator, color: 'bg-orange-500/10 text-orange-600' },
moms: { label: 'Moms', icon: Receipt, color: 'bg-blue-500/10 text-blue-600' },
faktura: { label: 'Faktura', icon: FileText, color: 'bg-green-500/10 text-green-600' },
bokföring: { label: 'Bokföring', icon: BookOpen, color: 'bg-purple-500/10 text-purple-600' },
bank: { label: 'Bank', icon: Building2, color: 'bg-pink-500/10 text-pink-600' },
företag: { label: 'Företag', icon: Building2, color: 'bg-cyan-500/10 text-cyan-600' },
}
function TermCard({ term, isExpanded, onToggle }: { term: GlossaryTerm; isExpanded: boolean; onToggle: () => void }) {
const config = categoryConfig[term.category]
const CategoryIcon = config.icon
return (
<Card className={cn('transition-all', isExpanded && 'ring-2 ring-primary/20')}>
<CardContent className="pt-4">
<button
onClick={onToggle}
className="w-full text-left"
>
<div className="flex items-start justify-between gap-3">
<div className="flex items-start gap-3">
<div className={cn('p-2 rounded-lg', config.color)}>
<CategoryIcon className="h-4 w-4" />
</div>
<div>
<div className="flex items-center gap-2 flex-wrap">
<h3 className="font-medium">{term.term}</h3>
{term.simpleTerm && (
<Badge variant="secondary" className="font-normal">
{term.simpleTerm}
</Badge>
)}
</div>
{!isExpanded && (
<p className="text-sm text-muted-foreground line-clamp-2 mt-1">
{term.definition}
</p>
)}
</div>
</div>
{isExpanded ? (
<ChevronUp className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-1" />
) : (
<ChevronDown className="h-4 w-4 text-muted-foreground flex-shrink-0 mt-1" />
)}
</div>
</button>
{isExpanded && (
<div className="mt-4 pl-11 space-y-3 animate-fade-in">
<p className="text-sm text-muted-foreground leading-relaxed">
{term.definition}
</p>
{term.relatedTerms && term.relatedTerms.length > 0 && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-xs text-muted-foreground">Relaterat:</span>
{term.relatedTerms.map((related) => (
<Badge key={related} variant="outline" className="text-xs">
{related}
</Badge>
))}
</div>
)}
{term.skatteverketUrl && (
<HelpLink href={term.skatteverketUrl}>
Läs mer på Skatteverket
<ExternalLink className="h-3 w-3" />
</HelpLink>
)}
</div>
)}
</CardContent>
</Card>
)
}
export default function HelpPage() {
const [searchQuery, setSearchQuery] = useState('')
const [selectedCategory, setSelectedCategory] = useState<string | null>(null)
const [expandedTerms, setExpandedTerms] = useState<Set<string>>(new Set())
const filteredTerms = useMemo(() => {
return glossaryTerms.filter((term) => {
// Category filter
if (selectedCategory && term.category !== selectedCategory) {
return false
}
// Search filter
if (searchQuery) {
const query = searchQuery.toLowerCase()
return (
term.term.toLowerCase().includes(query) ||
term.simpleTerm?.toLowerCase().includes(query) ||
term.definition.toLowerCase().includes(query) ||
term.relatedTerms?.some((r) => r.toLowerCase().includes(query))
)
}
return true
})
}, [searchQuery, selectedCategory])
const toggleTerm = (termName: string) => {
setExpandedTerms((prev) => {
const next = new Set(prev)
if (next.has(termName)) {
next.delete(termName)
} else {
next.add(termName)
}
return next
})
}
return (
<div className="space-y-8">
{/* Header */}
<header>
<h1 className="font-display text-3xl font-medium tracking-tight mb-2">Hjälp & Ordlista</h1>
<p className="text-muted-foreground">
Förklaringar av skatte- och bokföringstermer på ren svenska.
</p>
</header>
{/* Search */}
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
type="search"
placeholder="Sök efter term..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9"
/>
</div>
{/* Category filters */}
<div className="flex flex-wrap gap-2">
<button
onClick={() => setSelectedCategory(null)}
className={cn(
'px-3 py-1.5 rounded-lg text-sm font-medium transition-colors',
selectedCategory === null
? 'bg-primary text-primary-foreground'
: 'bg-secondary text-muted-foreground hover:text-foreground'
)}
>
Alla
</button>
{Object.entries(categoryConfig).map(([key, config]) => (
<button
key={key}
onClick={() => setSelectedCategory(selectedCategory === key ? null : key)}
className={cn(
'px-3 py-1.5 rounded-lg text-sm font-medium transition-colors',
selectedCategory === key
? 'bg-primary text-primary-foreground'
: 'bg-secondary text-muted-foreground hover:text-foreground'
)}
>
{config.label}
</button>
))}
</div>
{/* Terms list */}
<div className="space-y-3">
{filteredTerms.length === 0 ? (
<Card>
<CardContent className="py-12 text-center">
<Search className="h-8 w-8 text-muted-foreground mx-auto mb-3" />
<p className="text-muted-foreground">
Inga termer hittades för "{searchQuery}"
</p>
</CardContent>
</Card>
) : (
filteredTerms.map((term) => (
<TermCard
key={term.term}
term={term}
isExpanded={expandedTerms.has(term.term)}
onToggle={() => toggleTerm(term.term)}
/>
))
)}
</div>
{/* External resources */}
<Card>
<CardHeader>
<CardTitle className="text-lg">Externa resurser</CardTitle>
<CardDescription>Mer hjälp från officiella källor</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-3 sm:grid-cols-2">
<HelpLink
href="https://www.skatteverket.se/foretag/foretagarguiden.4.361dc8c15312eff6fd1f87f.html"
className="p-3 rounded-lg border border-border hover:border-primary/50 transition-colors block"
>
<div className="flex items-center gap-2">
<ExternalLink className="h-4 w-4" />
<span>Skatteverkets företagarguide</span>
</div>
<p className="text-xs text-muted-foreground mt-1">
Omfattande guide för nya företagare
</p>
</HelpLink>
<HelpLink
href="https://www.verksamt.se/"
className="p-3 rounded-lg border border-border hover:border-primary/50 transition-colors block"
>
<div className="flex items-center gap-2">
<ExternalLink className="h-4 w-4" />
<span>Verksamt.se</span>
</div>
<p className="text-xs text-muted-foreground mt-1">
Starta och driva företag i Sverige
</p>
</HelpLink>
</div>
</CardContent>
</Card>
</div>
)
}
+371
View File
@@ -0,0 +1,371 @@
'use client'
import { useState, useCallback } from 'react'
import { Card, CardContent } from '@/components/ui/card'
import { Progress } from '@/components/ui/progress'
import { useToast } from '@/components/ui/use-toast'
import SIEUploadStep from '@/components/import/SIEUploadStep'
import SIEPreviewStep from '@/components/import/SIEPreviewStep'
import AccountMappingStep from '@/components/import/AccountMappingStep'
import ImportReviewStep, { type ImportExecuteOptions } from '@/components/import/ImportReviewStep'
import ImportResultStep from '@/components/import/ImportResultStep'
import { applyMappingOverride } from '@/lib/import/account-mapper'
import type {
ImportWizardStep,
ParsedSIEFile,
AccountMapping,
ImportPreview,
ImportResult,
ParseIssue,
} from '@/lib/import/types'
import type { BASAccount } from '@/types'
const STEPS: ImportWizardStep[] = ['upload', 'preview', 'mapping', 'review', 'result']
const STEP_LABELS: Record<ImportWizardStep, string> = {
upload: 'Ladda upp',
preview: 'Förhandsgranskning',
mapping: 'Kontomappning',
review: 'Bekräfta',
result: 'Resultat',
}
export default function ImportPage() {
const { toast } = useToast()
// Wizard state
const [step, setStep] = useState<ImportWizardStep>('upload')
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
// Data state
const [file, setFile] = useState<File | null>(null)
const [_parsed, setParsed] = useState<ParsedSIEFile | null>(null)
const [mappings, setMappings] = useState<AccountMapping[]>([])
const [basAccounts, setBasAccounts] = useState<BASAccount[]>([])
const [preview, setPreview] = useState<ImportPreview | null>(null)
const [issues, setIssues] = useState<ParseIssue[]>([])
const [importResult, setImportResult] = useState<ImportResult | null>(null)
const [_sieAccounts, setSieAccounts] = useState<{ number: string; name: string }[]>([])
const [isCreatingAccounts, setIsCreatingAccounts] = useState(false)
// Calculate progress
const currentStepIndex = STEPS.indexOf(step)
const progress = ((currentStepIndex + 1) / STEPS.length) * 100
// Handle file selection and parsing
const handleFileSelect = useCallback(async (selectedFile: File) => {
setFile(selectedFile)
setError(null)
setIsLoading(true)
try {
const formData = new FormData()
formData.append('file', selectedFile)
const res = await fetch('/api/import/sie/parse', {
method: 'POST',
body: formData,
})
const data = await res.json()
if (!res.ok) {
if (data.error === 'duplicate') {
setError(data.message)
} else if (data.error === 'validation') {
setError(`${data.message}: ${data.errors?.join(', ') || 'Unknown validation error'}`)
} else {
setError(data.error || 'Failed to parse file')
}
return
}
// Store parsed data
setParsed({
header: data.parsed.header,
accounts: data.parsed.accounts,
openingBalances: [],
closingBalances: [],
resultBalances: [],
vouchers: [],
issues: data.parsed.issues,
stats: data.parsed.stats,
})
setMappings(data.mappings)
setPreview(data.preview)
setIssues(data.parsed.issues)
setSieAccounts(data.parsed.accounts)
// Fetch BAS accounts for the mapping step
const accountsRes = await fetch('/api/bookkeeping/accounts')
if (accountsRes.ok) {
const accountsData = await accountsRes.json()
setBasAccounts(accountsData.data || [])
}
// Move to preview step
setStep('preview')
toast({
title: 'Fil analyserad',
description: `${data.parsed.stats.totalAccounts} konton och ${data.parsed.stats.totalVouchers} verifikationer hittades`,
})
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to parse file')
} finally {
setIsLoading(false)
}
}, [toast])
// Handle mapping changes
const handleMappingChange = useCallback((sourceAccount: string, targetAccount: string, targetName: string) => {
setMappings((prev) => applyMappingOverride(prev, sourceAccount, targetAccount, targetName))
// Update preview mapping status
setPreview((prev) => {
if (!prev) return prev
const updatedMappings = applyMappingOverride(mappings, sourceAccount, targetAccount, targetName)
const mapped = updatedMappings.filter((m) => m.targetAccount).length
const unmapped = updatedMappings.length - mapped
const lowConfidence = updatedMappings.filter((m) => m.targetAccount && m.confidence < 0.7).length
return {
...prev,
mappingStatus: {
...prev.mappingStatus,
mapped,
unmapped,
lowConfidence,
},
}
})
}, [mappings])
// Calculate missing accounts (unmapped accounts that could be created)
const missingAccounts = mappings
.filter((m) => !m.targetAccount)
.map((m) => ({ number: m.sourceAccount, name: m.sourceName }))
// Handle creating missing accounts
const handleCreateAccounts = useCallback(async () => {
if (missingAccounts.length === 0) return
setIsCreatingAccounts(true)
try {
const res = await fetch('/api/import/sie/create-accounts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accounts: missingAccounts }),
})
const data = await res.json()
if (!res.ok) {
toast({
title: 'Fel',
description: data.error || 'Kunde inte skapa konton',
variant: 'destructive',
})
return
}
toast({
title: 'Konton skapade',
description: `${data.created} nya konton har lagts till i din kontoplan`,
})
// Re-parse the file to get updated mappings
if (file) {
const formData = new FormData()
formData.append('file', file)
const parseRes = await fetch('/api/import/sie/parse', {
method: 'POST',
body: formData,
})
const parseData = await parseRes.json()
if (parseRes.ok) {
setMappings(parseData.mappings)
setPreview(parseData.preview)
// Refresh BAS accounts
const accountsRes = await fetch('/api/bookkeeping/accounts')
if (accountsRes.ok) {
const accountsData = await accountsRes.json()
setBasAccounts(accountsData.data || [])
}
}
}
} catch (err) {
toast({
title: 'Fel',
description: err instanceof Error ? err.message : 'Kunde inte skapa konton',
variant: 'destructive',
})
} finally {
setIsCreatingAccounts(false)
}
}, [missingAccounts, file, toast])
// Handle import execution
const handleExecuteImport = useCallback(async (options: ImportExecuteOptions) => {
if (!file) {
setError('No file selected')
return
}
setIsLoading(true)
setError(null)
try {
const formData = new FormData()
formData.append('file', file)
formData.append('mappings', JSON.stringify(mappings))
formData.append('options', JSON.stringify(options))
const res = await fetch('/api/import/sie/execute', {
method: 'POST',
body: formData,
})
const data = await res.json()
if (!res.ok) {
if (data.result) {
setImportResult(data.result)
} else {
setError(data.error || 'Import failed')
return
}
} else {
setImportResult(data.result)
}
// Move to result step
setStep('result')
if (data.result?.success) {
toast({
title: 'Import genomförd',
description: `${data.result.journalEntriesCreated} verifikationer skapades`,
})
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Import failed')
} finally {
setIsLoading(false)
}
}, [file, mappings, toast])
// Navigation handlers
const goToStep = (targetStep: ImportWizardStep) => {
setStep(targetStep)
setError(null)
}
const goBack = () => {
const currentIndex = STEPS.indexOf(step)
if (currentIndex > 0) {
setStep(STEPS[currentIndex - 1])
}
}
const handleNewImport = () => {
// Reset all state
setStep('upload')
setFile(null)
setParsed(null)
setMappings([])
setPreview(null)
setIssues([])
setImportResult(null)
setError(null)
setSieAccounts([])
setIsCreatingAccounts(false)
}
return (
<div className="space-y-6">
{/* Header */}
<div>
<h1 className="text-3xl font-bold tracking-tight">Importera bokföring</h1>
<p className="text-muted-foreground">
Migrera din bokföring från Fortnox, Visma eller annat bokföringssystem via SIE-fil
</p>
</div>
{/* Progress */}
<Card>
<CardContent className="pt-6">
<div className="space-y-2">
<div className="flex justify-between text-sm">
{STEPS.map((s, i) => (
<span
key={s}
className={`${
i <= currentStepIndex ? 'text-primary font-medium' : 'text-muted-foreground'
}`}
>
{STEP_LABELS[s]}
</span>
))}
</div>
<Progress value={progress} className="h-2" />
</div>
</CardContent>
</Card>
{/* Step content */}
{step === 'upload' && (
<SIEUploadStep
onFileSelect={handleFileSelect}
isLoading={isLoading}
error={error}
/>
)}
{step === 'preview' && preview && (
<SIEPreviewStep
preview={preview}
issues={issues}
missingAccounts={missingAccounts}
onCreateAccounts={handleCreateAccounts}
isCreatingAccounts={isCreatingAccounts}
onContinue={() => goToStep('mapping')}
onBack={goBack}
/>
)}
{step === 'mapping' && (
<AccountMappingStep
mappings={mappings}
basAccounts={basAccounts}
onMappingChange={handleMappingChange}
onContinue={() => goToStep('review')}
onBack={goBack}
/>
)}
{step === 'review' && preview && (
<ImportReviewStep
preview={preview}
mappings={mappings}
onExecute={handleExecuteImport}
onBack={goBack}
isLoading={isLoading}
/>
)}
{step === 'result' && importResult && (
<ImportResultStep
result={importResult}
onNewImport={handleNewImport}
/>
)}
</div>
)
}
@@ -0,0 +1,316 @@
'use client'
import { useState, useEffect, use } from 'react'
import { useRouter } from 'next/navigation'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import { useToast } from '@/components/ui/use-toast'
import { formatCurrency, formatDate } from '@/lib/utils'
import { getVatTreatmentLabel } from '@/lib/invoice/vat-rules'
import { Loader2, ArrowLeft, AlertTriangle } from 'lucide-react'
import type { Invoice, InvoiceItem, Customer } from '@/types'
interface InvoiceWithRelations extends Invoice {
customer: Customer
items: InvoiceItem[]
}
export default function CreateCreditNotePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
const router = useRouter()
const { toast } = useToast()
const supabase = createClient()
const [invoice, setInvoice] = useState<InvoiceWithRelations | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [isSubmitting, setIsSubmitting] = useState(false)
const [reason, setReason] = useState('')
useEffect(() => {
fetchInvoice()
}, [id])
async function fetchInvoice() {
setIsLoading(true)
const { data, error } = await supabase
.from('invoices')
.select(`
*,
customer:customers(*),
items:invoice_items(*)
`)
.eq('id', id)
.single()
if (error || !data) {
toast({
title: 'Fel',
description: 'Kunde inte hämta faktura',
variant: 'destructive',
})
router.push('/invoices')
return
}
// Check if invoice can be credited
if (!['sent', 'paid', 'overdue'].includes(data.status)) {
toast({
title: 'Kan inte krediteras',
description: 'Endast skickade, betalda eller förfallna fakturor kan krediteras',
variant: 'destructive',
})
router.push(`/invoices/${id}`)
return
}
if (data.status === 'credited') {
toast({
title: 'Redan krediterad',
description: 'Denna faktura har redan krediterats',
variant: 'destructive',
})
router.push(`/invoices/${id}`)
return
}
// Sort items by sort_order
if (data.items) {
data.items.sort((a: InvoiceItem, b: InvoiceItem) => a.sort_order - b.sort_order)
}
setInvoice(data as InvoiceWithRelations)
setReason(`Krediterar faktura ${data.invoice_number}`)
setIsLoading(false)
}
async function handleSubmit() {
if (!invoice) return
setIsSubmitting(true)
try {
const response = await fetch('/api/invoices', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
credited_invoice_id: invoice.id,
reason,
}),
})
if (!response.ok) {
const data = await response.json()
throw new Error(data.error || 'Failed to create credit note')
}
const { data: creditNote } = await response.json()
toast({
title: 'Kreditfaktura skapad',
description: `Kreditfaktura ${creditNote.invoice_number} har skapats`,
})
router.push(`/invoices/${creditNote.id}`)
} catch (error) {
toast({
title: 'Fel',
description: error instanceof Error ? error.message : 'Kunde inte skapa kreditfaktura',
variant: 'destructive',
})
}
setIsSubmitting(false)
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
)
}
if (!invoice) {
return null
}
const customer = invoice.customer
return (
<div className="space-y-6 max-w-3xl mx-auto">
{/* Header */}
<div className="flex items-center gap-4">
<Button variant="ghost" size="icon" onClick={() => router.back()}>
<ArrowLeft className="h-5 w-5" />
</Button>
<div>
<h1 className="text-3xl font-bold tracking-tight">Skapa kreditfaktura</h1>
<p className="text-muted-foreground">
Krediterar faktura {invoice.invoice_number}
</p>
</div>
</div>
{/* Warning */}
<Card className="border-warning/50 bg-warning/5">
<CardContent className="flex items-start gap-4 pt-6">
<AlertTriangle className="h-5 w-5 text-warning flex-shrink-0 mt-0.5" />
<div>
<p className="font-medium">Viktigt om kreditfakturor</p>
<p className="text-sm text-muted-foreground mt-1">
En kreditfaktura makulerar den ursprungliga fakturan helt.
Alla belopp blir negativa och den ursprungliga fakturan markeras som krediterad.
Denna åtgärd kan inte ångras.
</p>
</div>
</CardContent>
</Card>
{/* Original invoice info */}
<Card>
<CardHeader>
<CardTitle>Ursprunglig faktura</CardTitle>
<CardDescription>
Kreditfakturan baseras på denna faktura
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-muted-foreground">Fakturanummer:</span>
<span className="ml-2 font-medium">{invoice.invoice_number}</span>
</div>
<div>
<span className="text-muted-foreground">Datum:</span>
<span className="ml-2">{formatDate(invoice.invoice_date)}</span>
</div>
<div>
<span className="text-muted-foreground">Kund:</span>
<span className="ml-2">{customer.name}</span>
</div>
<div>
<span className="text-muted-foreground">Momsbehandling:</span>
<span className="ml-2">{getVatTreatmentLabel(invoice.vat_treatment)}</span>
</div>
</div>
</CardContent>
</Card>
{/* Credit note preview */}
<Card>
<CardHeader>
<CardTitle>Kreditfaktura förhandsgranskning</CardTitle>
<CardDescription>
Kreditfakturanummer: KR-{invoice.invoice_number}
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{/* Header */}
<div className="grid grid-cols-12 gap-4 text-sm font-medium text-muted-foreground border-b pb-2">
<div className="col-span-5">Beskrivning</div>
<div className="col-span-2 text-right">Antal</div>
<div className="col-span-1 text-center">Enhet</div>
<div className="col-span-2 text-right">à-pris</div>
<div className="col-span-2 text-right">Summa</div>
</div>
{/* Items (negated) */}
{invoice.items.map((item) => (
<div key={item.id} className="grid grid-cols-12 gap-4 text-sm">
<div className="col-span-5">{item.description}</div>
<div className="col-span-2 text-right text-destructive">
-{Math.abs(item.quantity)}
</div>
<div className="col-span-1 text-center">{item.unit}</div>
<div className="col-span-2 text-right">
{formatCurrency(item.unit_price, invoice.currency)}
</div>
<div className="col-span-2 text-right font-medium text-destructive">
{formatCurrency(-Math.abs(item.line_total), invoice.currency)}
</div>
</div>
))}
<Separator />
{/* Totals (negated) */}
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-muted-foreground">Delsumma</span>
<span className="text-destructive">
{formatCurrency(-Math.abs(invoice.subtotal), invoice.currency)}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Moms ({invoice.vat_rate}%)</span>
<span className="text-destructive">
{formatCurrency(-Math.abs(invoice.vat_amount), invoice.currency)}
</span>
</div>
<Separator />
<div className="flex justify-between font-bold text-lg">
<span>Totalt</span>
<span className="text-destructive">
{formatCurrency(-Math.abs(invoice.total), invoice.currency)}
</span>
</div>
{invoice.currency !== 'SEK' && invoice.total_sek && (
<div className="flex justify-between text-sm text-muted-foreground">
<span>I SEK (kurs {invoice.exchange_rate})</span>
<span className="text-destructive">
{formatCurrency(-Math.abs(invoice.total_sek))}
</span>
</div>
)}
</div>
</div>
</CardContent>
</Card>
{/* Reason */}
<Card>
<CardHeader>
<CardTitle>Anledning</CardTitle>
<CardDescription>
Ange anledning till kreditering (visas på kreditfakturan)
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Label htmlFor="reason">Anledning</Label>
<Textarea
id="reason"
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder="T.ex. Felaktig fakturering, returnerade varor..."
rows={3}
/>
</div>
</CardContent>
</Card>
{/* Actions */}
<div className="flex justify-end gap-4">
<Button variant="outline" onClick={() => router.back()}>
Avbryt
</Button>
<Button onClick={handleSubmit} disabled={isSubmitting}>
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Skapar...
</>
) : (
'Skapa kreditfaktura'
)}
</Button>
</div>
</div>
)
}
File diff suppressed because it is too large Load Diff
+474
View File
@@ -0,0 +1,474 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { createClient } from '@/lib/supabase/client'
import { useForm, useFieldArray, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { addDays, format } from 'date-fns'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Separator } from '@/components/ui/separator'
import { useToast } from '@/components/ui/use-toast'
import { formatCurrency } from '@/lib/utils'
import { getVatRules, getVatTreatmentLabel } from '@/lib/invoice/vat-rules'
import { Loader2, Plus, Trash2, ArrowLeft } from 'lucide-react'
import type { Customer, Currency, CreateInvoiceInput } from '@/types'
const itemSchema = z.object({
description: z.string().min(1, 'Beskrivning krävs'),
quantity: z.number().min(0.01, 'Minst 0.01'),
unit: z.string().min(1, 'Enhet krävs'),
unit_price: z.number().min(0, 'Pris måste vara positivt'),
})
const schema = z.object({
customer_id: z.string().min(1, 'Välj en kund'),
invoice_date: z.string().min(1, 'Fakturadatum krävs'),
due_date: z.string().min(1, 'Förfallodatum krävs'),
currency: z.enum(['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']),
your_reference: z.string().optional(),
our_reference: z.string().optional(),
notes: z.string().optional(),
items: z.array(itemSchema).min(1, 'Minst en rad krävs'),
})
type FormData = z.infer<typeof schema>
const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
const units = ['st', 'tim', 'dag', 'mån', 'km', 'kg']
export default function NewInvoicePage() {
const router = useRouter()
const { toast } = useToast()
const supabase = createClient()
const searchParams = useSearchParams()
const campaignId = searchParams.get('campaign_id')
const preselectedCustomerId = searchParams.get('customer_id')
const [customers, setCustomers] = useState<Customer[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isSubmitting, setIsSubmitting] = useState(false)
const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null)
const {
register,
control,
handleSubmit,
watch,
setValue,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
customer_id: '',
invoice_date: '',
due_date: '',
currency: 'SEK',
items: [{ description: '', quantity: 1, unit: 'st', unit_price: 0 }],
},
})
// Set date defaults on client only to avoid hydration mismatch
useEffect(() => {
setValue('invoice_date', format(new Date(), 'yyyy-MM-dd'))
setValue('due_date', format(addDays(new Date(), 30), 'yyyy-MM-dd'))
}, [])
const { fields, append, remove } = useFieldArray({
control,
name: 'items',
})
const watchItems = watch('items')
const watchCurrency = watch('currency')
const watchCustomerId = watch('customer_id')
useEffect(() => {
fetchCustomers()
}, [])
useEffect(() => {
if (watchCustomerId) {
const customer = customers.find((c) => c.id === watchCustomerId)
setSelectedCustomer(customer || null)
// Update due date based on customer payment terms
if (customer?.default_payment_terms) {
setValue(
'due_date',
format(addDays(new Date(), customer.default_payment_terms), 'yyyy-MM-dd')
)
}
}
}, [watchCustomerId, customers, setValue])
async function fetchCustomers() {
const { data, error } = await supabase
.from('customers')
.select('*')
.order('name', { ascending: true })
if (error) {
toast({
title: 'Fel',
description: 'Kunde inte hämta kunder',
variant: 'destructive',
})
} else {
setCustomers(data || [])
}
setIsLoading(false)
}
useEffect(() => {
if (!campaignId || customers.length === 0) return
async function fetchCampaign() {
const response = await fetch(`/api/campaigns/${campaignId}`)
if (!response.ok) return
const { data: campaign } = await response.json()
if (campaign.customer_id) {
setValue('customer_id', campaign.customer_id)
} else if (preselectedCustomerId) {
setValue('customer_id', preselectedCustomerId)
}
if (campaign.currency) {
setValue('currency', campaign.currency)
}
if (campaign.total_value) {
setValue('items.0.description', campaign.name || '')
setValue('items.0.quantity', 1)
setValue('items.0.unit', 'st')
setValue('items.0.unit_price', campaign.total_value)
}
// Calculate due date from publication_date + payment_terms
const paymentTerms = campaign.payment_terms || 30
const baseDate = campaign.publication_date ? new Date(campaign.publication_date) : new Date()
setValue('due_date', format(addDays(baseDate, paymentTerms), 'yyyy-MM-dd'))
}
fetchCampaign()
}, [campaignId, customers, setValue])
const subtotal = watchItems.reduce((sum, item) => {
return sum + (item.quantity || 0) * (item.unit_price || 0)
}, 0)
const vatRules = selectedCustomer
? getVatRules(selectedCustomer.customer_type, selectedCustomer.vat_number_validated)
: null
const vatAmount = vatRules ? subtotal * (vatRules.rate / 100) : 0
const total = subtotal + vatAmount
async function onSubmit(data: FormData) {
setIsSubmitting(true)
try {
const response = await fetch('/api/invoices', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data as CreateInvoiceInput),
})
const result = await response.json()
if (!response.ok) {
throw new Error(result.error || 'Kunde inte skapa faktura')
}
toast({
title: 'Faktura skapad',
description: `Faktura ${result.data.invoice_number} har skapats`,
})
router.push(`/invoices/${result.data.id}`)
} catch (error) {
toast({
title: 'Fel',
description: error instanceof Error ? error.message : 'Något gick fel',
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</div>
)
}
return (
<div className="space-y-6">
<div className="flex items-center gap-4">
<Button variant="ghost" size="icon" onClick={() => router.back()}>
<ArrowLeft className="h-5 w-5" />
</Button>
<div>
<h1 className="text-3xl font-bold tracking-tight">Ny faktura</h1>
<p className="text-muted-foreground">Skapa en ny faktura</p>
</div>
</div>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
<div className="grid gap-6 lg:grid-cols-3">
{/* Main content */}
<div className="lg:col-span-2 space-y-6">
{/* Customer selection */}
<Card>
<CardHeader>
<CardTitle>Kund</CardTitle>
<CardDescription>Välj vilken kund fakturan ska skickas till</CardDescription>
</CardHeader>
<CardContent>
<Controller
name="customer_id"
control={control}
render={({ field }) => (
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Välj kund" />
</SelectTrigger>
<SelectContent>
{customers.map((customer) => (
<SelectItem key={customer.id} value={customer.id}>
{customer.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
{errors.customer_id && (
<p className="text-sm text-destructive mt-2">{errors.customer_id.message}</p>
)}
{selectedCustomer && vatRules && (
<div className="mt-4 p-3 bg-muted rounded-lg">
<p className="text-sm">
<strong>Momsbehandling:</strong> {getVatTreatmentLabel(vatRules.treatment)}
</p>
{vatRules.reverseChargeText && (
<p className="text-xs text-muted-foreground mt-1">
Omvänd skattskyldighet tillämpas
</p>
)}
</div>
)}
</CardContent>
</Card>
{/* Invoice items */}
<Card>
<CardHeader>
<CardTitle>Fakturarader</CardTitle>
<CardDescription>Lägg till produkter eller tjänster</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{fields.map((field, index) => (
<div key={field.id} className="grid gap-4 md:grid-cols-12 items-start">
<div className="md:col-span-5 space-y-2">
<Label>Beskrivning</Label>
<Input
placeholder="T.ex. Instagram-kampanj"
{...register(`items.${index}.description`)}
/>
{errors.items?.[index]?.description && (
<p className="text-sm text-destructive">
{errors.items[index].description?.message}
</p>
)}
</div>
<div className="md:col-span-2 space-y-2">
<Label>Antal</Label>
<Input
type="number"
step="0.01"
{...register(`items.${index}.quantity`, { valueAsNumber: true })}
/>
</div>
<div className="md:col-span-2 space-y-2">
<Label>Enhet</Label>
<Controller
name={`items.${index}.unit`}
control={control}
render={({ field }) => (
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{units.map((unit) => (
<SelectItem key={unit} value={unit}>
{unit}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</div>
<div className="md:col-span-2 space-y-2">
<Label>à-pris</Label>
<Input
type="number"
step="0.01"
{...register(`items.${index}.unit_price`, { valueAsNumber: true })}
/>
</div>
<div className="md:col-span-1 flex items-end">
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => remove(index)}
disabled={fields.length === 1}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
<Button
type="button"
variant="outline"
onClick={() =>
append({ description: '', quantity: 1, unit: 'st', unit_price: 0 })
}
>
<Plus className="mr-2 h-4 w-4" />
Lägg till rad
</Button>
</div>
</CardContent>
</Card>
{/* Notes */}
<Card>
<CardHeader>
<CardTitle>Anteckningar</CardTitle>
<CardDescription>Valfritt meddelande på fakturan</CardDescription>
</CardHeader>
<CardContent>
<Textarea
placeholder="T.ex. betalningsvillkor eller tack för samarbetet..."
{...register('notes')}
/>
</CardContent>
</Card>
</div>
{/* Sidebar */}
<div className="space-y-6">
{/* Invoice details */}
<Card>
<CardHeader>
<CardTitle>Fakturadetaljer</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>Valuta</Label>
<Controller
name="currency"
control={control}
render={({ field }) => (
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{currencies.map((currency) => (
<SelectItem key={currency} value={currency}>
{currency}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</div>
<div className="space-y-2">
<Label>Fakturadatum</Label>
<Input type="date" {...register('invoice_date')} />
</div>
<div className="space-y-2">
<Label>Förfallodatum</Label>
<Input type="date" {...register('due_date')} />
</div>
<Separator />
<div className="space-y-2">
<Label>Er referens</Label>
<Input
placeholder="Kontaktperson hos kund"
{...register('your_reference')}
/>
</div>
<div className="space-y-2">
<Label>Vår referens</Label>
<Input placeholder="Ditt namn" {...register('our_reference')} />
</div>
</CardContent>
</Card>
{/* Summary */}
<Card>
<CardHeader>
<CardTitle>Summering</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex justify-between">
<span className="text-muted-foreground">Delsumma</span>
<span>{formatCurrency(subtotal, watchCurrency)}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">
Moms ({vatRules?.rate || 25}%)
</span>
<span>{formatCurrency(vatAmount, watchCurrency)}</span>
</div>
<Separator />
<div className="flex justify-between font-bold text-lg">
<span>Totalt</span>
<span>{formatCurrency(total, watchCurrency)}</span>
</div>
</CardContent>
</Card>
{/* Actions */}
<Button type="submit" className="w-full" size="lg" disabled={isSubmitting}>
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Skapar...
</>
) : (
'Skapa faktura'
)}
</Button>
</div>
</div>
</form>
</div>
)
}
+292
View File
@@ -0,0 +1,292 @@
'use client'
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { PageHeader } from '@/components/ui/page-header'
import { useToast } from '@/components/ui/use-toast'
import { formatCurrency, formatDate } from '@/lib/utils'
import { Plus, Search, Receipt, FileText, Send, CheckCircle, Clock, XCircle, ReceiptText, AlertTriangle } from 'lucide-react'
import { EmptyInvoices } from '@/components/ui/empty-state'
import type { Invoice, InvoiceStatus } from '@/types'
const statusConfig: Record<InvoiceStatus, { label: string; variant: 'default' | 'secondary' | 'success' | 'warning' | 'destructive'; icon: React.ElementType; borderColor: string }> = {
draft: { label: 'Utkast', variant: 'secondary', icon: FileText, borderColor: 'border-l-muted-foreground/30' },
sent: { label: 'Skickad', variant: 'default', icon: Send, borderColor: 'border-l-warning' },
paid: { label: 'Betald', variant: 'success', icon: CheckCircle, borderColor: 'border-l-success' },
overdue: { label: 'Förfallen', variant: 'destructive', icon: Clock, borderColor: 'border-l-destructive' },
cancelled: { label: 'Makulerad', variant: 'secondary', icon: XCircle, borderColor: 'border-l-muted-foreground/30' },
credited: { label: 'Krediterad', variant: 'secondary', icon: XCircle, borderColor: 'border-l-muted-foreground/30' },
}
function getRelativeTimeLabel(dueDateStr: string, status: InvoiceStatus): { text: string; color: string } | null {
if (status === 'paid' || status === 'cancelled' || status === 'credited' || status === 'draft') return null
const today = new Date()
today.setHours(0, 0, 0, 0)
const dueDate = new Date(dueDateStr)
dueDate.setHours(0, 0, 0, 0)
const diffDays = Math.round((dueDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
if (diffDays < 0) {
return { text: `${Math.abs(diffDays)} dagar försenad`, color: 'text-destructive' }
} else if (diffDays === 0) {
return { text: 'Förfaller idag', color: 'text-warning-foreground' }
} else if (diffDays <= 3) {
return { text: `${diffDays} dagar kvar`, color: 'text-warning-foreground' }
} else if (diffDays <= 7) {
return { text: `${diffDays} dagar kvar`, color: 'text-muted-foreground' }
}
return null
}
export default function InvoicesPage() {
const [invoices, setInvoices] = useState<Invoice[]>([])
const [isLoading, setIsLoading] = useState(true)
const [searchTerm, setSearchTerm] = useState('')
const [activeTab, setActiveTab] = useState('all')
const { toast } = useToast()
const supabase = createClient()
useEffect(() => {
fetchInvoices()
}, [])
async function fetchInvoices() {
setIsLoading(true)
const { data, error } = await supabase
.from('invoices')
.select('*, customer:customers(name)')
.order('invoice_date', { ascending: false })
if (error) {
toast({
title: 'Fel',
description: 'Kunde inte hämta fakturor',
variant: 'destructive',
})
} else {
setInvoices(data || [])
}
setIsLoading(false)
}
const filteredInvoices = invoices.filter((invoice) => {
const matchesSearch =
invoice.invoice_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
(invoice.customer as { name: string })?.name?.toLowerCase().includes(searchTerm.toLowerCase())
const isCreditNote = !!invoice.credited_invoice_id
const matchesTab =
activeTab === 'all' ||
(activeTab === 'unpaid' && ['sent', 'overdue'].includes(invoice.status) && !isCreditNote) ||
(activeTab === 'credit' && isCreditNote) ||
invoice.status === activeTab
return matchesSearch && matchesTab
})
const stats = {
unpaid: invoices.filter((i) => ['sent', 'overdue'].includes(i.status)).length,
unpaidAmount: invoices
.filter((i) => ['sent', 'overdue'].includes(i.status))
.reduce((sum, i) => sum + Number(i.total_sek || i.total), 0),
overdue: invoices.filter((i) => i.status === 'overdue').length,
}
return (
<div className="space-y-6">
<PageHeader
title="Fakturor"
description="Skapa och hantera dina fakturor"
action={
<Link href="/invoices/new">
<Button>
<Plus className="mr-2 h-4 w-4" />
Ny faktura
</Button>
</Link>
}
/>
{/* Stats */}
<div className="grid gap-4 md:grid-cols-3">
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-4">
<div className="h-12 w-12 rounded-lg bg-primary/10 flex items-center justify-center">
<Receipt className="h-6 w-6 text-primary" />
</div>
<div>
<p className="text-sm text-muted-foreground">Totalt antal</p>
<p className="text-2xl font-bold tabular-nums">{invoices.length}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-4">
<div className="h-12 w-12 rounded-lg bg-warning/10 flex items-center justify-center">
<Clock className="h-6 w-6 text-warning" />
</div>
<div>
<p className="text-sm text-muted-foreground">Obetalda</p>
<div className="flex items-center gap-2">
<p className="text-2xl font-bold tabular-nums">{stats.unpaid}</p>
{stats.overdue > 0 && (
<Badge variant="destructive" className="text-xs">
{stats.overdue} förfallna
</Badge>
)}
</div>
</div>
</div>
</CardContent>
</Card>
<Card className="bg-gradient-to-br from-success/5 to-transparent border-success/20">
<CardContent className="pt-6">
<div className="flex items-center gap-4">
<div className="h-12 w-12 rounded-lg bg-success/10 flex items-center justify-center">
<Send className="h-6 w-6 text-success" />
</div>
<div>
<p className="text-sm text-muted-foreground">Att få in</p>
<p className="text-2xl font-bold tabular-nums">{formatCurrency(stats.unpaidAmount)}</p>
</div>
</div>
</CardContent>
</Card>
</div>
{/* Search and tabs */}
<div className="flex flex-col sm:flex-row gap-4">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Sök på fakturanummer eller kund..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div>
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList>
<TabsTrigger value="all">Alla</TabsTrigger>
<TabsTrigger value="unpaid">Obetalda</TabsTrigger>
<TabsTrigger value="paid">Betalda</TabsTrigger>
<TabsTrigger value="draft">Utkast</TabsTrigger>
<TabsTrigger value="credit">Kredit</TabsTrigger>
</TabsList>
</Tabs>
</div>
{/* Invoice list */}
{isLoading ? (
<div className="space-y-4">
{[1, 2, 3].map((i) => (
<Card key={i} className="animate-pulse">
<CardContent className="py-4">
<div className="flex items-center justify-between">
<div className="space-y-2">
<div className="h-5 bg-muted rounded w-32" />
<div className="h-4 bg-muted rounded w-48" />
</div>
<div className="h-8 bg-muted rounded w-24" />
</div>
</CardContent>
</Card>
))}
</div>
) : filteredInvoices.length === 0 ? (
<Card>
<CardContent>
{searchTerm ? (
<div className="flex flex-col items-center justify-center py-12">
<Receipt className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-medium">Inga träffar</h3>
<p className="text-muted-foreground text-center mt-1">
Inga fakturor matchar &quot;{searchTerm}&quot;
</p>
</div>
) : invoices.length === 0 ? (
<EmptyInvoices />
) : (
<div className="flex flex-col items-center justify-center py-12">
<Receipt className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-medium">Inga fakturor i denna kategori</h3>
<p className="text-muted-foreground text-center mt-1">
Prova att byta flik för att se fler fakturor
</p>
</div>
)}
</CardContent>
</Card>
) : (
<div className="space-y-2">
{filteredInvoices.map((invoice) => {
const status = statusConfig[invoice.status]
const isCreditNote = !!invoice.credited_invoice_id
const StatusIcon = isCreditNote ? ReceiptText : status.icon
const relativeTime = invoice.due_date ? getRelativeTimeLabel(invoice.due_date, invoice.status) : null
const borderClass = isCreditNote ? 'border-l-4 border-l-destructive/50' : `border-l-4 ${status.borderColor}`
return (
<Link key={invoice.id} href={`/invoices/${invoice.id}`}>
<Card className={`hover:border-primary/50 transition-colors cursor-pointer ${borderClass} ${invoice.status === 'overdue' ? 'ring-1 ring-destructive/20' : ''}`}>
<CardContent className="py-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className={`h-10 w-10 rounded-lg flex items-center justify-center ${isCreditNote ? 'bg-destructive/10' : 'bg-muted'}`}>
<StatusIcon className={`h-5 w-5 ${isCreditNote ? 'text-destructive' : 'text-muted-foreground'}`} />
</div>
<div>
<div className="flex items-center gap-2">
<p className="font-medium">{invoice.invoice_number}</p>
{isCreditNote && (
<Badge variant="destructive" className="text-xs">
Kredit
</Badge>
)}
<Badge variant={status.variant as 'default' | 'secondary' | 'destructive'}>
{status.label}
</Badge>
</div>
<div className="flex items-center gap-2">
<p className="text-sm text-muted-foreground">
{(invoice.customer as { name: string })?.name} · {formatDate(invoice.invoice_date)}
</p>
{relativeTime && (
<span className={`text-xs font-medium ${relativeTime.color}`}>
{relativeTime.text}
</span>
)}
</div>
</div>
</div>
<div className="text-right">
<p className={`font-medium tabular-nums ${isCreditNote ? 'text-destructive' : ''}`}>
{formatCurrency(Number(invoice.total), invoice.currency)}
</p>
{invoice.currency !== 'SEK' && invoice.total_sek && (
<p className={`text-sm tabular-nums ${isCreditNote ? 'text-destructive/70' : 'text-muted-foreground'}`}>
{formatCurrency(Number(invoice.total_sek))}
</p>
)}
</div>
</div>
</CardContent>
</Card>
</Link>
)
})}
</div>
)}
</div>
)
}
+53
View File
@@ -0,0 +1,53 @@
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import DashboardNav from '@/components/dashboard/DashboardNav'
import { ChatWidget } from '@/components/chat'
import type { EntityType } from '@/types'
export default async function DashboardLayout({
children,
}: {
children: React.ReactNode
}) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
redirect('/login')
}
const { data: settings } = await supabase
.from('company_settings')
.select('company_name, onboarding_complete, entity_type')
.eq('user_id', user.id)
.single()
if (!settings?.onboarding_complete) {
redirect('/onboarding')
}
const entityType = (settings.entity_type as EntityType) || 'enskild_firma'
return (
<div className="min-h-screen bg-background">
{/* Skip to content link for keyboard/screen reader users */}
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4 focus:z-[100] focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-lg focus:text-sm focus:font-medium"
>
Hoppa till innehåll
</a>
<DashboardNav
companyName={settings.company_name || 'Min verksamhet'}
entityType={entityType}
/>
<main id="main-content" className="pb-20 md:pb-0 md:pl-60" role="main">
<div className="max-w-4xl mx-auto px-6 py-10 md:py-12">
{children}
</div>
</main>
<ChatWidget />
</div>
)
}
+407
View File
@@ -0,0 +1,407 @@
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import DashboardContent from '@/components/dashboard/DashboardContent'
import LightDashboardContent from '@/components/dashboard/LightDashboardContent'
import type { Gift, GiftSummary, Deadline, Campaign, ReceiptQueueSummary, OnboardingProgress, ShadowLedgerEntry } from '@/types'
export const dynamic = 'force-dynamic'
export default async function DashboardPage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
redirect('/login')
}
// Fetch profile for name
const { data: profile } = await supabase
.from('profiles')
.select('full_name')
.eq('id', user.id)
.single()
const firstName = profile?.full_name?.split(' ')[0] || null
// Fetch company settings
const { data: settings } = await supabase
.from('company_settings')
.select('*')
.eq('user_id', user.id)
.single()
// ── Light mode early return ──────────────────────────────────────────
if (settings?.entity_type === 'light') {
const currentYear = new Date().getFullYear()
const lightStartOfYear = `${currentYear}-01-01`
const lightEndOfYear = `${currentYear}-12-31`
// Fetch bank balance
const { data: lightBankConnections } = await supabase
.from('bank_connections')
.select('accounts, status')
.eq('user_id', user.id)
.eq('status', 'active')
.limit(1)
let lightBankBalance: number | null = null
if (lightBankConnections && lightBankConnections.length > 0) {
const accounts = lightBankConnections[0].accounts as { balance: number }[] | null
if (accounts && accounts.length > 0) {
lightBankBalance = accounts.reduce((sum, acc) => sum + (acc.balance || 0), 0)
}
}
// Fetch gifts for current year
const { data: lightGifts } = await supabase
.from('gifts')
.select('*')
.eq('user_id', user.id)
.gte('date', lightStartOfYear)
// Fetch shadow ledger entries for current year
const { data: shadowLedgerEntriesRaw } = await supabase
.from('shadow_ledger_entries')
.select('*')
.eq('user_id', user.id)
.gte('date', lightStartOfYear)
.lte('date', lightEndOfYear)
.order('date', { ascending: false })
const shadowLedgerEntries: ShadowLedgerEntry[] = (shadowLedgerEntriesRaw || []) as ShadowLedgerEntry[]
// Fetch active campaigns
const { data: lightCampaigns } = await supabase
.from('campaigns')
.select(`
*,
customer:customers!campaigns_customer_id_fkey(id, name),
deliverables(*)
`)
.eq('user_id', user.id)
.in('status', ['negotiation', 'contracted', 'active'])
.order('created_at', { ascending: false })
// Fetch upcoming deadlines (next 7 days + overdue)
const lightToday = new Date().toISOString().split('T')[0]
const lightNextWeek = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
const { data: lightDeadlines } = await supabase
.from('deadlines')
.select('*, customer:customers(id, name)')
.eq('user_id', user.id)
.eq('is_completed', false)
.or(`due_date.lt.${lightToday},due_date.lte.${lightNextWeek}`)
.order('due_date', { ascending: true })
// Compute gift tax debt from gifts data
const taxableGifts = (lightGifts || []).filter(
(g: Gift) => g.classification?.taxable && !g.returned
)
const taxableGiftValue = taxableGifts.reduce(
(sum: number, g: Gift) => sum + Number(g.estimated_value), 0
)
const municipalRate = Number(settings.municipal_tax_rate) || 0.3238
const churchRate = settings.church_tax ? (Number(settings.church_tax_rate) || 0.01) : 0
const effectiveRate = municipalRate + churchRate
const giftTaxDebt = Math.round(taxableGiftValue * effectiveRate * 100) / 100
// Find days since last payout
const lastPayout = shadowLedgerEntries.find(e => e.type === 'payout')
let daysSinceLastPayout: number | null = null
if (lastPayout) {
const lastPayoutDate = new Date(lastPayout.date)
const today = new Date()
daysSinceLastPayout = Math.floor((today.getTime() - lastPayoutDate.getTime()) / (1000 * 60 * 60 * 24))
}
// Recent entries for payout card (last 5)
const recentEntries = shadowLedgerEntries.slice(0, 5).map(e => ({
id: e.id,
date: e.date,
description: e.description,
gross_amount: Number(e.gross_amount),
net_amount: Number(e.net_amount),
service_fee: Number(e.service_fee),
pension_deduction: Number(e.pension_deduction),
social_fees: Number(e.social_fees),
income_tax_withheld: Number(e.income_tax_withheld),
platform_fee: Number(e.platform_fee),
type: e.type,
provider: e.provider,
}))
return (
<LightDashboardContent
firstName={firstName}
bankBalance={lightBankBalance}
giftTaxDebt={giftTaxDebt}
taxableGiftCount={taxableGifts.length}
effectiveRate={effectiveRate}
daysSinceLastPayout={daysSinceLastPayout}
recentEntries={recentEntries}
hobbyReserve={0}
/>
)
}
// ── EF / AB dashboard (existing logic) ──────────────────────────────
// Fetch onboarding progress for new user checklist
const { count: customerCount } = await supabase
.from('customers')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id)
const { count: invoiceCount } = await supabase
.from('invoices')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id)
const { count: receiptCount } = await supabase
.from('receipts')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id)
const { count: bankConnectionCount } = await supabase
.from('bank_connections')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id)
.eq('status', 'active')
const onboardingProgress: OnboardingProgress = {
hasCustomers: (customerCount || 0) > 0,
hasInvoices: (invoiceCount || 0) > 0,
hasReceipts: (receiptCount || 0) > 0,
hasBankConnected: (bankConnectionCount || 0) > 0,
}
// Fetch current year transactions summary
const startOfYear = new Date(new Date().getFullYear(), 0, 1).toISOString()
const startOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString()
const { data: transactions } = await supabase
.from('transactions')
.select('amount, amount_sek, is_business, category, date')
.eq('user_id', user.id)
.gte('date', startOfYear.split('T')[0])
// Calculate summaries
const ytdTransactions = transactions || []
const mtdTransactions = ytdTransactions.filter(
(t) => t.date >= startOfMonth.split('T')[0]
)
const calculateTotals = (txns: typeof ytdTransactions) => {
const income = txns
.filter((t) => t.is_business && t.amount > 0)
.reduce((sum, t) => sum + Number(t.amount_sek || t.amount), 0)
const expenses = txns
.filter((t) => t.is_business && t.amount < 0)
.reduce((sum, t) => sum + Math.abs(Number(t.amount_sek || t.amount)), 0)
return { income, expenses, net: income - expenses }
}
const ytdTotals = calculateTotals(ytdTransactions)
const mtdTotals = calculateTotals(mtdTransactions)
const uncategorizedTxns = (transactions || []).filter(
(t) => t.is_business === null
)
const uncategorizedCount = uncategorizedTxns.length
const uncategorizedIncome = uncategorizedTxns
.filter((t) => t.amount > 0)
.reduce((sum, t) => sum + Number(t.amount_sek || t.amount), 0)
const uncategorizedExpenses = uncategorizedTxns
.filter((t) => t.amount < 0)
.reduce((sum, t) => sum + Math.abs(Number(t.amount_sek || t.amount)), 0)
// Fetch unpaid invoices with VAT amounts
const { data: unpaidInvoices } = await supabase
.from('invoices')
.select('total, total_sek, vat_amount, vat_amount_sek, status')
.eq('user_id', user.id)
.in('status', ['sent', 'overdue'])
const unpaidTotal = (unpaidInvoices || []).reduce(
(sum, inv) => sum + Number(inv.total_sek || inv.total),
0
)
// Calculate VAT from unpaid invoices (this is VAT we've invoiced but not yet received)
const unpaidVatTotal = (unpaidInvoices || []).reduce(
(sum, inv) => sum + Number(inv.vat_amount_sek || inv.vat_amount || 0),
0
)
const overdueCount = (unpaidInvoices || []).filter(
(inv) => inv.status === 'overdue'
).length
// Fetch mileage entries for schablonavdrag
const { data: mileageEntries } = await supabase
.from('mileage_entries')
.select('*')
.eq('user_id', user.id)
.gte('date', startOfYear.split('T')[0])
// Fetch bank balance (if connected)
const { data: bankConnections } = await supabase
.from('bank_connections')
.select('accounts, status')
.eq('user_id', user.id)
.eq('status', 'active')
.limit(1)
let bankBalance: number | null = null
if (bankConnections && bankConnections.length > 0) {
const accounts = bankConnections[0].accounts as { balance: number }[] | null
if (accounts && accounts.length > 0) {
bankBalance = accounts.reduce((sum, acc) => sum + (acc.balance || 0), 0)
}
}
// Fetch upcoming deadlines (next 7 days + overdue)
const today = new Date().toISOString().split('T')[0]
const nextWeek = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
const { data: deadlines } = await supabase
.from('deadlines')
.select('*, customer:customers(id, name)')
.eq('user_id', user.id)
.eq('is_completed', false)
.or(`due_date.lt.${today},due_date.lte.${nextWeek}`)
.order('due_date', { ascending: true })
// Fetch active campaigns with deliverables
const { data: campaigns } = await supabase
.from('campaigns')
.select(`
*,
customer:customers!campaigns_customer_id_fkey(id, name),
deliverables(*)
`)
.eq('user_id', user.id)
.in('status', ['negotiation', 'contracted', 'active'])
.order('created_at', { ascending: false })
// Fetch gift summary for current year
const { data: gifts } = await supabase
.from('gifts')
.select('estimated_value, classification')
.eq('user_id', user.id)
.gte('date', startOfYear.split('T')[0])
// Fetch receipt queue summary
const { count: pendingReviewCount } = await supabase
.from('receipts')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id)
.eq('status', 'extracted')
const { count: unmatchedReceiptsCount } = await supabase
.from('receipts')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id)
.eq('status', 'confirmed')
.is('matched_transaction_id', null)
const { count: unmatchedTransactionsCount } = await supabase
.from('transactions')
.select('*', { count: 'exact', head: true })
.eq('user_id', user.id)
.lt('amount', 0)
.is('receipt_id', null)
// Calculate receipt streak
const { data: recentReceiptActivity } = await supabase
.from('receipts')
.select('created_at')
.eq('user_id', user.id)
.eq('status', 'confirmed')
.order('created_at', { ascending: false })
.limit(30)
let streakCount = 0
if (recentReceiptActivity && recentReceiptActivity.length > 0) {
const todayDate = new Date()
todayDate.setHours(0, 0, 0, 0)
const activityDates = new Set(
recentReceiptActivity.map((r) => new Date(r.created_at).toISOString().split('T')[0])
)
let checkDate = new Date(todayDate)
while (activityDates.has(checkDate.toISOString().split('T')[0])) {
streakCount++
checkDate.setDate(checkDate.getDate() - 1)
}
}
const receiptQueue: ReceiptQueueSummary = {
unmatched_receipts_count: unmatchedReceiptsCount || 0,
unmatched_transactions_count: unmatchedTransactionsCount || 0,
pending_review_count: pendingReviewCount || 0,
streak_count: streakCount,
}
let giftSummary: GiftSummary | null = null
if (gifts && gifts.length > 0) {
giftSummary = {
year: new Date().getFullYear(),
total_count: gifts.length,
total_value: 0,
taxable_count: 0,
taxable_value: 0,
tax_free_count: 0,
tax_free_value: 0,
deductible_count: 0,
deductible_value: 0,
}
for (const gift of gifts as Pick<Gift, 'estimated_value' | 'classification'>[]) {
const value = Number(gift.estimated_value)
const classification = gift.classification
giftSummary.total_value += value
if (classification?.taxable) {
giftSummary.taxable_count++
giftSummary.taxable_value += value
} else {
giftSummary.tax_free_count++
giftSummary.tax_free_value += value
}
if (classification?.deductibleAsExpense) {
giftSummary.deductible_count++
giftSummary.deductible_value += value
}
}
}
return (
<DashboardContent
firstName={firstName}
settings={settings}
summary={{
ytd: ytdTotals,
mtd: mtdTotals,
uncategorizedCount,
uncategorizedIncome,
uncategorizedExpenses,
unpaidInvoicesCount: (unpaidInvoices || []).length,
unpaidInvoicesTotal: unpaidTotal,
unpaidVatTotal,
overdueInvoicesCount: overdueCount,
bankBalance,
mileageEntries: mileageEntries || [],
giftSummary,
deadlines: (deadlines || []) as Deadline[],
campaigns: (campaigns || []) as Campaign[],
receiptQueue,
}}
onboardingProgress={onboardingProgress}
/>
)
}
+369
View File
@@ -0,0 +1,369 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
Camera,
Package,
Receipt,
Check,
Clock,
AlertCircle,
ArrowRight,
ExternalLink,
} from 'lucide-react'
import { formatCurrency, formatDate } from '@/lib/utils'
import { useRouter } from 'next/navigation'
import ReceiptDashboard from '@/components/receipts/ReceiptDashboard'
import ReceiptReviewView from '@/components/receipts/ReceiptReviewView'
import TransactionMatcher from '@/components/receipts/TransactionMatcher'
import ProductCapture from '@/components/receipts/ProductCapture'
import type { Receipt as ReceiptType, ReceiptLineItem, ReceiptQueueSummary, ConfirmLineItemInput } from '@/types'
type ViewMode = 'dashboard' | 'list' | 'review' | 'match' | 'product'
type ListFilter = 'all' | 'pending' | 'confirmed'
export default function ReceiptsPage() {
const router = useRouter()
const [viewMode, setViewMode] = useState<ViewMode>('dashboard')
const [listFilter, setListFilter] = useState<ListFilter>('all')
const [receipts, setReceipts] = useState<(ReceiptType & { line_items: ReceiptLineItem[] })[]>([])
const [summary, setSummary] = useState<ReceiptQueueSummary | null>(null)
const [isLoading, setIsLoading] = useState(true)
// Selected receipt for review/match
const [selectedReceipt, setSelectedReceipt] = useState<(ReceiptType & { line_items: ReceiptLineItem[] }) | null>(null)
// Fetch receipts and summary
const fetchData = useCallback(async () => {
setIsLoading(true)
try {
const [receiptsRes, queueRes] = await Promise.all([
fetch('/api/receipts'),
fetch('/api/receipts/queue'),
])
const [receiptsData, queueData] = await Promise.all([
receiptsRes.json(),
queueRes.json(),
])
if (receiptsData.data) {
setReceipts(receiptsData.data)
}
if (queueData.data?.summary) {
setSummary(queueData.data.summary)
}
} catch (error) {
console.error('Fetch error:', error)
} finally {
setIsLoading(false)
}
}, [])
useEffect(() => {
fetchData()
}, [fetchData])
// Filter receipts based on tab
const filteredReceipts = receipts.filter((r) => {
if (listFilter === 'pending') return r.status === 'extracted'
if (listFilter === 'confirmed') return r.status === 'confirmed'
return true
})
// Handle scan receipt
const handleScanReceipt = () => {
router.push('/receipts/scan')
}
// Handle register product
const handleRegisterProduct = () => {
setViewMode('product')
}
// Handle view receipt queue
const handleViewReceiptQueue = () => {
setListFilter('pending')
setViewMode('list')
}
// Handle view transaction queue
const handleViewTransactionQueue = () => {
router.push('/transactions?filter=unmatched')
}
// Handle receipt selection for review
const handleSelectReceipt = (receipt: ReceiptType & { line_items: ReceiptLineItem[] }) => {
setSelectedReceipt(receipt)
if (receipt.status === 'extracted') {
setViewMode('review')
} else {
setViewMode('match')
}
}
// Handle confirm receipt
const handleConfirmReceipt = async (data: {
line_items: ConfirmLineItemInput[]
representation_persons?: number
representation_purpose?: string
}) => {
if (!selectedReceipt) return
const response = await fetch(`/api/receipts/${selectedReceipt.id}/confirm`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
if (response.ok) {
await fetchData()
setSelectedReceipt(null)
setViewMode('dashboard')
} else {
const errorData = await response.json()
throw new Error(errorData.error || 'Kunde inte bekräfta kvitto')
}
}
// Handle match receipt to transaction
const handleMatchReceipt = async (transactionId: string, confidence: number) => {
if (!selectedReceipt) return
const response = await fetch(`/api/receipts/${selectedReceipt.id}/match`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transaction_id: transactionId, match_confidence: confidence }),
})
if (response.ok) {
await fetchData()
setSelectedReceipt(null)
setViewMode('dashboard')
}
}
// Handle product capture complete
const handleProductComplete = () => {
setViewMode('dashboard')
fetchData()
}
// Render receipt review view
if (viewMode === 'review' && selectedReceipt) {
return (
<ReceiptReviewView
receipt={selectedReceipt}
onConfirm={handleConfirmReceipt}
onCancel={() => {
setSelectedReceipt(null)
setViewMode('dashboard')
}}
onFindMatches={() => setViewMode('match')}
/>
)
}
// Render transaction matcher
if (viewMode === 'match' && selectedReceipt) {
return (
<TransactionMatcher
receipt={selectedReceipt}
onMatch={handleMatchReceipt}
onSkip={() => {
setSelectedReceipt(null)
setViewMode('dashboard')
}}
onClose={() => {
setSelectedReceipt(null)
setViewMode('dashboard')
}}
/>
)
}
// Render product capture
if (viewMode === 'product') {
return (
<ProductCapture
onComplete={handleProductComplete}
onCancel={() => setViewMode('dashboard')}
/>
)
}
// Render main page
return (
<div className="container max-w-4xl mx-auto p-4 space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold">Kvittohantering</h1>
<Button onClick={handleScanReceipt}>
<Camera className="mr-2 h-4 w-4" />
Skanna kvitto
</Button>
</div>
{/* Dashboard or List view toggle */}
<Tabs
value={viewMode === 'list' ? 'list' : 'dashboard'}
onValueChange={(v) => setViewMode(v as ViewMode)}
>
<TabsList>
<TabsTrigger value="dashboard">Översikt</TabsTrigger>
<TabsTrigger value="list">Alla kvitton</TabsTrigger>
</TabsList>
</Tabs>
{viewMode === 'dashboard' && (
<>
{isLoading ? (
<div className="space-y-4">
<div className="grid grid-cols-2 gap-3">
<Skeleton className="h-24" />
<Skeleton className="h-24" />
</div>
<Skeleton className="h-32" />
<Skeleton className="h-24" />
</div>
) : summary ? (
<ReceiptDashboard
summary={summary}
onScanReceipt={handleScanReceipt}
onRegisterProduct={handleRegisterProduct}
onViewReceiptQueue={handleViewReceiptQueue}
onViewTransactionQueue={handleViewTransactionQueue}
/>
) : (
<Card>
<CardContent className="pt-4 text-center py-8">
<AlertCircle className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
<p>Kunde inte ladda data</p>
<Button variant="outline" className="mt-4" onClick={fetchData}>
Försök igen
</Button>
</CardContent>
</Card>
)}
</>
)}
{viewMode === 'list' && (
<>
{/* List filters */}
<div className="flex gap-2">
<Button
variant={listFilter === 'all' ? 'default' : 'outline'}
size="sm"
onClick={() => setListFilter('all')}
>
Alla
</Button>
<Button
variant={listFilter === 'pending' ? 'default' : 'outline'}
size="sm"
onClick={() => setListFilter('pending')}
>
<Clock className="mr-1 h-3 w-3" />
Att granska
</Button>
<Button
variant={listFilter === 'confirmed' ? 'default' : 'outline'}
size="sm"
onClick={() => setListFilter('confirmed')}
>
<Check className="mr-1 h-3 w-3" />
Bekräftade
</Button>
</div>
{/* Receipt list */}
{isLoading ? (
<div className="space-y-3">
{[1, 2, 3].map((i) => (
<Skeleton key={i} className="h-24" />
))}
</div>
) : filteredReceipts.length === 0 ? (
<Card>
<CardContent className="pt-4 text-center py-8">
<Receipt className="h-12 w-12 text-muted-foreground mx-auto mb-3" />
<p className="text-muted-foreground">Inga kvitton hittades</p>
</CardContent>
</Card>
) : (
<div className="space-y-3">
{filteredReceipts.map((receipt) => (
<Card
key={receipt.id}
className="cursor-pointer hover:border-primary/50 transition-colors"
onClick={() => handleSelectReceipt(receipt)}
>
<CardContent className="pt-4">
<div className="flex items-start justify-between">
<div className="flex items-start gap-3">
{receipt.image_url ? (
<img
src={receipt.image_url}
alt="Receipt"
className="h-16 w-12 object-cover rounded"
/>
) : (
<div className="h-16 w-12 bg-muted rounded flex items-center justify-center">
<Receipt className="h-6 w-6 text-muted-foreground" />
</div>
)}
<div>
<p className="font-medium">{receipt.merchant_name || 'Okänt kvitto'}</p>
{receipt.receipt_date && (
<p className="text-sm text-muted-foreground">
{formatDate(receipt.receipt_date)}
</p>
)}
<div className="flex flex-wrap gap-1 mt-1">
<Badge
variant={
receipt.status === 'confirmed'
? 'default'
: receipt.status === 'extracted'
? 'secondary'
: receipt.status === 'error'
? 'destructive'
: 'outline'
}
>
{receipt.status === 'confirmed' && 'Bekräftat'}
{receipt.status === 'extracted' && 'Att granska'}
{receipt.status === 'processing' && 'Analyserar...'}
{receipt.status === 'pending' && 'Väntar'}
{receipt.status === 'error' && 'Fel'}
</Badge>
{receipt.matched_transaction_id && (
<Badge variant="outline">Kopplat</Badge>
)}
</div>
</div>
</div>
<div className="text-right">
<p className="font-bold">
{formatCurrency(receipt.total_amount || 0, receipt.currency)}
</p>
<ArrowRight className="h-4 w-4 text-muted-foreground mt-2 ml-auto" />
</div>
</div>
</CardContent>
</Card>
))}
</div>
)}
</>
)}
</div>
)
}
+157
View File
@@ -0,0 +1,157 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import ReceiptCamera from '@/components/receipts/ReceiptCamera'
import ReceiptReviewView from '@/components/receipts/ReceiptReviewView'
import TransactionMatcher from '@/components/receipts/TransactionMatcher'
import { Loader2 } from 'lucide-react'
import type { Receipt, ReceiptLineItem, ConfirmLineItemInput } from '@/types'
type PageState = 'camera' | 'uploading' | 'review' | 'match' | 'done'
export default function ScanReceiptPage() {
const router = useRouter()
const [pageState, setPageState] = useState<PageState>('camera')
const [uploadError, setUploadError] = useState<string | null>(null)
const [receipt, setReceipt] = useState<(Receipt & { line_items: ReceiptLineItem[] }) | null>(null)
// Handle image capture
const handleCapture = async (imageData: string, mimeType: string) => {
setPageState('uploading')
setUploadError(null)
try {
// Convert base64 to blob
const byteCharacters = atob(imageData)
const byteNumbers = new Array(byteCharacters.length)
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i)
}
const byteArray = new Uint8Array(byteNumbers)
const blob = new Blob([byteArray], { type: mimeType })
// Create form data
const formData = new FormData()
formData.append('image', blob, 'receipt.jpg')
// Upload and analyze
const response = await fetch('/api/receipts/upload', {
method: 'POST',
body: formData,
})
const data = await response.json()
if (response.ok && data.data) {
setReceipt(data.data)
setPageState('review')
} else {
setUploadError(data.error || 'Kunde inte analysera kvittot')
setPageState('camera')
}
} catch (error) {
console.error('Upload error:', error)
setUploadError('Nätverksfel. Försök igen.')
setPageState('camera')
}
}
// Handle close/cancel
const handleClose = () => {
router.push('/receipts')
}
// Handle confirm receipt
const handleConfirm = async (data: {
line_items: ConfirmLineItemInput[]
representation_persons?: number
representation_purpose?: string
}) => {
if (!receipt) return
const response = await fetch(`/api/receipts/${receipt.id}/confirm`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
if (response.ok) {
const updatedData = await response.json()
setReceipt(updatedData.data)
setPageState('match')
} else {
const errorData = await response.json()
throw new Error(errorData.error || 'Kunde inte bekräfta kvitto')
}
}
// Handle match to transaction
const handleMatch = async (transactionId: string, confidence: number) => {
if (!receipt) return
const response = await fetch(`/api/receipts/${receipt.id}/match`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transaction_id: transactionId, match_confidence: confidence }),
})
if (response.ok) {
router.push('/receipts')
}
}
// Handle skip matching
const handleSkipMatch = () => {
router.push('/receipts')
}
// Render uploading state
if (pageState === 'uploading') {
return (
<div className="fixed inset-0 bg-background z-50 flex flex-col items-center justify-center">
<Loader2 className="h-12 w-12 animate-spin text-primary mb-4" />
<p className="text-lg font-medium">Analyserar kvitto...</p>
<p className="text-sm text-muted-foreground mt-1">
AI läser av artiklar och belopp
</p>
</div>
)
}
// Render review view
if (pageState === 'review' && receipt) {
return (
<ReceiptReviewView
receipt={receipt}
onConfirm={handleConfirm}
onCancel={handleClose}
onFindMatches={() => setPageState('match')}
/>
)
}
// Render match view
if (pageState === 'match' && receipt) {
return (
<TransactionMatcher
receipt={receipt}
onMatch={handleMatch}
onSkip={handleSkipMatch}
onClose={handleClose}
/>
)
}
// Render camera (default)
return (
<>
{uploadError && (
<div className="fixed top-4 left-4 right-4 z-[60] bg-destructive text-destructive-foreground p-3 rounded-lg text-sm">
{uploadError}
</div>
)}
<ReceiptCamera onCapture={handleCapture} onClose={handleClose} />
</>
)
}
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More