Skip to content

Commit

Permalink
fucking vs code
Browse files Browse the repository at this point in the history
  • Loading branch information
Piyuuussshhh committed Sep 17, 2024
1 parent 280b1a5 commit 0cca2a3
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 48 deletions.
69 changes: 49 additions & 20 deletions src-tauri/src/export.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
use headless_chrome::{Browser, LaunchOptions};
use rusqlite::Connection;
use std::{collections::HashMap, fs::File, io::Write, path::PathBuf};
use tauri::api::dialog::FileDialogBuilder;

use crate::db::ops::{
crud_commands::{get_all_tasks, get_item},
FetchBasis,
use tauri::{api::dialog::FileDialogBuilder, State};

use crate::db::{
init::DbConn,
todos::{
commands::{fetch_todos, TODAY},
FetchBasis, Todo,
},
};

fn get_python_input(tasks: &[(u64, String)]) -> Vec<(String, String)> {
fn get_python_input(conn: &Connection, todos: &[Todo]) -> Vec<(String, String)> {
let mut res: Vec<(String, String)> = Vec::new();
for (parent_id, name) in tasks.iter() {
let parent_name = get_item(*parent_id);
res.push((parent_name, name.clone()));
for todo in todos.iter() {
if todo.id == 0 {
continue;
}
let parent = match fetch_todos(conn, TODAY, FetchBasis::ById(todo.parent_group_id.unwrap()))
{
Ok(parent_group) => parent_group,
Err(e) => panic!("[ERROR] why tf is python is still here: {e}"),
};
res.push((parent[0].name.clone(), todo.name.clone()));
}
res
}
Expand Down Expand Up @@ -63,9 +74,9 @@ fn generate_ordered_list(map: HashMap<String, Vec<String>>, is_completed: bool)
html
}

fn generate_html(active_tasks: Vec<(u64, String)>, completed_tasks: Vec<(u64, String)>) -> String {
let active_tasks_inp: Vec<(String, String)> = get_python_input(&active_tasks);
let completed_tasks_inp: Vec<(String, String)> = get_python_input(&completed_tasks);
fn generate_html(conn: &Connection, active_tasks: Vec<Todo>, completed_tasks: Vec<Todo>) -> String {
let active_tasks_inp: Vec<(String, String)> = get_python_input(conn, &active_tasks);
let completed_tasks_inp: Vec<(String, String)> = get_python_input(conn, &completed_tasks);

let pdf_css = format!(
"
Expand Down Expand Up @@ -132,7 +143,7 @@ fn generate_html(active_tasks: Vec<(u64, String)>, completed_tasks: Vec<(u64, St
)
}

fn generate_pdf(html: String, pdf_name: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
fn generate_pdf(html: String) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let browser = Browser::new(LaunchOptions {
headless: true,
..Default::default()
Expand All @@ -146,27 +157,45 @@ fn generate_pdf(html: String, pdf_name: PathBuf) -> Result<(), Box<dyn std::erro

let pdf_data = tab.print_to_pdf(None)?;

Ok(pdf_data)
}

fn write_pdf(pdf_data: Vec<u8>, pdf_name: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
let mut file = File::create(pdf_name)?;
file.write_all(&pdf_data)?;

Ok(())
}

#[tauri::command]
pub fn export_to_pdf() {
let active_tasks = get_all_tasks(FetchBasis::Active);
let completed_tasks = get_all_tasks(FetchBasis::Completed);
pub fn export_to_pdf(db_conn: State<'_, DbConn>) {
let conn = db_conn.lock().unwrap();
let active_tasks = match fetch_todos(&conn, TODAY, FetchBasis::Active) {
Ok(todos) => todos,
Err(_) => return,
};
let completed_tasks = match fetch_todos(&conn, TODAY, FetchBasis::Completed) {
Ok(todos) => todos,
Err(_) => return,
};

// Since we are forming the pdf before we start to save the file, this takes some time
// and the app sort of hangs for a period of time before the file dialog shows up.
let pdf = match generate_pdf(generate_html(&conn, active_tasks, completed_tasks)) {
Ok(data) => data,
Err(e) => {
println!("[ERROR] Couldn't generate pdf: {e}");
return;
}
};

FileDialogBuilder::new()
.set_title("Export Tasks to PDF")
.add_filter("PDF files", &["pdf"])
.set_file_name("Today's Tasks.pdf")
.save_file(move |path| {
if let Some(path) = path {
match generate_pdf(
generate_html(active_tasks, completed_tasks),
path
) {
match write_pdf(pdf, path) {
Ok(_) => (),
Err(err) => println!("{err}"),
}
Expand Down
31 changes: 20 additions & 11 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,37 @@

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command

use habtrack::{db::{init::DbInitializer, ops}, window, export};
use std::sync::{Arc, Mutex};

use habtrack::{db::init, db::todos, window, export};
use tauri::Manager;

// Start work on database.
// TODO: Once done, merge with main, and pull changes into FEATURE-add-delete-task.



fn main() {
tauri::Builder::default()
.setup(|app| {
let db_init_obj = DbInitializer::new(app.handle()).init();
ops::DB_SINGLETON
.lock()
.unwrap()
.set_conn(db_init_obj.get_db_path().as_str())
.expect("i fucked up");
let db_path = match app.path_resolver().app_data_dir() {
Some(p) => p.to_string_lossy().into_owned(),
None => panic!("[ERROR] Cannot find data directory on this device!"),
};

let conn = init::init(&db_path);
init::create_tables(&conn).unwrap();
init::migrate_todos(&conn).unwrap();

app.manage(Arc::new(Mutex::new(conn)));

Ok(())
})
.invoke_handler(tauri::generate_handler![
ops::crud_commands::get_tasks_view,
ops::crud_commands::add_item,
ops::crud_commands::delete_item,
ops::crud_commands::update_item,
todos::commands::get_todos,
todos::commands::add_todo,
todos::commands::delete_todo,
todos::commands::update_todo,
window::open_tomorrow_window,
window::close_tomorrow_window,
export::export_to_pdf,
Expand Down
8 changes: 4 additions & 4 deletions src/Constants.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ const TASK = "Task";
const TASK_GROUP = "TaskGroup";
const ACTIVE_TASKS = true;
const COMPLETED_TASKS = false;
const TAURI_FETCH_TASKS_VIEW = "get_tasks_view";
const TAURI_ADD_ITEM = "add_item";
const TAURI_DELETE_ITEM = "delete_item";
const TAURI_UPDATE_ITEM = "update_item";
const TAURI_FETCH_TASKS_VIEW = "get_todos";
const TAURI_ADD_ITEM = "add_todo";
const TAURI_DELETE_ITEM = "delete_todo";
const TAURI_UPDATE_ITEM = "update_todo";

// New Window.
const TAURI_OPEN_TOMORROW_WINDOW = "open_tomorrow_window";
Expand Down
19 changes: 10 additions & 9 deletions src/components/CompletedTasksModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const CompletedTasksModal = ({ onChangeTasksView, onCancel }) => {
status: COMPLETED_TASKS,
});
const data = JSON.parse(response);
console.log(JSON.stringify(data));

setCompletedStructure(data);
} catch (error) {
Expand All @@ -42,26 +43,26 @@ const CompletedTasksModal = ({ onChangeTasksView, onCancel }) => {
// Update db.
invoke(TAURI_UPDATE_ITEM, {
table: TODAY,
id: item[0],
id: item.id,
field: { Status: false },
});

// Update frontend of completed tasks view.
setCompletedStructure(
completedStructure.filter((child) => child[0] != item[0])
completedStructure.filter((child) => child.id != item.id)
);
// Update frontend of active tasks view.
updateFrontend(
addItem,
TASKS_VIEW,
onChangeTasksView,
{
id: item[0],
name: item[1],
id: item.id,
name: item.name,
type: TASK,
parentId: item[item.length - 1],
parentId: item.parent_group_id,
},
item[item.length - 1]
item.parent_group_id
);
};

Expand All @@ -81,11 +82,11 @@ const CompletedTasksModal = ({ onChangeTasksView, onCancel }) => {
>
<ul>
{completedStructure.map((node) => {
console.log("this is the node:" + node);
console.log("this is the node:" + JSON.stringify(node));
return (
<li key={node[0]}>
<li key={node.id}>
<div className="completed-task">
<label>{node[1]}</label>
<label>{node.name}</label>
<button
type="button"
className="task-btn"
Expand Down
4 changes: 4 additions & 0 deletions src/views/TasksView/DragDropContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ const DragDropProvider = ({ children, item, dbTable }) => {
// basically event.dataTransfer.getData() always returns a string.
const droppedItemId = Number(event.dataTransfer.getData("text/plain"));

// There is a redundant command call when the todo is dropped in the
// same group of its origin. No update is made, and simply the database
// is queried. Fix that.

invoke(TAURI_UPDATE_ITEM, {
table: dbTable,
id: droppedItemId,
Expand Down
2 changes: 1 addition & 1 deletion src/views/TasksView/Task.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const Task = (props) => {
invoke(TAURI_DELETE_ITEM, {
table: props.dbTable,
id: props.id,
item_type: TASK,
todo_type: {type: TASK},
});

// Delete task from the frontend.
Expand Down
2 changes: 1 addition & 1 deletion src/views/TasksView/TaskGroup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ const TaskGroup = ({
invoke(TAURI_DELETE_ITEM, {
table: dbTable,
id: id,
item_type: TASK_GROUP,
todo_type: {type: TASK_GROUP},
});

// Deleting group from front-end.
Expand Down
2 changes: 1 addition & 1 deletion src/views/TasksView/TasksView.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const TasksView = ({ isSidebarOpen, mainAreaRef }) => {
table: TODAY,
name: name,
parent_group_id: parentGroupId,
item_type: option,
todo_type: option === TASK ? { type: TASK } : { type: TASK_GROUP },
})
.then((id) => {
let isActive = option === TASK ? true : null;
Expand Down
2 changes: 1 addition & 1 deletion src/views/TasksView/Tomorrow/TomorrowView.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ const TomorrowView = () => {
table: TOMORROW,
name: name,
parent_group_id: parentGroupId,
item_type: option,
todo_type: option === TASK ? { type: TASK } : { type: TASK_GROUP },
})
.then((id) => {
let isActive = option === TASK ? true : null;
Expand Down

0 comments on commit 0cca2a3

Please sign in to comment.