feat: first commit

master
adriano 2025-06-09 08:13:05 -03:00
commit b828d8b9bd
63 changed files with 10983 additions and 0 deletions

View File

@ -0,0 +1,8 @@
PORT=5000
FRONTEND_URL=http://localhost:3000
MONGO_URI=mongodb://admin:SODIOXX98*@172.31.187.24:27017
SECRET_KEY=TESTPSOJDFPSODIJFPDSJP
JWT_SECRET_KEY=sua_chave_supersecreta
JWT_ACCESS_TOKEN_EXPIRES_DAYS=15

55
backend/.gitignore vendored 100644
View File

@ -0,0 +1,55 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# Virtual environment
venv/
.env/
.env.bak
.env.*
# Environment variable files
*.env
# Flask instance folder
instance/
# Pytest cache
.pytest_cache/
# VSCode settings
.vscode/
# macOS
.DS_Store
# Logs and database
*.log
*.sqlite3
*.db
# Coverage reports
htmlcov/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
# Mypy
.mypy_cache/
# Flask-Migrate files (optional)
migrations/
# Celery beat schedule file
celerybeat-schedule
# Node.js (caso tenha frontend integrado)
node_modules/
dist/
build/
# Jupyter Notebook checkpoints (se usar notebooks)
.ipynb_checkpoints/

26
backend/Pipfile 100644
View File

@ -0,0 +1,26 @@
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
flask = "*"
dotenv = "*"
flask-sqlalchemy = "*"
pymongo = "*"
pymysql = "*"
openpyxl = "*"
pandas = "*"
pydantic = "*"
flask-restx = "*"
pytest = "*"
pytest-mock = "*"
flask-jwt-extended = "*"
flask-bcrypt = "*"
flask-cors = "*"
mypy = "*"
[dev-packages]
[requires]
python_version = "3.12"

1031
backend/Pipfile.lock generated 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
from flask import Flask
from flask_restx import Api
from .config import Config
from .extensions import init_mongo, init_jwt
from .errors.handlers import register_error_handlers
from .routes.usage_routes import usage_ns
from .routes.auth_routes import auth_ns
from flask_cors import CORS
def create_app():
app = Flask(__name__)
app.config.from_object(Config)
CORS(app, origins=app.config["FRONTEND_URL"], supports_credentials=True)
init_mongo(app)
init_jwt(app)
api = Api(
app,
title='Trascription usage API',
version='1.0',
description='API documentation',
doc='/docs',
prefix='/api/v1',
authorizations={
'Bearer Auth': {
'type': 'apiKey',
'in': 'header',
'name': 'Authorization',
'description': "Enter your JWT token as: **Bearer <token>**"
}
}
)
api.add_namespace(usage_ns, path='/usage')
api.add_namespace(auth_ns, path='/auth')
register_error_handlers(app)
return app

View File

@ -0,0 +1,19 @@
import os
from dotenv import load_dotenv
from datetime import timedelta
load_dotenv()
class Config:
PORT = os.getenv("PORT", 8001)
DEBUG = True
TESTING = False
SECRET_KEY = os.getenv("SECRET_KEY", "default-secret-key")
MONGO_URI = os.getenv("MONGO_URI")
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "chave_secreta")
JWT_ACCESS_TOKEN_EXPIRES = timedelta(days=int(os.getenv("JWT_ACCESS_TOKEN_EXPIRES_DAYS", 1)))
FRONTEND_URL = os.getenv("FRONTEND_URL", 3000)

View File

@ -0,0 +1,19 @@
from flask_bcrypt import generate_password_hash, check_password_hash
from flask import current_app
from pymongo import MongoClient
class UserModel:
def __init__(self):
client = current_app.mongo_client
self.collection = client["billing-api"]["users"]
def create_user(self, email, password):
hashed = generate_password_hash(password).decode('utf-8')
user = {"email": email, "password": hashed}
return self.collection.insert_one(user)
def find_by_email(self, email):
return self.collection.find_one({"email": email})
def verify_password(self, hashed_password, plain_password):
return check_password_hash(hashed_password, plain_password)

View File

@ -0,0 +1,19 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from urllib.parse import quote_plus
def get_engine_for_company(company_id: str):
schema = f"hitpbx_{company_id}"
user = "appuser"
password = quote_plus("nmvP$x23Vzb@T%Su")
# Dev
# db_url = f"mysql+pymysql://root:mypass@127.0.0.1:3307/{schema}?charset=utf8mb4"
db_url = f"mysql+pymysql://{user}:{password}@172.31.187.150:6033/{schema}?charset=utf8mb4"
return create_engine(db_url, pool_pre_ping=True)
def get_session_for_company(company_id):
engine = get_engine_for_company(company_id)
Session = scoped_session(sessionmaker(bind=engine))
return Session

View File

@ -0,0 +1,8 @@
from flask_restx import fields, Namespace
auth_ns = Namespace('auth', description='Authentication')
signup_model = auth_ns.model('Signup', {
'email': fields.String(required=True),
'password': fields.String(required=True)
})

View File

@ -0,0 +1,54 @@
from flask_restx import fields, Namespace
usage_ns = Namespace('usage', description='Usage transcription data, export, price and cost update operations')
usage_cost_model = usage_ns.model('UpdateUsageCost', {
'company_ids': fields.List(fields.String, required=False, description='Company id list'),
'start_date': fields.String(required=True, description='Start date (YYYY-MM-DD)'),
'end_date': fields.String(required=True, description='End date (YYYY-MM-DD)'),
'product': fields.String(required=True, description='Product name'),
'price': fields.String(required=True, description='Price'),
'billing_unit': fields.Integer(required=True, description='Billing unit')
})
model_price_update = usage_ns.model('UpdateModelPrice', {
'product': fields.String(required=False),
'provider': fields.String(required=False),
'type': fields.String(required=False),
'billingBy': fields.String(required=False),
'billingUnit': fields.Integer(required=False),
'currency': fields.String(required=False),
'price': fields.String(required=False),
'clientPrice': fields.String(required=False),
})
model_prices_query_params = {
'type': {
'description': 'Type of the model. Ex: stt, tts (Optional)',
'type': 'string'
},
'provider': {
'description': 'The API provider. E.g., google, openai, meta (Optional)',
'type': 'string'
},
}
transcription_data_query_params = {
'companyId': {
'description': 'Company ID (required)',
'type': 'string'
},
'startDate': {
'description': 'Start date (YYYY-MM-DD) (required)',
'type': 'string'
},
'endDate': {
'description': 'End date (YYYY-MM-DD) (required)',
'type': 'string'
},
'who': {
'description': 'Who made: "hit" or "client" (required)',
'type': 'string'
}
}

View File

@ -0,0 +1,21 @@
import traceback
from flask import jsonify
from werkzeug.exceptions import HTTPException
from pydantic import ValidationError
import traceback
def register_error_handlers(app):
@app.errorhandler(ValidationError)
def handle_validation_error(e):
return jsonify({"error": e.errors()}), 400
@app.errorhandler(HTTPException)
def handle_http_exception(e):
return jsonify({"errror": e.description}), e.code
@app.errorhandler(Exception)
def handle_unexpected_exception(e):
app.logger.error(traceback.format_exc())
return jsonify({"error": str(e)}), 500

View File

@ -0,0 +1,10 @@
from pymongo import MongoClient
from flask_jwt_extended import JWTManager
jwt = JWTManager()
def init_mongo(app):
app.mongo_client = MongoClient(app.config["MONGO_URI"])
def init_jwt(app):
jwt.init_app(app)

View File

View File

@ -0,0 +1,31 @@
from flask_restx import Namespace, Resource, fields
from flask import request
from flask_jwt_extended import create_access_token
from app.db.models import UserModel
from app.docs.auth_models import auth_ns, signup_model
@auth_ns.route('/signup')
class SignUp(Resource):
@auth_ns.expect(signup_model)
def post(self):
data = request.get_json()
user_model = UserModel()
if user_model.find_by_email(data['email']):
return {'message': 'User already exists'}, 400
user_model.create_user(data['email'], data['password'])
return {'message': 'success'}, 201
@auth_ns.route('/login')
class Login(Resource):
@auth_ns.expect(signup_model)
def post(self):
data = request.get_json()
user_model = UserModel()
user = user_model.find_by_email(data['email'])
if not user or not user_model.verify_password(user['password'], data['password']):
return {'message': 'Invalid credentials'}, 401
access_token = create_access_token(identity=user['email'])
return {'access_token': access_token}, 200

View File

@ -0,0 +1,199 @@
import os
from bson import json_util
from flask_restx import Resource
from flask_jwt_extended import jwt_required
from app.schemas.prices_schema import GetTranscriptionRequest
from app.schemas.transcription_schema import TranscriptionRequest
from app.schemas.model_price_update_schema import UpdateModelPriceRequest
from app.schemas.usage_cost_update_schema import UpdateUsageCostRequest
from flask import current_app, request, send_file, after_this_request
from app.services.report_service import TranscriptionReportService
from app.services.mongo_billing_service import MongoBillingService
from app.docs.usage_models import (
usage_cost_model,
model_price_update,
model_prices_query_params,
transcription_data_query_params, usage_ns)
@usage_ns.route('/export/trascription')
class TranscriptionExport(Resource):
@usage_ns.doc(security='Bearer Auth')
@usage_ns.doc(params=transcription_data_query_params)
@usage_ns.response(200, 'success')
@usage_ns.response(400, 'Validation error')
@usage_ns.response(404, 'File not found')
@jwt_required()
def get(self):
"""
Export transcription report in XLSX.
"""
data = {
"company_id": request.args.get("companyId", type=str),
"start_date": request.args.get("startDate"),
"end_date": request.args.get("endDate"),
"who": request.args.get("who", type=str)
}
validated = TranscriptionRequest(**data)
service = TranscriptionReportService(
validated.company_id,
validated.start_date,
validated.end_date
)
if validated.who == "hit":
report_path = service.reportDataXLSX(hit_report=True)
else:
report_path = service.reportDataXLSX()
if not os.path.exists(report_path):
return {"error": "File not found"}, 404
@after_this_request
def remove_file(response):
try:
os.remove(report_path)
except Exception as delete_error:
current_app.logger.warning(f"Error trying to delete file: {delete_error}")
return response
return send_file(
path_or_file=report_path,
as_attachment=True,
download_name=os.path.basename(report_path),
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
@usage_ns.route('/data/trascription')
class TranscriptionUsageData(Resource):
@usage_ns.doc(security='Bearer Auth')
@usage_ns.doc(params=transcription_data_query_params)
@usage_ns.response(200, 'success')
@usage_ns.response(400, 'Validation error')
@jwt_required()
def get(self):
"""
Get transcription report data.
"""
data = {
"company_id": request.args.get("companyId", type=str),
"start_date": request.args.get("startDate"),
"end_date": request.args.get("endDate"),
"who": request.args.get("who", type=str)
}
validated = TranscriptionRequest(**data)
page = request.args.get("page", default=1, type=int)
page_size = request.args.get("page_size", default=20, type=int)
service = TranscriptionReportService(
validated.company_id,
validated.start_date,
validated.end_date
)
if validated.who == "hit":
result = service.reportData(page=page, page_size=page_size,hit_report=True)
else:
result = service.reportData(page=page, page_size=page_size)
return {"success": True, "data": {"data": result["data"], "pagination": result["pagination"]}}, 200
@usage_ns.route('/model/prices')
class TranscriptionModelPrices(Resource):
@usage_ns.doc(security='Bearer Auth')
@usage_ns.doc(params=model_prices_query_params)
@usage_ns.response(200, 'success')
@usage_ns.response(400, 'Validation error')
@jwt_required()
def get(self):
"""
Get model pricing and supplier information
"""
data = {
"type": request.args.get("type", "").split(",") if request.args.get("type") else [],
"provider": request.args.get("provider", "").split(",") if request.args.get("provider") else []
}
validated = GetTranscriptionRequest(**data)
mongo = current_app.mongo_client
collection = mongo["billing-api"]["api_pricings"]
query = {"product": {"$nin": ["whatsapp",]}}
if validated.type:
query["type"] = {"$in": validated.type}
if validated.provider:
query["provider"] = {"$in": validated.provider}
prices_cursor = collection.find(query)
prices_list = list(prices_cursor)
return current_app.response_class(
response=json_util.dumps({"success": True, "data": prices_list}),
mimetype='application/json'
)
@usage_ns.route('/cost')
class UpdateUsageCost(Resource):
@usage_ns.doc(security='Bearer Auth')
@usage_ns.expect(usage_cost_model)
@usage_ns.response(200, 'success')
@usage_ns.response(400, 'Validation error')
@jwt_required()
def patch(self):
"""
Updates the total cost of using products by company
"""
data = request.get_json()
validated = UpdateUsageCostRequest(**data)
service = MongoBillingService()
count_udpated = service.update_usage_total_cost(
product=validated.product,
start_date=validated.start_date,
end_date=validated.end_date,
price=validated.price,
billing_unit=validated.billing_unit,
company_ids=validated.company_ids,
)
return {"success": True, "docs_updated": count_udpated}, 200
@usage_ns.route('/model/prices/<string:id>')
@usage_ns.param('id', 'ID of the model to be updated')
class UpdateModelPrice(Resource):
@usage_ns.doc(security='Bearer Auth')
@usage_ns.expect(model_price_update)
@usage_ns.response(200, 'Sucess')
@usage_ns.response(400, 'Validation error')
@jwt_required()
def patch(self, id):
"""
Updates the price of a specific model by ID.
Only the fields provided in the body will be changed.
"""
data = request.get_json()
data["id"] = id
validated = UpdateModelPriceRequest(**data)
del data["id"]
service = MongoBillingService()
service.update_model_policy_price(validated.id, data)
return {"success": True}, 200

View File

@ -0,0 +1,16 @@
from pydantic import BaseModel, Field
from typing import List, Optional, Literal
class UpdateModelPriceRequest(BaseModel):
id: str
product: Optional[str] = None
provider: Optional[str] = None
type: Optional[str] = None
billingBy: Optional[str] = None
billingUnit: Optional[int] = None
currency: Optional[str] = None
price: Optional[str] = None
clientPrice: Optional[str] = None
class Config:
extra = "forbid"

View File

@ -0,0 +1,6 @@
from pydantic import BaseModel, Field
from typing import List, Optional, Literal
class GetTranscriptionRequest(BaseModel):
type: Optional[List[str]] = None
provider: Optional[List[str]] = None

View File

@ -0,0 +1,8 @@
from pydantic import BaseModel, Field
from typing import List, Optional, Literal
class TranscriptionRequest(BaseModel):
company_id: str
start_date: str
end_date: str
who: Literal['hit', 'client']

View File

@ -0,0 +1,10 @@
from pydantic import BaseModel, Field
from typing import List, Optional, Literal
class UpdateUsageCostRequest(BaseModel):
company_ids: Optional[List[str]] = None
start_date: str
end_date: str
product: str
price: float
billing_unit: int

View File

@ -0,0 +1,66 @@
from datetime import datetime
from app.utils.calc_api_usage import calculate_api_usage
from flask import current_app
from typing import List, Dict, Any, Optional
from bson import ObjectId
class MongoBillingService:
def __init__(self):
self.mongo_client = current_app.mongo_client
def update_usage_total_cost(self,
product: str,
start_date: str,
end_date: str,
price: float,
billing_unit: int,
company_ids: Optional[List[str]] = None, ) -> int:
query = {
"product": product,
"createdAt": {
"$gte": datetime.strptime(f"{start_date} 00:00:00", "%Y-%m-%d %H:%M:%S"),
"$lte": datetime.strptime(f"{end_date} 23:59:59", "%Y-%m-%d %H:%M:%S")
}
}
if company_ids:
query["companyId"] = {"$in": company_ids}
collection = self.mongo_client["billing-api"]["api_usages"]
cursor = collection.find(query)
count = 0
for doc in cursor:
usage = float(doc.get("usage", 0))
new_total_cost = calculate_api_usage(float(price), int(billing_unit), float(usage))
collection.update_one(
{"_id": doc["_id"]},
{
"$set": {
"total_cost": new_total_cost,
"price": f"{price}",
"billingUnit": billing_unit,
"updatedAt": datetime.utcnow()
}
}
)
count+=1
return count
def update_model_policy_price(self, id:str, update_data: Dict[str, Any]) -> int:
collection = self.mongo_client["billing-api"]["api_pricings"]
update_data["updatedAt"] = datetime.utcnow()
result = collection.update_one(
{"_id": ObjectId(id)},
{"$set": update_data}
)
return result.modified_count

View File

@ -0,0 +1,237 @@
from flask import current_app
from datetime import datetime
from decimal import Decimal
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.styles import Font, PatternFill
import pandas as pd
import os
from typing import List, Dict, Any, Optional
from app.utils.mysql_query import execute_query
from app.utils.calc_api_usage import calculate_api_usage
class TranscriptionReportService:
def __init__(self, company_id: str, start_date: str, end_date: str):
self.company_id = str(company_id)
self.start_date = start_date
self.end_date = end_date
self.end_date = end_date
self.mongo_client = current_app.mongo_client
self.mongo_results = []
self.unique_ids= []
def _fetch_mongo_data(self, page: int = 1, page_size: int = 20, all_data: Optional[bool] = False) -> Dict[str, int]:
collection = self.mongo_client["billing-api"]["api_pricings"]
result_stt = collection.find({"type": "stt"})
products = [t["product"] for t in result_stt]
match_stage = {
"$match": {
"companyId": self.company_id,
"product": {"$in": products},
"createdAt": {
"$gte": datetime.strptime(f"{self.start_date} 00:00:00", "%Y-%m-%d %H:%M:%S"),
"$lte": datetime.strptime(f"{self.end_date} 23:59:59", "%Y-%m-%d %H:%M:%S")
}
}
}
group_stage = {
"$group": {
"_id": "$sessionId",
"count": {"$sum": 1},
"firstCreatedAt": {"$first": "$createdAt"},
"callerIds": {"$addToSet": "$callerId"},
"totalCost": {"$sum": {"$toDouble": "$total_cost"}},
"totalUsage": {"$sum": {"$toDouble": "$usage"}},
"price": {"$first": {"$toDouble": "$price"}},
"product": {"$first": "$product"}
}
}
sort_stage = {"$sort": {"firstCreatedAt": 1}}
pipeline = [match_stage, group_stage, sort_stage]
if not all_data:
# Aplica paginação se all_data for False
pipeline.extend([
{"$skip": (page - 1) * page_size},
{"$limit": page_size}
])
# Executa pipeline com ou sem paginação
collection = self.mongo_client["billing-api"]["api_usages"]
self.mongo_results = list(collection.aggregate(pipeline))
self.unique_ids = [doc["_id"] for doc in self.mongo_results]
# print("=====> mongoResults: ", self.mongo_results)
# Sempre calcula o total (para controle)
count_pipeline = [
match_stage,
group_stage,
{"$count": "total"}
]
count_result = list(collection.aggregate(count_pipeline))
total = count_result[0]["total"] if count_result else 0
return {
"total": total,
"page": page,
"page_size": page_size,
"total_pages": (total + page_size - 1) // page_size
}
def _fetch_mysql_data(self, hit_report: Optional[bool] = False)-> List[Dict[str, Any]]:
sql = f"""SELECT
uniqueid,
src,
dst,
MIN(calldate) AS start_call,
MAX(calldate) AS end_call,
SUM(CASE
WHEN dstchannel LIKE 'PJSIP/%' AND lastapp = 'Queue'
THEN billsec
ELSE 0
END) AS total_billsec
FROM
tab_cdr
WHERE
uniqueid IN {tuple(self.unique_ids)}
GROUP BY
uniqueid, src, dst;"""
rows = execute_query(self.company_id, sql)
if hit_report:
collection = self.mongo_client["billing-api"]["api_pricings"]
result_stt = collection.find({"type": "stt"})
result_stt = [{"product": t["product"], "clientPrice": t["clientPrice"]} for t in result_stt if "clientPrice" in t]
for row in rows:
row["companyId"] = self.company_id
if rowMongo := next((m for m in self.mongo_results if m["_id"] == row["uniqueid"] ), None):
row["custo_HIT"] = rowMongo["totalCost"]
row["price"] = rowMongo["price"]
p = [p for p in result_stt if p['product'] == rowMongo["product"]]
if len(p) > 0:
row["client_price"] = p[0]["clientPrice"]
# row["client_total_cost"] = calculate_api_usage(float(p[0]["clientPrice"]), 60, float(rowMongo["totalUsage"]))
for key in row:
if isinstance(row[key], datetime):
row[key] = row[key].isoformat(sep=' ')
elif isinstance(row[key], Decimal):
row[key] = float(row[key])
elif key == "uniqueid":
row[key] = str(row[key])
else:
for row in rows:
row["total_min"] = f"{(int(row['total_billsec']) / 60):.2f}"
del row["end_call"]
for key in row:
if isinstance(row[key], datetime):
row[key] = row[key].isoformat(sep=' ')
elif isinstance(row[key], Decimal):
row[key] = float(row[key])
elif key == "uniqueid":
row[key] = str(row[key])
return rows
def _create_excel(self, data: list, hit_report: Optional[bool] = False) -> str:
if hit_report:
header_mapping = {
"companyId": "companyId",
"uniqueid": "sessionId",
"total_billsec": "tempo (billsec)",
"custo_HIT": "custo_HIT",
"price": "tarifa ($/min)",
"client_price": "valor_cobrado"
}
else:
header_mapping = {
"uniqueid": "Identificador da chamada",
"src": "Origem",
"dst": "Destino",
"start_call": "Inicio da Chamada",
"total_billsec": "Duração (Em segundos)",
"total_min": "Duração (Em minutos)"
}
# Filtrar e ordenar os dados conforme header_mapping
selected_keys = list(header_mapping.keys())
filtered_data = [{k: row.get(k, "") for k in selected_keys} for row in data]
df = pd.DataFrame(filtered_data, columns=selected_keys)
# Criação do Excel
wb = Workbook()
ws = wb.active
ws.title = "tab_cdr"
header_font = Font(bold=True)
yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
# Adiciona cabeçalhos personalizados
custom_headers = [header_mapping[col] for col in selected_keys]
ws.append(custom_headers)
for cell in ws[ws.max_row]:
cell.font = header_font
cell.fill = yellow_fill
# Adiciona os dados
for row in df.itertuples(index=False, name=None):
ws.append(row)
# Define caminho e salva o arquivo
filename = f"HISTORICO-CHAMADAS-GRAVADAS-{self.start_date}_{self.end_date}.xlsx"
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
reports_dir = os.path.join(BASE_DIR, "reports")
os.makedirs(reports_dir, exist_ok=True)
path = os.path.join(reports_dir, filename)
wb.save(path)
return path
def reportDataXLSX(self, hit_report: Optional[bool] = False) -> str:
self._fetch_mongo_data(all_data=True)
if hit_report:
mysql_data = self._fetch_mysql_data(hit_report=True)
return self._create_excel(mysql_data, hit_report=True)
mysql_data = self._fetch_mysql_data()
return self._create_excel(mysql_data)
def reportData(self, page: int = 1, page_size: int = 20, hit_report: Optional[bool] = False) -> Dict[str, Any]:
mongo_data = self._fetch_mongo_data(page=page, page_size=page_size)
if hit_report:
mysql_data = self._fetch_mysql_data(hit_report=True)
else:
mysql_data = self._fetch_mysql_data()
return {
"pagination": mongo_data,
"data": mysql_data
}

View File

View File

@ -0,0 +1,5 @@
def calculate_api_usage(price: float, billing_unit: int, usage: float) -> str:
num_billing_units = (usage / billing_unit)
total_cost = num_billing_units * price
return f"{total_cost:.10f}"

View File

@ -0,0 +1,15 @@
from typing import Any
from sqlalchemy import text
from app.db.mysql_router import get_engine_for_company
def execute_query(company_id: str, sql_query: str) -> list[dict[Any, Any]]:
engine = get_engine_for_company(company_id)
try:
with engine.connect() as connection:
result = connection.execute(text(sql_query))
columns = result.keys()
rows = [dict(zip(columns, row)) for row in result]
return rows
except Exception as e:
raise e

2
backend/mypy.ini 100644
View File

@ -0,0 +1,2 @@
[mypy]
ignore_missing_imports = True

View File

6
backend/run.py 100644
View File

@ -0,0 +1,6 @@
from app import create_app
app = create_app()
if __name__ == "__main__":
app.run(host="0.0.0.0", port= app.config["PORT"])

View File

View File

@ -0,0 +1 @@

41
frontend/.gitignore vendored 100644
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
frontend/README.md 100644
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.

View File

@ -0,0 +1,106 @@
"use client"
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { LogOut } from "lucide-react"
import TranscriptionTable from "@/components/transcription-table"
import ModelPricesTable from "@/components/model-prices-table"
import CostUpdateForm from "@/components/cost-update-form"
export default function Dashboard() {
const [isAuthenticated, setIsAuthenticated] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const router = useRouter()
useEffect(() => {
const token = localStorage.getItem("access_token")
if (!token) {
router.push("/")
} else {
setIsAuthenticated(true)
setIsLoading(false)
}
}, [router])
const handleLogout = () => {
localStorage.removeItem("access_token")
router.push("/")
}
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
</div>
)
}
if (!isAuthenticated) {
return null
}
return (
<div className="min-h-screen bg-gray-50">
<header className="bg-white shadow">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between items-center py-6">
<h1 className="text-3xl font-bold text-gray-900">Dashboard - Sistema de Transcrição</h1>
<Button onClick={handleLogout} variant="outline">
<LogOut className="mr-2 h-4 w-4" />
Sair
</Button>
</div>
</div>
</header>
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<Tabs defaultValue="transcription" className="space-y-6">
<TabsList className="grid w-full grid-cols-3">
<TabsTrigger value="transcription">Dados de Transcrição</TabsTrigger>
<TabsTrigger value="models">Preços dos Modelos</TabsTrigger>
<TabsTrigger value="costs">Atualizar Custos</TabsTrigger>
</TabsList>
<TabsContent value="transcription">
<Card>
<CardHeader>
<CardTitle>Dados de Transcrição</CardTitle>
<CardDescription>Visualize e exporte dados de transcrição por cliente ou empresa</CardDescription>
</CardHeader>
<CardContent>
<TranscriptionTable />
</CardContent>
</Card>
</TabsContent>
<TabsContent value="models">
<Card>
<CardHeader>
<CardTitle>Preços dos Modelos</CardTitle>
<CardDescription>Gerencie os preços dos modelos de IA disponíveis</CardDescription>
</CardHeader>
<CardContent>
<ModelPricesTable />
</CardContent>
</Card>
</TabsContent>
<TabsContent value="costs">
<Card>
<CardHeader>
<CardTitle>Atualizar Custos Consumidos</CardTitle>
<CardDescription>Atualize os custos de uso dos produtos consumidos</CardDescription>
</CardHeader>
<CardContent>
<CostUpdateForm />
</CardContent>
</Card>
</TabsContent>
</Tabs>
</main>
</div>
)
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@ -0,0 +1,122 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}

View File

@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Sistema de Trascrição",
description: "Trascriçã de audios de telefonia usando modelos de llm",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}

View File

@ -0,0 +1,43 @@
"use client"
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import LoginForm from "@/components/login-form"
export default function HomePage() {
const [isAuthenticated, setIsAuthenticated] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const router = useRouter()
useEffect(() => {
const token = localStorage.getItem("access_token")
if (token) {
setIsAuthenticated(true)
router.push("/dashboard")
} else {
setIsLoading(false)
}
}, [router])
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-gray-900"></div>
</div>
)
}
return (
<div className="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
<div className="sm:mx-auto sm:w-full sm:max-w-md">
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">Sistema de Transcrição</h2>
<p className="mt-2 text-center text-sm text-gray-600">Faça login para acessar o dashboard</p>
</div>
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
<div className="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
<LoginForm />
</div>
</div>
</div>
)
}

View File

@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View File

@ -0,0 +1,332 @@
"use client"
import type React from "react"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Textarea } from "@/components/ui/textarea"
import { Loader2, Save, RefreshCw } from "lucide-react"
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:5000/api/v1"
interface ModelPrice {
_id: { $oid: string }
provider: string
product: string
currency: string
price: string
billingBy: string
billingUnit: number
type: string
createdAt: { $date: string }
updatedAt: { $date: string }
__v: number
}
interface ModelPricesResponse {
success: boolean
data: ModelPrice[]
}
interface CostUpdateResponse {
success: boolean
docs_updated: number
}
export default function CostUpdateForm() {
const [isLoading, setIsLoading] = useState(false)
const [isLoadingData, setIsLoadingData] = useState(false)
const [error, setError] = useState("")
const [success, setSuccess] = useState("")
// Estados para os dados dos combos
const [products, setProducts] = useState<string[]>([])
const [billingOptions, setBillingOptions] = useState<{ billingBy: string; billingUnit: number }[]>([])
const [formData, setFormData] = useState({
product: "",
start_date: "",
end_date: "",
price: "",
billing_unit: "",
company_ids: "",
})
const getAuthHeaders = () => {
const token = localStorage.getItem("access_token")
return {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
}
}
// Função para buscar dados dos modelos
const fetchModelPrices = async () => {
setIsLoadingData(true)
setError("")
try {
const response = await fetch(`${API_BASE_URL}/usage/model/prices?type=stt`, {
headers: getAuthHeaders(),
})
if (response.ok) {
const result: ModelPricesResponse = await response.json()
if (result.success && Array.isArray(result.data)) {
// Extrair produtos únicos
const uniqueProducts = [...new Set(result.data.map((item) => item.product))]
setProducts(uniqueProducts)
// Extrair opções de billing únicas
const uniqueBillingOptions = result.data.reduce(
(acc, item) => {
const existing = acc.find(
(option) => option.billingBy === item.billingBy && option.billingUnit === item.billingUnit,
)
if (!existing) {
acc.push({
billingBy: item.billingBy,
billingUnit: item.billingUnit,
})
}
return acc
},
[] as { billingBy: string; billingUnit: number }[],
)
setBillingOptions(uniqueBillingOptions)
}
} else {
const errorData = await response.json()
setError(errorData.message || "Erro ao buscar dados dos modelos")
}
} catch (err) {
setError("Erro de conexão com o servidor")
} finally {
setIsLoadingData(false)
}
}
// Carregar dados ao montar o componente
useEffect(() => {
fetchModelPrices()
}, [])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setIsLoading(true)
setError("")
setSuccess("")
try {
// Converte company_ids de string para array (se fornecido)
let company_ids: string[] | undefined
if (formData.company_ids.trim()) {
company_ids = formData.company_ids
.split(",")
.map((id) => id.trim())
.filter((id) => id.length > 0)
}
const payload: any = {
product: formData.product,
start_date: formData.start_date,
end_date: formData.end_date,
price: formData.price,
billing_unit: Number(formData.billing_unit),
}
// Só adiciona company_ids se foi fornecido
if (company_ids && company_ids.length > 0) {
payload.company_ids = company_ids
}
const response = await fetch(`${API_BASE_URL}/usage/cost`, {
method: "PATCH",
headers: getAuthHeaders(),
body: JSON.stringify(payload),
})
if (response.ok) {
const result: CostUpdateResponse = await response.json()
if (result.success) {
setSuccess(`Custos atualizados com sucesso! ${result.docs_updated} registros foram atualizados.`)
setFormData({
product: "",
start_date: "",
end_date: "",
price: "",
billing_unit: "",
company_ids: "",
})
} else {
setError("Erro na resposta do servidor")
}
} else {
const errorData = await response.json()
setError(errorData.message || "Erro ao atualizar custos")
}
} catch (err) {
setError("Erro de conexão com o servidor")
} finally {
setIsLoading(false)
}
}
const handleInputChange = (field: string, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }))
}
const handleBillingChange = (billingBy: string) => {
// Encontrar o billingUnit correspondente
const selectedOption = billingOptions.find((option) => option.billingBy === billingBy)
if (selectedOption) {
setFormData((prev) => ({
...prev,
billing_unit: selectedOption.billingUnit.toString(),
}))
}
}
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center justify-between">
Atualizar Custos de Uso
<Button variant="outline" size="sm" onClick={fetchModelPrices} disabled={isLoadingData}>
{isLoadingData ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
</Button>
</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="product">Produto *</Label>
<Select
value={formData.product}
onValueChange={(value) => handleInputChange("product", value)}
disabled={isLoadingData}
>
<SelectTrigger>
<SelectValue placeholder={isLoadingData ? "Carregando..." : "Selecione um produto"} />
</SelectTrigger>
<SelectContent>
{products.map((product) => (
<SelectItem key={product} value={product}>
{product}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="billing_by">Unidade de Cobrança *</Label>
<Select
value={
billingOptions.find((option) => option.billingUnit.toString() === formData.billing_unit)?.billingBy ||
""
}
onValueChange={handleBillingChange}
disabled={isLoadingData}
>
<SelectTrigger>
<SelectValue placeholder={isLoadingData ? "Carregando..." : "Selecione a unidade"} />
</SelectTrigger>
<SelectContent>
{billingOptions.map((option, index) => (
<SelectItem key={`${option.billingBy}-${option.billingUnit}-${index}`} value={option.billingBy}>
{option.billingBy} ({option.billingUnit})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="start_date">Data Inicial *</Label>
<Input
id="start_date"
type="date"
value={formData.start_date}
onChange={(e) => handleInputChange("start_date", e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="end_date">Data Final *</Label>
<Input
id="end_date"
type="date"
value={formData.end_date}
onChange={(e) => handleInputChange("end_date", e.target.value)}
required
/>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="price">Preço *</Label>
<Input
id="price"
type="text"
value={formData.price}
onChange={(e) => handleInputChange("price", e.target.value)}
placeholder="0.024"
required
/>
</div>
<div className="space-y-2 md:col-span-2">
<Label htmlFor="company_ids">IDs das Empresas (opcional)</Label>
<Textarea
id="company_ids"
value={formData.company_ids}
onChange={(e) => handleInputChange("company_ids", e.target.value)}
placeholder="123, 456, 789 (separados por vírgula - deixe vazio para atualizar todas)"
rows={3}
/>
<p className="text-sm text-gray-500">
Digite os IDs das empresas separados por vírgula. Deixe vazio para atualizar todas as empresas.
</p>
</div>
{/* Campo oculto para mostrar o billing_unit selecionado */}
{formData.billing_unit && (
<div className="space-y-2 md:col-span-2">
<Label>Valor da Unidade de Cobrança</Label>
<Input value={formData.billing_unit} disabled className="bg-gray-50" />
<p className="text-sm text-gray-500">
Este valor é definido automaticamente baseado na unidade de cobrança selecionada.
</p>
</div>
)}
</div>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{success && (
<Alert>
<AlertDescription>{success}</AlertDescription>
</Alert>
)}
<Button type="submit" disabled={isLoading || isLoadingData} className="w-full">
{isLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
Atualizar Custos
</Button>
</form>
</CardContent>
</Card>
)
}

View File

@ -0,0 +1,171 @@
"use client"
import type React from "react"
import { useState } from "react"
import { useRouter } from "next/navigation"
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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Loader2 } from "lucide-react"
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000/api/v1"
export default function LoginForm() {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState("")
const [success, setSuccess] = useState("")
const router = useRouter()
const handleLogin = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
setIsLoading(true)
setError("")
const formData = new FormData(e.currentTarget)
const email = formData.get("email") as string
const password = formData.get("password") as string
try {
console.log(`${API_BASE_URL}/auth/login`)
const response = await fetch(`${API_BASE_URL}/auth/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
})
const data = await response.json()
if (response.ok) {
localStorage.setItem("access_token", data.access_token)
router.push("/dashboard")
} else {
setError(data.message || "Erro ao fazer login")
}
} catch (err) {
setError("Erro de conexão com o servidor")
} finally {
setIsLoading(false)
}
}
const handleSignup = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
setIsLoading(true)
setError("")
setSuccess("")
const formData = new FormData(e.currentTarget)
const email = formData.get("email") as string
const password = formData.get("password") as string
try {
const response = await fetch(`${API_BASE_URL}/auth/signup`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
})
const data = await response.json()
if (response.ok) {
setSuccess("Usuário criado com sucesso! Faça login para continuar.")
} else {
setError(data.message || "Erro ao criar usuário")
}
} catch (err) {
setError("Erro de conexão com o servidor")
} finally {
setIsLoading(false)
}
}
return (
<Tabs defaultValue="login" className="w-full">
<TabsList className="grid w-full grid-cols-1">
<TabsTrigger value="login">Login</TabsTrigger>
{/* <TabsTrigger value="signup">Cadastro</TabsTrigger> */}
</TabsList>
<TabsContent value="login">
<Card>
<CardHeader>
<CardTitle>Login</CardTitle>
<CardDescription>Entre com suas credenciais para acessar o sistema</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleLogin} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="login-email">Email</Label>
<Input id="login-email" name="email" type="email" required placeholder="seu@email.com" />
</div>
<div className="space-y-2">
<Label htmlFor="login-password">Senha</Label>
<Input id="login-password" name="password" type="password" required placeholder="Sua senha" />
</div>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Entrar
</Button>
</form>
</CardContent>
</Card>
</TabsContent>
<TabsContent value="signup">
<Card>
<CardHeader>
<CardTitle>Cadastro</CardTitle>
<CardDescription>Crie uma nova conta para acessar o sistema</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSignup} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="signup-email">Email</Label>
<Input id="signup-email" name="email" type="email" required placeholder="seu@email.com" />
</div>
<div className="space-y-2">
<Label htmlFor="signup-password">Senha</Label>
<Input
id="signup-password"
name="password"
type="password"
required
placeholder="Sua senha"
minLength={8}
/>
</div>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{success && (
<Alert>
<AlertDescription>{success}</AlertDescription>
</Alert>
)}
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Criar Conta
</Button>
</form>
</CardContent>
</Card>
</TabsContent>
</Tabs>
)
}

View File

@ -0,0 +1,443 @@
"use client"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Edit2, Save, X, Loader2, RefreshCw } from "lucide-react"
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000/api/v1"
// Atualizar a interface ModelPrice para refletir a nova estrutura da API:
interface ModelPrice {
_id: {
$oid: string
}
provider: string
product: string
type: string
billingBy: string
billingUnit: number
currency: string
price: string
clientPrice?: string // Campo opcional que pode não vir da API
createdAt: {
$date: string
}
updatedAt: {
$date: string
}
__v: number
}
// Interface para a resposta da API:
interface ApiResponse {
success: boolean
data: ModelPrice[]
}
export default function ModelPricesTable() {
const [data, setData] = useState<ModelPrice[]>([])
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState("")
const [editingId, setEditingId] = useState<string | null>(null)
// Atualizar editValues para incluir todos os campos editáveis:
const [editValues, setEditValues] = useState<{
product: string
provider: string
type: string
billingBy: string
billingUnit: string
currency: string
clientPrice: string
price: string
}>({
product: "",
provider: "",
type: "",
billingBy: "",
billingUnit: "",
currency: "",
clientPrice: "",
price: "",
})
const [isSaving, setIsSaving] = useState(false)
// Filtros
const [typeFilter, setTypeFilter] = useState("stt")
const [providerFilter, setProviderFilter] = useState("")
const getAuthHeaders = () => {
const token = localStorage.getItem("access_token")
return {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
}
}
const fetchData = async () => {
setIsLoading(true)
setError("")
try {
const params = new URLSearchParams()
if (typeFilter) params.append("type", typeFilter)
if (providerFilter) params.append("provider", providerFilter)
const response = await fetch(`${API_BASE_URL}/usage/model/prices?${params}`, {
headers: getAuthHeaders(),
})
if (response.ok) {
// Atualizar o processamento da resposta para a nova estrutura:
const result: ApiResponse = await response.json()
if (result.success && Array.isArray(result.data)) {
setData(result.data)
} else {
setData([])
}
} else {
const errorData = await response.json()
setError(errorData.message || "Erro ao buscar dados")
}
} catch (err) {
setError("Erro de conexão com o servidor")
} finally {
setIsLoading(false)
}
}
// Atualizar a função startEdit para trabalhar com todos os campos:
const startEdit = (item: ModelPrice) => {
const id = item._id.$oid
setEditingId(id)
setEditValues({
product: item.product,
provider: item.provider,
type: item.type,
billingBy: item.billingBy,
billingUnit: item.billingUnit.toString(),
currency: item.currency,
clientPrice: item.clientPrice || "",
price: item.price,
})
}
const cancelEdit = () => {
setEditingId(null)
setEditValues({
product: "",
provider: "",
type: "",
billingBy: "",
billingUnit: "",
currency: "",
clientPrice: "",
price: "",
})
}
// Atualizar a função saveEdit para enviar todos os campos:
const saveEdit = async (id: string) => {
setIsSaving(true)
setError("")
try {
const response = await fetch(`${API_BASE_URL}/usage/model/prices/${id}`, {
method: "PATCH",
headers: getAuthHeaders(),
body: JSON.stringify({
product: editValues.product,
provider: editValues.provider,
type: editValues.type,
billingBy: editValues.billingBy,
billingUnit: Number.parseInt(editValues.billingUnit),
currency: editValues.currency,
clientPrice: editValues.clientPrice,
price: editValues.price,
}),
})
if (response.ok) {
await fetchData() // Recarrega os dados
setEditingId(null)
setEditValues({
product: "",
provider: "",
type: "",
billingBy: "",
billingUnit: "",
currency: "",
clientPrice: "",
price: "",
})
} else {
const errorData = await response.json()
setError(errorData.message || "Erro ao salvar alterações")
}
} catch (err) {
setError("Erro de conexão com o servidor")
} finally {
setIsSaving(false)
}
}
useEffect(() => {
fetchData()
}, [])
// Opções para os selects
const typeOptions = ["stt", "tts", "llm", "embedding", "vision"]
const providerOptions = ["openai", "aws", "google", "anthropic", "mistral", "azure"]
const currencyOptions = ["dollar", "real", "euro"]
const billingByOptions = ["second", "minute", "character", "token", "image", "request"]
return (
<div className="space-y-6">
{/* Filtros */}
<Card>
<CardHeader>
<CardTitle>Filtros</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-2">
<Label htmlFor="typeFilter">Tipo</Label>
<Input
id="typeFilter"
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value)}
placeholder="stt,tts"
/>
</div>
<div className="space-y-2">
<Label htmlFor="providerFilter">Provedor</Label>
<Input
id="providerFilter"
value={providerFilter}
onChange={(e) => setProviderFilter(e.target.value)}
placeholder="openai,aws"
/>
</div>
<div className="space-y-2">
<Label>&nbsp;</Label>
<Button onClick={fetchData} disabled={isLoading} className="w-full">
{isLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <RefreshCw className="mr-2 h-4 w-4" />}
Atualizar
</Button>
</div>
</div>
</CardContent>
</Card>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Tabela de Preços */}
<Card>
<CardHeader>
<CardTitle>Preços dos Modelos ({data.length} modelos)</CardTitle>
</CardHeader>
<CardContent>
{data.length > 0 ? (
<div className="overflow-x-auto">
{/* Atualizar a tabela para exibir os novos campos: */}
<Table>
<TableHeader>
<TableRow>
<TableHead>Produto</TableHead>
<TableHead>Provedor</TableHead>
<TableHead>Tipo</TableHead>
<TableHead>Cobrança Por</TableHead>
<TableHead>Unidade</TableHead>
<TableHead>Moeda</TableHead>
<TableHead>Preço</TableHead>
<TableHead>Preço Cliente</TableHead>
<TableHead>Ações</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.map((item) => {
const itemId = item._id.$oid
const isEditing = editingId === itemId
return (
<TableRow key={itemId}>
<TableCell>
{isEditing ? (
<Input
value={editValues.product}
onChange={(e) => setEditValues((prev) => ({ ...prev, product: e.target.value }))}
className="w-32"
/>
) : (
item.product || "-"
)}
</TableCell>
<TableCell>
{isEditing ? (
<Select
value={editValues.provider}
onValueChange={(value) => setEditValues((prev) => ({ ...prev, provider: value }))}
>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
{providerOptions.map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<Badge variant="secondary">{item.provider}</Badge>
)}
</TableCell>
<TableCell>
{isEditing ? (
<Select
value={editValues.type}
onValueChange={(value) => setEditValues((prev) => ({ ...prev, type: value }))}
>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
{typeOptions.map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<Badge variant="outline">{item.type}</Badge>
)}
</TableCell>
<TableCell>
{isEditing ? (
<Select
value={editValues.billingBy}
onValueChange={(value) => setEditValues((prev) => ({ ...prev, billingBy: value }))}
>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
{billingByOptions.map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
item.billingBy
)}
</TableCell>
<TableCell>
{isEditing ? (
<Input
type="number"
value={editValues.billingUnit}
onChange={(e) => setEditValues((prev) => ({ ...prev, billingUnit: e.target.value }))}
className="w-20"
/>
) : (
item.billingUnit
)}
</TableCell>
<TableCell>
{isEditing ? (
<Select
value={editValues.currency}
onValueChange={(value) => setEditValues((prev) => ({ ...prev, currency: value }))}
>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
{currencyOptions.map((option) => (
<SelectItem key={option} value={option}>
{option}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<Badge variant="outline">{item.currency}</Badge>
)}
</TableCell>
<TableCell>
{isEditing ? (
<Input
type="number"
step="0.0001"
value={editValues.price}
onChange={(e) => setEditValues((prev) => ({ ...prev, price: e.target.value }))}
className="w-24"
/>
) : (
`$${item.price}`
)}
</TableCell>
<TableCell>
{isEditing ? (
<Input
type="number"
step="0.0001"
value={editValues.clientPrice}
onChange={(e) => setEditValues((prev) => ({ ...prev, clientPrice: e.target.value }))}
className="w-24"
placeholder="0.000"
/>
) : item.clientPrice ? (
`$${item.clientPrice}`
) : (
"-"
)}
</TableCell>
<TableCell>
{isEditing ? (
<div className="flex gap-2">
<Button size="sm" onClick={() => saveEdit(itemId)} disabled={isSaving}>
{isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
</Button>
<Button size="sm" variant="outline" onClick={cancelEdit} disabled={isSaving}>
<X className="h-4 w-4" />
</Button>
</div>
) : (
<Button size="sm" variant="outline" onClick={() => startEdit(item)}>
<Edit2 className="h-4 w-4" />
</Button>
)}
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</div>
) : (
<div className="text-center py-8 text-gray-500">
{isLoading ? "Carregando..." : "Nenhum modelo encontrado."}
</div>
)}
</CardContent>
</Card>
</div>
)
}

View File

@ -0,0 +1,432 @@
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Download, Search, Loader2 } from "lucide-react"
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000/api/v1"
// Primeiro, vamos atualizar as interfaces para os diferentes tipos de dados
// Substitua a interface TranscriptionData existente com estas interfaces:
interface ClientTranscriptionData {
uniqueid: string
src: string
dst: string
start_call: string
total_billsec: number
total_min: string
}
interface HitTranscriptionData {
uniqueid: string
src: string
dst: string
start_call: string
end_call: string
total_billsec: number
companyId: string
custo_HIT: number
price: number
client_price: string
}
type TranscriptionData = ClientTranscriptionData | HitTranscriptionData
// Primeiro, vamos atualizar as interfaces para refletir a nova estrutura da API:
interface PaginationInfo {
total: number
page: number
page_size: number
total_pages: number
}
interface ApiResponse {
success: boolean
data: {
data: TranscriptionData[]
pagination: PaginationInfo
}
}
export default function TranscriptionTable() {
// Agora, atualize o estado para usar o tipo correto
// Substitua a linha do useState por:
const [data, setData] = useState<TranscriptionData[]>([])
const [isLoading, setIsLoading] = useState(false)
const [isExporting, setIsExporting] = useState(false)
const [error, setError] = useState("")
// Filtros
const [companyId, setCompanyId] = useState("")
const [startDate, setStartDate] = useState("")
const [endDate, setEndDate] = useState("")
// E atualize a definição do estado who:
const [who, setWho] = useState<"client" | "hit">("client")
// Adicionar estados para paginação após os estados existentes:
const [pagination, setPagination] = useState<PaginationInfo>({
total: 0,
page: 1,
page_size: 20,
total_pages: 0,
})
const [currentPage, setCurrentPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
const getAuthHeaders = () => {
const token = localStorage.getItem("access_token")
return {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
}
}
// Atualizar a função fetchData para incluir parâmetros de paginação:
const fetchData = async (page: number = currentPage) => {
if (!companyId || !startDate || !endDate) {
setError("Preencha todos os campos obrigatórios")
return
}
setIsLoading(true)
setError("")
try {
const params = new URLSearchParams({
companyId,
startDate,
endDate,
who,
page: page.toString(),
page_size: pageSize.toString(),
})
const response = await fetch(`${API_BASE_URL}/usage/data/trascription?${params}`, {
headers: getAuthHeaders(),
})
if (response.ok) {
const result: ApiResponse = await response.json()
if (result.success && result.data) {
setData(result.data.data || [])
setPagination(result.data.pagination)
setCurrentPage(result.data.pagination.page)
} else {
setData([])
setPagination({ total: 0, page: 1, page_size: 20, total_pages: 0 })
}
} else {
const errorData = await response.json()
setError(errorData.message || "Erro ao buscar dados")
}
} catch (err) {
setError("Erro de conexão com o servidor")
} finally {
setIsLoading(false)
}
}
const exportToExcel = async () => {
if (!companyId || !startDate || !endDate) {
setError("Preencha todos os campos obrigatórios")
return
}
setIsExporting(true)
setError("")
try {
const params = new URLSearchParams({
companyId,
startDate,
endDate,
who,
})
const response = await fetch(`${API_BASE_URL}/usage/export/trascription?${params}`, {
headers: getAuthHeaders(),
})
if (response.ok) {
const blob = await response.blob()
const url = window.URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = `transcription-report-${who}-${startDate}-${endDate}.xlsx`
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(a)
} else {
const errorData = await response.json()
setError(errorData.message || "Erro ao exportar dados")
}
} catch (err) {
setError("Erro de conexão com o servidor")
} finally {
setIsExporting(false)
}
}
// Adicionar funções de navegação de páginas:
const goToPage = (page: number) => {
if (page >= 1 && page <= pagination.total_pages) {
setCurrentPage(page)
fetchData(page)
}
}
const goToFirstPage = () => goToPage(1)
const goToPreviousPage = () => goToPage(currentPage - 1)
const goToNextPage = () => goToPage(currentPage + 1)
const goToLastPage = () => goToPage(pagination.total_pages)
return (
<div className="space-y-6">
{/* Filtros */}
<Card>
<CardHeader>
<CardTitle>Filtros de Consulta</CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4">
<div className="space-y-2">
<Label htmlFor="companyId">ID da Empresa *</Label>
<Input
id="companyId"
value={companyId}
onChange={(e) => setCompanyId(e.target.value)}
placeholder="123"
/>
</div>
<div className="space-y-2">
<Label htmlFor="startDate">Data Inicial *</Label>
<Input id="startDate" type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="endDate">Data Final *</Label>
<Input id="endDate" type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="who">Tipo de Consulta *</Label>
{/* Também vamos atualizar o Select para usar "hit" em vez de "company"
// Substitua o componente Select para o campo "who": */}
<Select value={who} onValueChange={(value: "client" | "hit") => setWho(value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="client">Cliente</SelectItem>
<SelectItem value="hit">HIT</SelectItem>
</SelectContent>
</Select>
</div>
{/* Adicionar seletor de tamanho de página nos filtros: */}
<div className="space-y-2">
<Label htmlFor="pageSize">Registros por página</Label>
<Select
value={pageSize.toString()}
onValueChange={(value) => {
setPageSize(Number(value))
setCurrentPage(1)
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="10">10</SelectItem>
<SelectItem value="20">20</SelectItem>
<SelectItem value="50">50</SelectItem>
<SelectItem value="100">100</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>&nbsp;</Label>
<div className="flex gap-2">
<Button onClick={() => fetchData(1)} disabled={isLoading} className="flex-1">
{isLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Search className="mr-2 h-4 w-4" />}
Buscar
</Button>
<Button onClick={exportToExcel} disabled={isExporting || data.length === 0} variant="outline">
{isExporting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
</Button>
</div>
</div>
</div>
</CardContent>
</Card>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{/* Tabela de Dados */}
<Card>
<CardHeader>
{/* Atualizar o título da tabela para mostrar informações de paginação: */}
<CardTitle>
Resultados da Consulta
{pagination.total > 0 && (
<span className="text-sm font-normal text-gray-500 ml-2">
(Página {currentPage} de {pagination.total_pages} - {pagination.total} registros total)
</span>
)}
</CardTitle>
</CardHeader>
<CardContent>
{/* Agora, atualize a parte da tabela para exibir colunas diferentes com base no valor de who
// Substitua a seção da tabela com: */}
{data.length > 0 ? (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>ID Único</TableHead>
<TableHead>Origem</TableHead>
<TableHead>Destino</TableHead>
<TableHead>Início</TableHead>
{who === "hit" && <TableHead>Fim</TableHead>}
<TableHead>Duração (s)</TableHead>
{who === "client" ? (
<TableHead>Total (min)</TableHead>
) : (
<>
<TableHead>Empresa</TableHead>
<TableHead>Custo HIT</TableHead>
<TableHead>Preço</TableHead>
<TableHead>Preço Cliente</TableHead>
</>
)}
</TableRow>
</TableHeader>
<TableBody>
{data.map((item, index) => (
<TableRow key={item.uniqueid || index}>
<TableCell>{item.uniqueid || "-"}</TableCell>
<TableCell>{item.src || "-"}</TableCell>
<TableCell>{item.dst || "-"}</TableCell>
<TableCell>{item.start_call || "-"}</TableCell>
{who === "hit" && <TableCell>{(item as HitTranscriptionData).end_call || "-"}</TableCell>}
<TableCell>{item.total_billsec || "-"}</TableCell>
{who === "client" ? (
<TableCell>{(item as ClientTranscriptionData).total_min || "-"}</TableCell>
) : (
<>
<TableCell>{(item as HitTranscriptionData).companyId || "-"}</TableCell>
<TableCell>
{(item as HitTranscriptionData).custo_HIT
? `$${(item as HitTranscriptionData).custo_HIT.toFixed(6)}`
: "-"}
</TableCell>
<TableCell>
{(item as HitTranscriptionData).price
? `$${(item as HitTranscriptionData).price.toFixed(4)}`
: "-"}
</TableCell>
<TableCell>
{(item as HitTranscriptionData).client_price
? `$${(item as HitTranscriptionData).client_price}`
: "-"}
</TableCell>
</>
)}
</TableRow>
))}
</TableBody>
</Table>
</div>
) : (
<div className="text-center py-8 text-gray-500">
Nenhum dado encontrado. Use os filtros acima para buscar dados.
</div>
)}
{/* Componente de Paginação */}
{pagination.total > 0 && (
<div className="flex items-center justify-between px-2 py-4">
<div className="flex items-center space-x-2">
<p className="text-sm text-gray-700">
Mostrando <span className="font-medium">{(currentPage - 1) * pagination.page_size + 1}</span> até{" "}
<span className="font-medium">{Math.min(currentPage * pagination.page_size, pagination.total)}</span>{" "}
de <span className="font-medium">{pagination.total}</span> resultados
</p>
</div>
<div className="flex items-center space-x-2">
<div className="flex items-center space-x-1">
<Button variant="outline" size="sm" onClick={goToFirstPage} disabled={currentPage === 1}>
Primeira
</Button>
<Button variant="outline" size="sm" onClick={goToPreviousPage} disabled={currentPage === 1}>
Anterior
</Button>
<div className="flex items-center space-x-1">
{/* Páginas numeradas */}
{Array.from({ length: Math.min(5, pagination.total_pages) }, (_, i) => {
let pageNum
if (pagination.total_pages <= 5) {
pageNum = i + 1
} else if (currentPage <= 3) {
pageNum = i + 1
} else if (currentPage >= pagination.total_pages - 2) {
pageNum = pagination.total_pages - 4 + i
} else {
pageNum = currentPage - 2 + i
}
return (
<Button
key={pageNum}
variant={currentPage === pageNum ? "default" : "outline"}
size="sm"
onClick={() => goToPage(pageNum)}
className="w-10"
>
{pageNum}
</Button>
)
})}
</div>
<Button
variant="outline"
size="sm"
onClick={goToNextPage}
disabled={currentPage === pagination.total_pages}
>
Próxima
</Button>
<Button
variant="outline"
size="sm"
onClick={goToLastPage}
disabled={currentPage === pagination.total_pages}
>
Última
</Button>
</div>
</div>
</div>
)}
</CardContent>
</Card>
</div>
)
}

View File

@ -0,0 +1,66 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }

View File

@ -0,0 +1,46 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant,
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "span"
return (
<Comp
data-slot="badge"
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@ -0,0 +1,59 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View File

@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@ -0,0 +1,185 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "popper",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@ -0,0 +1,66 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
function Tabs({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function TabsList({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.List>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
className={cn(
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
className
)}
{...props}
/>
)
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent }

View File

@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
{...props}
/>
)
}
export { Textarea }

View File

@ -0,0 +1,16 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
];
export default eslintConfig;

View File

@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View File

@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

6494
frontend/package-lock.json generated 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,36 @@
{
"name": "transcriptio-usage-frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@radix-ui/react-label": "^2.1.7",
"@radix-ui/react-select": "^2.2.5",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-tabs": "^1.1.12",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.513.0",
"next": "15.2.4",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tailwind-merge": "^3.3.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.2.4",
"tailwindcss": "^4",
"tw-animate-css": "^1.3.4",
"typescript": "^5"
}
}

View File

@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

View File

@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View File

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

View File

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}