-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
190 lines (165 loc) · 9.07 KB
/
main.ts
File metadata and controls
190 lines (165 loc) · 9.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import { Plugin, PluginSettingTab, Setting, App, TFile } from 'obsidian';
import { BearableDataImportSettingsTab } from 'src/settings';
import { findDailyNote, getCurrentDate } from 'src/utils';
import { importMoodData } from 'src/dataTypes/moodData'; // Import the function to import mood data
import { importEnergyData } from 'src/dataTypes/energyData'; // Import the function to import energy data
import { importSleepData } from 'src/dataTypes/sleepData'; // Import the function to import sleep data
import { importHealthMeasurementsData } from 'src/dataTypes/healthMeasurementsData'; // Import the function to import health measurements data
import { importSymptomData } from 'src/dataTypes/symptomData'; // Import the function to import symptom data
import { importMedsData } from 'src/dataTypes/medsData'; // Import the function to import meds data)
import { importCustomData } from 'src/dataTypes/customData'; // Import the function to import custom data
import { importBmData } from 'src/dataTypes/bowelMovementData'; // Import the function to import bowel movement data
export interface BearableDataImportSettings {
csvFilePath: string; // Path to the CSV file within the vault
dateFormat: string; // Date format for the daily notes
headerName: string; // New field to specify the header name
importMood: boolean; // Toggle to import or ignore Mood data
importEnergy: boolean; // Toggle to import or ignore Energy data
importSleep: boolean; // Toggle to import or ignore Sleep data
importHealthMeasurements: boolean; // Toggle to import or ignore Health Measurements data
importSymptoms: boolean; // Toggle to import or ignore Symptoms data
importMeds: boolean; // Toggle to import or ignore Medication & Suppluments data
importCustomRatings: boolean; // Toggle to import or ignore Custom Ratings data
customRatingsList: string; // List of custom ratings to import
importBm: boolean; // Toggle to import or ignore Bowel Movement data
}
export const DEFAULT_SETTINGS: BearableDataImportSettings = {
csvFilePath: 'Resources/bearable-export.csv', // Default file location
dateFormat: 'YYYY-MM-DD', // Default date format
headerName: 'Daily Recap', // Default header name
importMood: true, // Default to import Mood data
importEnergy: true, // Default to import Energy data
importSleep: true, // Default to import Sleep data
importHealthMeasurements: true, // Default to import Health Measurements data
importSymptoms: true, // Default to import Symptoms dataratingAmount
importMeds: true, // Default to import Medication & Suppluments data
importCustomRatings: true, // Default to import Custom Ratings data
customRatingsList: 'Productivity, Mindfulness, Social life, Love life, Family life, Hygiene, Relaxation', // Default custom ratings list
importBm: true, // Default to import Bowel Movement data
};
export default class BearableDataImportPlugin extends Plugin {
settings: BearableDataImportSettings;
headerName: any;
importMood: any;
importEnergy: any;
importSleep: any;
importHealthMeasurements: any;
importSymptoms: any;
importMeds: any;
importCustomRatings: any;
customRatingsList: any;
importBm: any;
async onload() {
await this.loadSettings();
//console.log("Loaded settings:", this.settings); // Debugging line
this.addSettingTab(new BearableDataImportSettingsTab(this.app, this));
this.addCommand({
id: 'import-bearable-data',
name: 'Import Bearable Data',
callback: () => this.convertCSVToMarkdown(),
});
}
async loadSettings() {
// Load settings and provide default if not previously saved
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
async convertCSVToMarkdown() {
const csvFile = this.app.vault.getAbstractFileByPath(this.settings.csvFilePath);
if (csvFile instanceof TFile) {
const csvData = await this.app.vault.read(csvFile);
const rows = this.parseCSV(csvData);
const newData = this.importData(rows, this.settings);
const dailyNote = findDailyNote(this.app, this.settings.dateFormat);
if (dailyNote) {
const noteContent = await this.app.vault.read(dailyNote);
const updatedContent = this.updateNoteContent(noteContent, newData, this.settings.headerName);
await this.app.vault.modify(dailyNote, updatedContent);
console.log("Data written to daily note under header:", this.settings.headerName);
} else {
console.log("Daily note not found for date:", this.settings.dateFormat);
}
} else {
console.log("CSV file not found at path:", this.settings.csvFilePath);
}
}
importData(rows: any[], settings: BearableDataImportSettings) {
//console.log("Settings:", settings); // Debugging line
let markdown = ""; // Initialize a variable to store the markdown content
if (settings.importMood) {
markdown += importMoodData(rows); // Assume this function is defined to handle Mood data.
}
if (settings.importEnergy) {
markdown += importEnergyData(rows); // Assume this function is defined to handle Energy data.
}
if (settings.importSleep) {
markdown += importSleepData(rows); // Assume this function is defined to handle SLeep data.
}
if (settings.importHealthMeasurements) {
markdown += importHealthMeasurementsData(rows); // Assume this function is defined to handle Health data.
}
if (settings.importSymptoms) {
markdown += importSymptomData(rows); // Assume this function is defined to handle Symptom data.
}
if (settings.importMeds) {
markdown += importMedsData(rows); // Assume this function is defined to handle Medication & Supplements data.
}
if (settings.importCustomRatings) {
markdown += importCustomData(rows, settings); // Assume this function is defined to handle Custom Ratings data.
}
if (settings.importBm) {
markdown += importBmData(rows); // Assume this function is defined to handle Custom Ratings data.
}
return markdown;
}
parseCSV(data: string): any[] {
//console.log("Raw CSV data:", data); // Log the raw CSV data for debugging
if (!data.trim()) {
console.log("No data to parse. CSV is empty.");
return [];
}
const rows = data.split('\n').slice(1); // Skip the header and split rows
return rows.map(row => {
const values = row.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g); // Handle CSV parsing with regex that accounts for quoted commas
if (!values) {
//console.log("Row could not be parsed:", row);
return null; // Handle rows that might not parse correctly
}
const currentDate = getCurrentDate();
// if ((values[1].toString().replace(/"/g, '')) === currentDate.toString()) {
// console.log("Current date found in CSV data.");
// }
const [date, dateFormatted, weekday, timeOfDay, category, ratingAmount, detail, notes] = values;
if (values[1].toString().replace(/"/g, '') === currentDate.toString()) {
return { date, dateFormatted, weekday, timeOfDay, category, ratingAmount, detail, notes };
}
return null;
}).filter(row => {
if (!row) {
//console.log("Row could not be parsed:", row);
return false;
}
return true;
});
}
updateNoteContent(originalContent: string, newData: string, headerName: string): string {
const header = `## ${headerName}`;
const headerIndex = originalContent.indexOf(header);
if (headerIndex !== -1) {
// Header exists, find the end of the header line
let endOfHeaderIndex = originalContent.indexOf('\n', headerIndex);
endOfHeaderIndex = endOfHeaderIndex === -1 ? originalContent.length : endOfHeaderIndex;
// Find the next header to determine the end of the current section
const nextHeaderIndex = originalContent.indexOf('##', endOfHeaderIndex + 1);
const startOfNextSection = nextHeaderIndex === -1 ? originalContent.length : nextHeaderIndex;
// Replace the existing section with new data, or append if section extends to the end of the content
return originalContent.substring(0, endOfHeaderIndex + 1) + newData +
(nextHeaderIndex !== -1 ? originalContent.substring(startOfNextSection) : "");
} else {
// If the header doesn't exist, append the header and the new data at the end
return originalContent + '\n' + header + '\n' + newData;
}
}
}