Перенес бизнес логику, хы

This commit is contained in:
Кашин Максим 2023-12-26 00:01:44 +04:00
parent 99f294da5d
commit c785a76e03
3 changed files with 103 additions and 82 deletions

View File

@ -1,5 +1,15 @@
package com.example.myapplication.api.item package com.example.myapplication.api.item
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.pdf.PdfDocument
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import com.example.myapplication.api.MyServerService import com.example.myapplication.api.MyServerService
import com.example.myapplication.api.report.ReportRemote import com.example.myapplication.api.report.ReportRemote
import com.example.myapplication.database.entities.model.Item import com.example.myapplication.database.entities.model.Item
@ -7,6 +17,10 @@ import com.example.myapplication.database.entities.repository.OfflineRentItemRep
import com.example.myapplication.database.entities.repository.OfflineItemRepository import com.example.myapplication.database.entities.repository.OfflineItemRepository
import com.example.myapplication.database.entities.repository.OfflineUserItemRepository import com.example.myapplication.database.entities.repository.OfflineUserItemRepository
import com.example.myapplication.database.entities.repository.ItemRepository import com.example.myapplication.database.entities.repository.ItemRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.OutputStream
class RestItemRepository( class RestItemRepository(
private val service: MyServerService, private val service: MyServerService,
@ -53,4 +67,87 @@ class RestItemRepository(
{ {
return service.getReportInfo(fromDate,toDate) return service.getReportInfo(fromDate,toDate)
} }
suspend fun createPdfFile(context: Context, fileName: String, reportData: List<ReportRemote>) {
withContext(Dispatchers.IO) {
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS)
}
val contentResolver: ContentResolver = context.contentResolver
val uri: Uri? = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues)
uri?.let {
try {
contentResolver.openOutputStream(uri)?.use { outputStream ->
createPdfContent(outputStream, reportData)
}
// Optional: Notify MediaStore about the new file
context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
private fun createPdfContent(outputStream: OutputStream, reportData: List<ReportRemote>) {
val pdfDocument = PdfDocument()
val pageInfo = PdfDocument.PageInfo.Builder(595, 842, 1).create()
val page = pdfDocument.startPage(pageInfo)
val canvas = page.canvas
val paint = Paint()
paint.textSize = 16f // Уменьшаем размер шрифта для лучшей видимости
paint.isAntiAlias = true
// Отображаем заголовок
val title = "Отчет"
val xTitle = (pageInfo.pageWidth - paint.measureText(title)) / 2
val yTitle = 40f
canvas.drawText(title, xTitle, yTitle, paint)
// Отображаем данные в виде таблицы
val tableStartY = yTitle + 80f
val columnWidths = floatArrayOf(0.5f, 1.5f, 1f, 1.5f, 1f) // Увеличиваем ширину столбцов
val rowHeight = 30f // Увеличиваем высоту строки
drawTableRow(canvas, arrayOf("ID", "Дата проверки", "Вес", "Количество", "ID велосипеда"), columnWidths, tableStartY, paint)
for ((index, report) in reportData.withIndex()) {
val row = arrayOf(
report.id.toString(),
report.dateTime.toString(),
report.weight.toString(),
report.maxCount.toString(),
report.bikeId.toString()
)
drawTableRow(canvas, row, columnWidths, tableStartY + (index + 1) * rowHeight, paint)
}
pdfDocument.finishPage(page)
pdfDocument.writeTo(outputStream)
pdfDocument.close()
}
private fun drawTableRow(
canvas: Canvas,
row: Array<String>,
columnWidths: FloatArray,
y: Float,
paint: Paint
) {
var x = 40f
for (i in row.indices) {
val text = row[i]
canvas.drawText(text, x, y, paint)
x += columnWidths[i] * 80 // Увеличиваем ширину столбцов
}
}
} }

View File

@ -131,7 +131,7 @@ fun ReportPage (navController: NavController?, viewModel: ReportViewModel = view
Button( Button(
onClick = {coroutineScope.launch { onClick = {coroutineScope.launch {
//viewModel.getReport() //viewModel.getReport()
createPdfFile(context = context, fileName = "отчет.pdf",reportData = reportResultPageState.resReport) viewModel.generatePdfFile(context = context, fileName = "отчет.pdf",reportData = reportResultPageState.resReport)
} }, } },
enabled = viewModel.reportPageUiState.isEntryValid, enabled = viewModel.reportPageUiState.isEntryValid,
modifier = Modifier modifier = Modifier
@ -194,85 +194,4 @@ fun TableScreen(reportData: List<ReportRemote>) {
} }
} }
suspend fun createPdfFile(context: Context, fileName: String, reportData: List<ReportRemote>) {
withContext(Dispatchers.IO) {
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS)
}
val contentResolver: ContentResolver = context.contentResolver
val uri: Uri? = contentResolver.insert(MediaStore.Files.getContentUri("external"), contentValues)
uri?.let {
try {
contentResolver.openOutputStream(uri)?.use { outputStream ->
createPdfContent(outputStream, reportData)
}
// Optional: Notify MediaStore about the new file
context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
private fun createPdfContent(outputStream: OutputStream, reportData: List<ReportRemote>) {
val pdfDocument = PdfDocument()
val pageInfo = PdfDocument.PageInfo.Builder(595, 842, 1).create()
val page = pdfDocument.startPage(pageInfo)
val canvas = page.canvas
val paint = Paint()
paint.textSize = 16f // Уменьшаем размер шрифта для лучшей видимости
paint.isAntiAlias = true
// Отображаем заголовок
val title = "Отчет"
val xTitle = (pageInfo.pageWidth - paint.measureText(title)) / 2
val yTitle = 40f
canvas.drawText(title, xTitle, yTitle, paint)
// Отображаем данные в виде таблицы
val tableStartY = yTitle + 80f
val columnWidths = floatArrayOf(0.5f, 1.5f, 1f, 1.5f, 1f) // Увеличиваем ширину столбцов
val rowHeight = 30f // Увеличиваем высоту строки
drawTableRow(canvas, arrayOf("ID", "Дата проверки", "Вес", "Количество", "ID велосипеда"), columnWidths, tableStartY, paint)
for ((index, report) in reportData.withIndex()) {
val row = arrayOf(
report.id.toString(),
report.dateTime.toString(),
report.weight.toString(),
report.maxCount.toString(),
report.bikeId.toString()
)
drawTableRow(canvas, row, columnWidths, tableStartY + (index + 1) * rowHeight, paint)
}
pdfDocument.finishPage(page)
pdfDocument.writeTo(outputStream)
pdfDocument.close()
}
private fun drawTableRow(
canvas: Canvas,
row: Array<String>,
columnWidths: FloatArray,
y: Float,
paint: Paint
) {
var x = 40f
for (i in row.indices) {
val text = row[i]
canvas.drawText(text, x, y, paint)
x += columnWidths[i] * 80 // Увеличиваем ширину столбцов
}
}

View File

@ -1,5 +1,6 @@
package com.example.myapplication.database.entities.composeui package com.example.myapplication.database.entities.composeui
import android.content.Context
import android.util.Log import android.util.Log
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
@ -40,6 +41,10 @@ class ReportViewModel(private val itemRespository: RestItemRepository): ViewMode
val res = itemRespository.getReport(startDateQueryParam, endDateQueryParam) val res = itemRespository.getReport(startDateQueryParam, endDateQueryParam)
reportResultPageUiState = ReportResultPageUiState(res) reportResultPageUiState = ReportResultPageUiState(res)
} }
suspend fun generatePdfFile(context: Context, fileName: String, reportData: List<ReportRemote>) {
itemRespository.createPdfFile(context, fileName, reportData)
}
} }
data class ReportDetails( data class ReportDetails(