1+ const fs = require ( 'fs' )
2+ const readline = require ( 'readline' )
3+
4+ const rl = readline . createInterface ( {
5+ input : process . stdin ,
6+ output : process . stdout
7+ } )
8+
9+ /*
10+ * EJERCICIO:
11+ * Desarrolla un programa capaz de crear un archivo que se llame como
12+ * tu usuario de GitHub y tenga la extensión .txt.
13+ * Añade varias líneas en ese fichero:
14+ * - Tu nombre.
15+ * - Edad.
16+ * - Lenguaje de programación favorito.
17+ * Imprime el contenido.
18+ * Borra el fichero.
19+ */
20+
21+ fs . writeFileSync ( 'victor-Casta.txt' , 'Victor\n21\nJavaScript' , 'utf8' )
22+ console . log ( fs . readFileSync ( 'victor-Casta.txt' , 'utf8' ) )
23+ fs . unlinkSync ( 'victor-Casta.txt' )
24+
25+ /*
26+ * DIFICULTAD EXTRA (opcional):
27+ * Desarrolla un programa de gestión de ventas que almacena sus datos en un
28+ * archivo .txt.
29+ * - Cada producto se guarda en una línea del archivo de la siguiente manera:
30+ * [nombre_producto], [cantidad_vendida], [precio].
31+ * - Siguiendo ese formato, y mediante terminal, debe permitir añadir, consultar,
32+ * actualizar, eliminar productos y salir.
33+ * - También debe poseer opciones para calcular la venta total y por producto.
34+ * - La opción salir borra el .txt.
35+ */
36+
37+ function promptInput ( question : string ) : Promise < string > {
38+ return new Promise ( ( resolve ) => rl . question ( question , ( input ) => resolve ( input . trim ( ) ) ) )
39+ }
40+
41+ async function addProduct ( ) : Promise < void > {
42+ const name = await promptInput ( 'Nombre del producto: ' )
43+ const quantity = await promptInput ( 'Cantidad vendida: ' )
44+ const price = await promptInput ( 'Precio: ' )
45+
46+ fs . appendFileSync ( 'sales.txt' , `${ name } , ${ quantity } , ${ price } \n` , 'utf8' )
47+ console . log ( '✅ Producto añadido correctamente.' )
48+ salesManagement ( )
49+ }
50+
51+ async function consult ( ) : Promise < void > {
52+ const name = await promptInput ( 'Ingresa el nombre del producto a consultar: ' )
53+
54+ if ( ! fs . existsSync ( 'sales.txt' ) ) {
55+ console . log ( '⚠️ Archivo de ventas no encontrado.' )
56+ return salesManagement ( )
57+ }
58+
59+ const lines = fs . readFileSync ( 'sales.txt' , 'utf8' ) . trim ( ) . split ( '\n' )
60+ const foundProducts = lines . filter ( line => line . toLowerCase ( ) . includes ( name . toLowerCase ( ) ) )
61+
62+ if ( foundProducts . length === 0 ) {
63+ console . log ( '❌ Producto no encontrado en la lista.' )
64+ } else {
65+ foundProducts . forEach ( product => {
66+ const [ productName , quantity , price ] = product . split ( ', ' )
67+ console . log ( `\nNombre: ${ productName } \nCantidad vendida: ${ quantity } \nPrecio: ${ price } ` )
68+ } )
69+ }
70+ salesManagement ( )
71+ }
72+
73+ async function updateProduct ( ) : Promise < void > {
74+ const name = await promptInput ( 'Nombre del producto a actualizar: ' )
75+
76+ if ( ! fs . existsSync ( 'sales.txt' ) ) {
77+ console . log ( '⚠️ Archivo de ventas no encontrado.' )
78+ return salesManagement ( )
79+ }
80+
81+ const lines = fs . readFileSync ( 'sales.txt' , 'utf8' ) . trim ( ) . split ( '\n' )
82+ const productIndex = lines . findIndex ( line => line . toLowerCase ( ) . includes ( name . toLowerCase ( ) ) )
83+
84+ if ( productIndex === - 1 ) {
85+ console . log ( '❌ Producto no encontrado para actualizar.' )
86+ return salesManagement ( )
87+ }
88+
89+ const newQuantity = await promptInput ( 'Nueva cantidad vendida: ' )
90+ const newPrice = await promptInput ( 'Nuevo precio: ' )
91+ lines [ productIndex ] = `${ name } , ${ newQuantity } , ${ newPrice } `
92+
93+ fs . writeFileSync ( 'sales.txt' , lines . join ( '\n' ) , 'utf8' )
94+ console . log ( '✅ Producto actualizado correctamente.' )
95+ salesManagement ( )
96+ }
97+
98+ async function deleteProduct ( ) : Promise < void > {
99+ const name = await promptInput ( 'Ingresa el nombre del producto a eliminar: ' )
100+
101+ if ( ! fs . existsSync ( 'sales.txt' ) ) {
102+ console . log ( '⚠️ Archivo de ventas no encontrado.' )
103+ return salesManagement ( )
104+ }
105+
106+ const lines = fs . readFileSync ( 'sales.txt' , 'utf8' ) . trim ( ) . split ( '\n' )
107+ const filteredProducts = lines . filter ( line => ! line . toLowerCase ( ) . includes ( name . toLowerCase ( ) ) )
108+
109+ if ( filteredProducts . length === lines . length ) {
110+ console . log ( '❌ Producto no encontrado en la lista.' )
111+ } else {
112+ fs . writeFileSync ( 'sales.txt' , filteredProducts . join ( '\n' ) , 'utf8' )
113+ console . log ( '✅ Producto eliminado correctamente.' )
114+ }
115+ salesManagement ( )
116+ }
117+
118+ function displayMenu ( ) : void {
119+ console . log ( '\n--- Gestión de Ventas ---' )
120+ console . log ( '1 - Añadir Producto' )
121+ console . log ( '2 - Consultar Producto' )
122+ console . log ( '3 - Actualizar Producto' )
123+ console . log ( '4 - Eliminar Producto' )
124+ console . log ( '0 - Salir' )
125+ }
126+
127+ async function salesManagement ( ) : Promise < void > {
128+ displayMenu ( )
129+
130+ const option = await promptInput ( 'Seleccione una opción: ' )
131+ switch ( option ) {
132+ case '1' :
133+ await addProduct ( )
134+ break
135+ case '2' :
136+ await consult ( )
137+ break
138+ case '3' :
139+ await updateProduct ( )
140+ break
141+ case '4' :
142+ await deleteProduct ( )
143+ break
144+ case '0' :
145+ console . log ( 'Saliendo del programa...' )
146+ rl . close ( )
147+ fs . unlinkSync ( 'sales.txt' )
148+ break
149+ default :
150+ console . log ( '⚠️ Opción no válida. Intente nuevamente.' )
151+ salesManagement ( )
152+ }
153+ }
154+
155+ salesManagement ( )
0 commit comments